32位整数数组的MIPS指令

MIPS instruction of an array of 32 bits integer

所以我目前被困在一个问题上,我很高兴看到是否有人可以详细说明我的问题。

问题如下

设寄存器$s1为数组A的基数,

注册$v0为变量X,

注册$t0作为索引i,

然后为下面的语句写一条MIPS指令

K = A[i] + A[i+3];

解决方法如下

sll $t1, $t0, 2
add $t2, $s1, $t1
lw $t3, 0($t2)
lw $t4, 12($t2)
add $v0, $t3, $t4

我对这个问题的解答是

addi $t1, $t0, 3  # for the $t1 <- i+3
lw $t2, 0($t1)    # for the $t2 <- A[i+3]
lw $t3, 0($t0)    # for the $t3 <- A[i]
add $v0, $t2, $t3 # for the K <- A[i+3] + A[i]

所以问题是,

我真的不明白为什么解决方案没有将索引添加 3 (i+3) 然后从添加的索引加载。

还有解决方案的第 2 行,添加 $t2、$s1、$t1,如何添加带有索引的基数(即 $t2 <- A+i)? array不代表内存栈,索引作为栈的位置地址吗?

提前致谢。

任何对类似问题的问题的详细说明将不胜感激。

记住A的每个索引不是32位的。 A的每个索引只有8位。上面的代码执行以下操作:

sll $t1, $t0, 2   # take $t0 and shift it over 2 bits
                  # (equivalent to multiply by 4)
add $t2, $s1, $t1 # from the 0 index, add on $t1 to get into the register for A[i]
lw $t3, 0($t2)    # load 4 bytes (the entire 32bits) from A[i]
lw $t4, 12($t2)   # load 4 bytes (the entire 32bits) from A[i + 3] 
                  # where 3 is actually 12 because it's 8bits per index
                  # so multiply by 4
add $v0, $t3, $t4

要实现的重要事情是 "array."

的 8 位(字节)与 32 位(字)索引

查看您的代码:

addi $t1, $t0, 3  # actually just moves this over 3 bytes, not 3 words
lw $t2, 0($t1)    # gets the word at A[i / 4]
lw $t3, 0($t0)    # gets the word at A[(i + 3) / 4]
add $v0, $t2, $t3 # and now you can see why this would be wrong.