MIPS: Why does the my code only sometimes mess up? -
ok,
so have main function does
jal gcd
and have code. it's not indenting whatever reason please bear me.
here's question. reason, when 1 call gcd made (from main), , gcd doesnt branch because $a1 0 , jumps exgcd, when $ra, $a1, $a0 restored, hold $sp's address, , not variables should stored before.
when gcd doesn't branch exgcd on first call, i.e $a1 not 0, loading @ end of recursion works fine , restores proper variables.
why not work in first case?
thank you.
i'd add understand there's no need store $ra, i'm still curious why doesn't work properly.
to try , make question more clear, why doesn't code work:
gcd: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) addi $sp, $sp, 12 lw $ra, 8($sp) # restore lw $a1, 4($sp) lw $a0, 0($sp) jr $ra
full functions:
gcd: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) bne $a1, $0, not0 add $v0, $0, $a0 j exgcd not0: sltu $t0, $a1, $a0 # b<a? beq $t0, $0, bgta sub $t0, $a0, $a1 add $a0, $0, $a1 add $a1, $a0, $0 j gcd bgta: sub $a1, $a1, $a0 j gcd j exgcd exgcd: addi $sp, $sp, 12 lw $ra, 8($sp) # restore lw $a1, 4($sp) lw $a0, 0($sp) jr $ra
you allocate stack space , store function arguments there, fine. when preparing return, though, release stack memory , then try read stored on stack. that's backward. restore original value of $sp
after lw
instructions.
don't read stack locations you've popped.
you're not reading same locations wrote. if locations you're reading happen contain values similar or equal values stored in other locations, program might appear work sometimes, though it's broken.
Comments
Post a Comment