Search code examples
gccassemblymipsmips32stack-pointer

$sp register does not change at the beginning of the function


Linked to: How to get a call stack backtrace?(GCC,MIPS,no frame pointer) I am reproducing the call stack(more details at the link above) by iterating the function using the assembly code and user stack. I have to find the previous $sp for each function, most of the functions start with the following instruction:

addiu sp, sp, -80

I can easily conclude the previous $sp from the opcode. The problem is that I found functions that never changes the $sp even though they use the stack, it seems that the functions that call this kind of functions use the same activation frame on the stack In other words never change $sp. How can I reproduce the previous $sp in this case?


Solution

  • This can happen with optimized code.

    If a leaf function only modifies the temporary registers, and returns to a return statement in its caller's code, then there is no need for $ra to be changed, and there is no need for a stack frame for that function. Example:

    int caller(....) {
      int a, b, c;
      ...
      c = leaf(a,b);
      return c;
    }
    int leaf(int a, int b) {
      return a + b;
    }
    

    See also tail calls.