Dilemma related to function call's increment of SP

China☆狼群 提交于 2019-12-11 09:18:23

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/31390228/dilemma-related-to-function-calls-increment-of-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!