Back to Stack Frames. On to Pause For Breath.
Held Wednesday, March 14, 2001
Summary
Today we continue our investigation of stack frames by considering some particular examples.
Due
Notes
Overview
factorial,
so we'll try that first.
function factorial(n: integer): integer;
var
tmp1: integer;
begin
if (n = 0) then
factorial := 1
else
begin
tmp := factorial(n-1);
factorial := n * tmp;
end
end;
+--------------+ <- FP | old FP | +--------------+ | return value | +--------------+ | ret. address | +--------------+ | n | +--------------+ | tmp | +--------------+ | extra | +--------------+ <- SP
factorial look like?
In a generic language with four bytes per word
BEGIN_FACTORIAL: # Do anything appropriate for the beginning of a procedure call ... # if (n = 0) START_FACTORIAL_CODE: COMPARE MEM[SP-12], CONSTANT[0] JUMP IF EQUAL BASE_CASE JUMP RECURSIVE_CASE # factorial := 1 BASE_CASE: STORE INTO MEM[FP+4] FROM CONSTANT[1] JUMP END_FACTORIAL # tmp := factorial(n-1) RECURSIVE_CASE: # Compute n-1 SUBTRACT CONSTANT[1] FROM MEM[SP-12], STORE IN MEM[SP-8] # Call factorial ... # Copy the value back STORE INTO MEM[SP-8] FROM MEM[SP+4] # factorial := n * tmp MULTIPLY MEM[SP-12] BY MEM[SP-8], STORE IN MEM[FP+4] JUMP END_FACTORIAL # Clean up END_FACTORIAL: ...
# Do anything appropriate for the beginning of a procedure call ADD CONSTANT[24] to SP
END_FACTORIAL: SUBTRACT CONSTANT[24] from SP
JMP MEM[SP+8]
STORE INTO MEM[SP+12] FROM MEM[SP-4]
STORE INTO MEM[SP] FROM FP
SET FP to SP
STORE INTO MEM[SP+8], RETURN_HERE
JUMP BEGIN_FACTORIAL RETURN_HERE:
STORE INTO FP FROM MEM[FP]
Back to Stack Frames. On to Pause For Breath.
[Current]
[Discussions]
[Glance]
[Honesty]
[Instructions]
[Links]
[Search]
[Syllabus]
Primary
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Project]
[Quizzes]
[Readings]
[Reference]
Sets
[Blackboard]
[98F]
Links
Disclaimer: I usually create these pages on the fly. This means that they are rarely proofread and may contain bad grammar and incorrect details. It also means that I may update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.
This page was generated by Siteweaver on Mon Apr 30 10:52:03 2001.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS362/2001S/outline.23.html.
You may validate
this page's HTML.
The source was last modified Mon Jan 22 10:39:11 2001.