wys的个人博客

你有很多事放不下?做人要潇洒一点~

0%

cs61c_lab4

cs61c_lab4

Exercise 1: Debugging megalistmanips.s

错误之处:

  1. 偏移量没有乘4。
  2. 偏移量应该加在结构体中数组的地址上而不是数组的地址的地址上。
  3. 调用函数之前没有保存s1。
  4. 在内存中取字应该是lw,而不是la。
  5. 将s1中的内容移入a1,而不是将s1指向的地址中的内容移入a1。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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

代码如下:

1
2
3
4
5
6
7
f:
addi a0, a0, 3
addi t1, x0, 4
mul a0, a0, t1
add a0, a1, a0
lw a0, 0(a0)
jr ra

或者:

1
2
3
4
5
6
f:
addi a0, a0, 3
slli a0, a0, 2
add a0, a1, a0
lw a0, 0(a0)
jr ra