SP = Stack Pointer, initially very high value Push X means SP=SP-1 then memory[SP]=X FP = Frame Pointer PC = Program Counter, address of next instruction to be executed int ffff(int X, int Y, int Z) { int A, B, C; A = X-Y; B = Y-Z; C = A*B; return A+B+C; } // parameters will have been evaluated and pushed before the call // The CALL instruction also pushes the return address // so stack will be: // memory[SP+4] = (whatever was already on the stack) // memory[SP+3] = value of Z // memory[SP+2] = value of Y // memory[SP+1] = value of X // memory[SP] = return address // memory[SP-1] = (not yet in use) // int ffff(int X, int Y, int Z) // { int A, B, C; // Function Prologue FFFF: PUSH FP STORE SP, FP SUB SP, 3 // total size of local variables // as long as this function is running, the stack will be: // memory[FP+5] = (whatever was already on the stack) // memory[FP+4] = value of Z // memory[FP+3] = value of Y // memory[FP+2] = value of X // memory[FP+1] = return address // memory[FP] = previous saved value of FP // memory[FP-1] = value of A // memory[FP-2] = value of B // memory[FP-3] = value of C // SP = FP-3 currently // memory[SP-1] = (available for anything) // A = X-Y; LOAD R1, [FP+2] SUB R1, [FP+3] STORE R1, [FP-1] // B = Y-Z; LOAD R1, [FP+3] SUB R1, [FP+4] STORE R1, [FP-2] // C = A*B; LOAD R1, [FP-1] MUL R1, [FP-2] STORE R1, [FP-3] // return A+B+C; } LOAD R1, [FP-1] ADD R1, [FP-2] ADD R1, [FP-3] // Function Epilogue ADD SP, 3 // reverses the effect of subtracting in prologue POP FP // recovers saved FP RET // pops return address and jumps back to there. void main() { int M, N; M = 34; N = ffff(M+1, M-1, 19); N = (N+2)*(M-3); } // void main() // { int M, N; // Function Prologue just as before FFFF: PUSH FP STORE SP, FP SUB SP, 2 // total size of local variables // M = 34; LOAD R1, 34 STORE R1, [FP-1] // N = ffff(M+1, M-1, 19); // Pre-Call Sequence PUSH 19 // evaluate and push 3rd param LOAD R1, [FP-1] // evaluate and push 2nd param SUB R1, 1 PUSH R1 LOAD R1, [FP-1] // evaluate and push 1st param ADD R1, 1 PUSH R1 CALL FFFF // push address of next instruction and jump // Post-Call Sequence ADD SP, 3 // equivalent to popping the three params STORE R1, [FP-2] // function's result always returned in R1 // N = (N+2)*(M-3); } LOAD R1, [FP-2] ADD R1, 2 LOAD R2, [FP-1] SUB R2, 3 MUL R1, R2 STORE R1, [FP-2] // Function Epilogue for main just like any other function ADD SP, 2 // reverses the effect of subtracting in prologue POP FP // recovers saved FP RET // pops return address and jumps back to there. // it will in fact jump back to the OS routine // that started this program.