CS270 Colorado State University ==================== Run-time Stack ==================== Ch. 14 and 16 Issues discovered - If each function only has one place to store registers, then it is not possible to use that function recursively. - There are not enough registers to always use registers to pass all of the parameters. Solution Use run-time stack to implement function calls. Each function instance will have an activation record on the stack values for formal parameters LC3: location for return value stored register values locations/slots for local variables stack grows to lower memory stack pointer frame pointer ------------------- Terminology function prototypes declaration versus definition formal parameters and arguments ----------------------------------- Goal in implementing function calls caller-independence calling convention implementation requirements for function calls 1) pass parameters and return values 2) call and return ---------------------- LC3 calling convention General - stack pointer (R6) always points at top location in stack Caller before call - push arguments onto stack right-to-left after call - pop return value off the stack - pop arguments off the stack Callee - save and restore R7 and R5 - place return value at top of stack on top of arguments - do NOT modify R4 - keep R6 pointing at top of stack Full details of callee, one possible implementation of the above calling convention beginning of function (prologue) - allocate memory for return value - save and restore R7 and R5, push R7 and R5 onto stack - set the frame pointer so that it will point at first local - allocate space for locals end of function (epilogue) - write return value in return value slot - pop local values off the stack - restore frame pointer (R5) by popping it off stack ------- Example int main() { int y = foo(1,2,3); int z = foo(4,5,6); printf( "%d\n", baz() ); } int foo(int p1, int p2, int p3) { bar(p1); bar(p2); bar(p3); return 77; } void bar(int x) { printf("%d\n", x + baz() ); } int baz() { return 7; } Invocation graph The run-time stack for the call path: main, foo(1,2,3), bar(p1), baz() ------------------- Register management R0-R3 -- 4 temporary registers, no convention specified R4 -- points to first address in global data section R5 -- frame pointer, callee-saved R6 -- stack pointer, should always point at top entry in stack R7 -- return address, callee-saved dynamic link ----------------------------- Implementing the stack in LC3 ------------------------ mstrout@cs.colostate.edu, 11/2/08