12.2.3.2 The C Stack Usage

The C compiler uses the software stack to:

  • Allocate automatic variables
  • Pass arguments to functions
  • Save the processor status in interrupt functions
  • Save function return address
  • Store temporary results
  • Save registers across function calls

The run-time stack grows upward from lower addresses to higher addresses. The compiler uses two working registers to manage the stack:

  • W15 – This is the Stack Pointer (SP). It points to the top of stack which is defined to be the first unused location on the stack.
  • W14 – This is the Frame Pointer (FP). It points to the current function’s frame. Each function, if required, creates a new frame at the top of the stack from which automatic and temporary variables are allocated. The compiler option -fomit-frame-pointer can be used to restrict the use of the FP.
    Figure 12-1. Stack and Frame Pointers

The C run-time startup modules in libpic30-omf.a initialize the Stack Pointer W15 to point to the bottom of the stack and initialize the Stack Pointer Limit register to point to the top of the stack. The stack grows up and if it should grow beyond the value in the Stack Pointer Limit register, then a stack error trap will be taken. The user may initialize the Stack Pointer Limit register to further restrict stack growth.

The following diagrams illustrate the steps involved in calling a function. Executing a CALL or RCALL instruction pushes the return address onto the software stack.

Figure 12-2. CALL or RCALL

The called function (callee) can now allocate space for its local context.

Figure 12-3. Callee Space Allocation

Any callee-saved registers that are used in the function are pushed.

Figure 12-4. Push Callee-Saved Registers