cs61c_lab3
Exercise 1: Debugging megalistmanips.s
错误之处:
- 偏移量没有乘4。
- 偏移量应该加在结构体中数组的地址上而不是数组的地址的地址上。
- 调用函数之前没有保存s1。
- 在内存中取字应该是lw,而不是la。
- 将s1中的内容移入a1,而不是将s1指向的地址中的内容移入a1。
代码如下:
mapLoop:
# add t1, s0, x0 # load the address of the array of current node into t1
lw t2, 4(s0) # load the size of the node's array into t2
# add t1, t1, t0 # offset the array address by the count
# lw a0, 0(t0) # load the value at that address into a0
addi t1, x0, 4
mul t1, t0, t1
lw t3, 0(s0)
add t1, t3, t1
lw a0, 0(t1)
addi sp, sp, -4
sw t1, 0(sp)
jalr s1 # call the function on that value.
lw t1, 0(sp)
addi sp, sp, 4
addi t1, x0, 4
mul t1, t0, t1
lw t3, 0(s0)
add t1, t3, t1
sw a0, 0(t1) # store the returned value back into the array
addi t0, t0, 1 # increment the count
bne t0, t2, mapLoop # repeat if we haven't reached the array size yet
lw a0, 8(s0) # load the address of the next node into a0
mv a1, s1 # put the address of the function back into a1 to prepare for the recursion
jal map # recurse
done:
lw s0, 8(sp)
lw s1, 4(sp)
lw ra, 0(sp)
addi sp, sp, 12
jr ra
Exercise 2: Write a function without branches
代码如下:
f:
addi a0, a0, 3
addi t1, x0, 4
mul a0, a0, t1
add a0, a1, a0
lw a0, 0(a0)
jr ra
或者:
f:
addi a0, a0, 3
slli a0, a0, 2
add a0, a1, a0
lw a0, 0(a0)
jr ra