有谁知道如何将其转换为mips 32?请出示代码并为我解释。非常感谢你
int service (int n) {
if (n <= 10)
return n;
else
return n + service(n+1) + service (n+2);
}
答案 0 :(得分:0)
请注意评论,并尝试按说明理解正在发生的事情。
service:
lw $t0, $a0 # Load word from memory to $t0. $a0 is the argument of the function (int n).
addi $t1, 10 # $t1 = 10
bne $t0, $t1, cont # If n != 10 , continue
slti $t2, $t1, $t0 # If 10 < n $t2 = 1, else $t2 = 0
bne $t2, $t0, cont # If $t2 != 0 , then $t2 = 1 so 10 < n , so continue
addi $v0, $t0, $0 # Else return n;
jr $ra
cont:
addi $sp, $sp, -4 # Room on stack for 4 bytes
sw $ra, 0($sp) # Save $ra, recursion
addi $a0, $a0, 1 # n+1
jal service # Call service(n+1)
addi $a0, $a0, 1 # (n+1) + 1 = n+2
jal service # Call service(n+2)
lw $ra, 0($sp) # restore $sp
addi $sp, $sp, 4 # Restore room on stack
jr $ra
答案 1 :(得分:0)
这是我的澄清尝试
# assuming $a0 is the parameter n
service:
bgt $a0, 10, else # if $a0 > 10 branch to else part
move $v0, $a0 # $v0 = $a0, to return the value
jr $ra # return n;
else:
addiu $sp, $sp, -8 # using stack to store $ra, $a0 each 4 bytes we need 8 bytes
sw $a0, 0($sp) # store the value of a0 in the stack
sw $ra, 4($sp) # store the caller addrs.
addiu $a0, $a0, 1 # parameter of the first function call (n+1)
jal service # service(n+1)
move $s0, $v0 # s0 = result of service(n+1)
lw $a0, 0($sp) # $a0 = n
addiu $a0, $a0, 2 # parameter of the second function call (n+2)
jal service # service(n+1)
move $s1, $v0 # s1 = result of service(n+1)
lw $a0, 0($sp) # $a0 = n
addu $v0, $a0, $s0 # $v0 = n + service(n+1)
addu $v0, $v0, $s1 # $v0 = n + service(n+1) + service(n+2)
lw $ra, 4($sp) # $ra = old caller return addrs.
addiu $sp, $sp, 8 # freeing the stack
jr $ra # return