Basic Guarantees C and the Stack 1 Right
Basic Guarantees C and the Stack 1 Right off the bat… what I'm going to describe is what almost certainly happens on contemporary machines, but there is absolutely nothing in the C Standard about the runtime stack. Variables with automatic storage duration have their storage space (memory) allocated when the surrounding block is executed and deallocated when the block terminates. That includes function parameters and local non-static variables: void Bubble. Sort(int* L, int Sz) { int Stop, Curr, Next, Temp; . . . } CS@VT November 2009 // local variables Computer Organization I © 2006 -09 Mc. Quain, Feng & Ribbens
Runtime Stack and Function Calls C and the Stack 2 The system maintains a stack structure for each running process that is used to manage function calls. When a function is called, an activation record for that call is created and pushed on the top of the stack. The activation record contains storage space for automatic variables, and typically also for the return value (if any) and the return address: void Bubble. Sort(int* L, int Sz) { int Stop, Curr, Next, Temp; . . . } // local variables Temp Next Curr Stop Sz L return address The assembly code to create the activation record is generated automatically by the C compiler. CS@VT November 2009 Computer Organization I © 2006 -09 Mc. Quain, Feng & Ribbens
Runtime Stack and Function Calls #define SZ 1000. . . int List[SZ]; . . . Bubble. Sort(List, SZ); void Bubble. Sort(int* L, int Sz) { int Stop, Curr, Next, Temp; . . . } la lw addi sw addi $s 0, $s 1, $sp, $s 0, $sp, jal Bubble. Sort # call procedure lw addi. . . $s 2, 0($sp) $sp, 28 # retrieve ret value # pop activation record CS@VT November 2009 List SZ $sp, -16 $sp, -4 0($sp) $sp, -4 C and the Stack 3 # # # # // local variables fetch array pointer and array dimension alloc space for locals alloc space for SZ put SZ onto stack alloc space for array ptr put array ptr onto stack alloc space for ret value Computer Organization I Temp Next Curr Stop SZ L return address © 2006 -09 Mc. Quain, Feng & Ribbens
Making It Real (for MIPS) C and the Stack 4 The example code on the previous slide violates some of the MIPS conventions: - the stack pointer convention isn't followed strictly - argument-passing conventions are violated - what code should a MIPS C compiler generate in order to conform to the earlier discussions? ? CS@VT November 2009 Computer Organization I return address Stop Curr Next Temp © 2006 -09 Mc. Quain, Feng & Ribbens
- Slides: 4