问题
I am having trouble translating this pseudo code to mips assembly i have added the registers i am using to help understand what is going on
# if (n == 1)
# return 1
# else if (n == 2)
# return 6
# else
# return 2*hex(n-1) - hex(n-2) + 4
# (hex) Registers:
# $a0 - n, the argument
# $v0 - the result the n-th Hexamorphic number
# $t0 - holds hex(n-2)
# $t1 - holds constants 1
# $t2 - holds constant 2
here is where i am at in my code i feel confident about hex: and elseif: but the else: is where the problem starts
hex: bne $a0,$t1,elseif #if n==1
li $t1,1
li $t2,2
li $v0,1
jr $ra #retu
elseif: bne $a0, $t2,else
li $v0,6
jr $ra
else: addi $sp,$sp,-12
sw $ra,$ra 0($sp)
addi $t3,$a0,-1
sll $t3, $t2,1
sw $a0,$a0,4($sp)
sw $t3,8($sp)
lw $ra
lw $a0
addi $t3,4
sub $t4,$t3,$t0
lw $t4
sw $v0,$t4
lw $ra
lw $a0
j $ra
回答1:
You have some instructions wrong (sw
, lw
, addi
and j
). The definitions of these intstructions can be found in the MIPS32 instruction set quick reference.
You're on the right track in the else block. What you want to do is save all the values (on the stack) that you want to be preserved throughout your recursive calls. jal
to hex (n - 1), save it on the stack and jal
to hex again (n - 2). Then load up all values, do the calculations on them and jr ra
. Do not forget to restore $sp before returning. When using jal
, remember the branch delay:
jal hex
The instruction here will be run "together" with jal, before taking the branch.
ra will point here
The jr $ra
in elseif will run addi $sp,$sp,-12
due to branch delay. This is not good.
来源:https://stackoverflow.com/questions/15119808/mips-translating-problems