lw in MIPS (also a bit C)
I have a homework question and it is troubling me. It goes like
sll $t0, $s0, 2 // $t0 = $s0 << 2;
add $t1, $t0, $s2 // $t1 = $t + $s2;
lw $s3, $0($t1)
I'm confused about the $0
, does it have the same effect as 0?
What value would the result give?
It is a question asking me to translate mips into c, where $s0 is represented as variable name a, $s1 b, $s2 c etc.
The answer for this section is supposed to be d = c[开发者_如何学Pythona];
,
but i really dont see why.
In MIPS, $0
or $zero
is the 0th indexed and first register, and has value 0. See here.
Although that looks like a typo, since lw
uses a 16-bit offset, which isn't the value from a register but rather a constant (recall that a register is 32 bits). So it should actually be lw $s3, 0($t1)
.
The reason the code performs d = c[a]
might seem simpler if I translate the MIPS into pseudo C-code:
$t0 = a*4
$t1 = $t0 + c (= c + a*4)
d = *(c + a*4)
So we end up loading into d
the value in memory at location c + 4a
, which is the base address of the array c
, and the index of the element we want, a
. We multiply by four because the type of the array is obviously a 4-byte long type, for example a 4-byte integer, so we need to jump 4*a
bytes from the beginning of the array to reach the appropriate point in memory.
精彩评论