Search code examples
pointersoperating-systemstackmipsfunction-calls

Dilemma related to function call's increment of SP


In case of push during function call, why the stack pointer moves to a smaller value by subtracting 4 times the number of registers to be pushed on the stack?

I got this while reading Understanding the stack


Solution

  • In the same page, it is clearly mentioned about the memory layout of stack :-

    It's useful to think of the following aspects of a stack.

    stack bottom The largest valid address of a stack. When a stack is initialized, the stack pointer points to the stack bottom.

    stack limit The smallest valid address of a stack. If the stack pointer gets smaller than this, then there's a stack overflow (this should not be confused with overflow from math operations).

    Other sections of memory are used for the program and for the heap (the section of memory used for dynamic memory allocation).

    And, talking about the PUSH operation, subtracting 4 times the number of registers to be pushed on the stack is needed because in MIPS architecture, addresses of sequential words differ by 4. And, the registers are 32 bits(4 bytes) for MIPS I instruction set architecture (ISA) and II ISA.

    For our stack of 4-byte (full word) data, adding an item means subtracting four from $sp and storing the item in that address.

    Here is what that looks like in code. Say that the value to push on the stack is in register $t0:

    # PUSH the item in $t0:
    subu $sp,$sp,4      #   point to the place for the new item,
    sw   $t0,($sp)      #   store the contents of $t0 as the new top.
    

    And, so, you can push one or more registers, by setting the stack pointer to a smaller value (usually by subtracting 4 times the number of registers to be pushed on the stack) and copying the registers to the stack.