问题
My professor gave a video that looks like this:
In the lower right, he wrote $ra
at location 124 while the $sp
is at 128 which implies that the first sw $ra, 4($sp)
instruction stores the $ra
value at a location 4 bytes less than the $sp
. But my book does it differently:
and
The image implies that the lw instruction stores it at locations larger, more positive numbers than the $sp
. So which is right? Does lw and sw offset numbers refer to numbers higher or lower than the $sp
?
回答1:
You are right in observing that the first factorial is storing above the stack pointer, stack storage that it did not allocate, and must have been allocated by the caller.
This is somewhat non-standard usage, but technically legal, since the MIPS calling convention requires giving the top 4 stack locations of any stack frame to the callee. The function is only allocating a 2-word frame, and according to the calling convention (which allows the callee to use the top 4 words of the frame) it should be allocating minimally a 4-word frame.
Still, since the factorial function calls no other except itself, this is ~legal, and in compliance with the calling convention — in the sense that its job is to ensure that one function can call another.
(Note that in RISC V (the open source MIPS follow-on) this requirement of 4-words stack frame for callee to use is not present so similar would not work there.)
The second example is more traditional, however, it also does not allocate a standard sized frame — one that gives the top 4-words to the callee. Still it is also not technically necessary, and less reliant on the original caller (e.g. main
) providing a proper stack frame (one with 4 words given to the callee).
Let's further observe that the first code sample stores $ra
and $a0
on the stack, which are registers that we expect to be saved — whereas the latter example stores $s0
(which we would expect to be saved as these are dedicated non-volatile), but also $t0
and $t1
which seems non standard as these are dedicated temporaries.
来源:https://stackoverflow.com/questions/58325075/does-sw-and-lw-in-mips-store-a-value-below-or-above-the-stack-pointer