Question

MIPS (MARS CODE) Please covert this C++ code to MIPS code and leave comments on each...

MIPS (MARS CODE) Please covert this C++ code to MIPS code and leave comments on each line to what it does!

int fib( int n )

{

if ( n <= 1 )

return n;

else

return fib(n - 1 ) + fib( n - 2 );

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

there are two recursive calls in the function. we need to save the result of first fib before calling it again

1. give register names to variables and determine which is base case and which is recursive. Only single input, n is passed in register $a0. The base case is the “then” clause. The recursive case is the “else” clause.

2. Convert the code for the base case.

  fib:

bgt $a0, 1, recurse

move $v0, $a0

jr $ra

3. Save callee- and caller-saved registers on the stack for not calling again and to know who called whom.

recurse:

sub $sp, $sp, 12 # We need to store 3 registers to stack

sw $ra, 0($sp) # $ra is the first register

sw $a0, 4($sp) # $a0 is the second register, we cannot assume

# $a registers will not be overwritten by callee

4. calling fib recursively

  addi $a0, $a0, -1 # N-1

  jal fib

sw $v0, 8($sp) # store $v0, the third register to be stored on

  # the stack so it doesn’t get overwritten by callee

5. Call fib recursively again.

lw $a0, 4($sp) # retrieve original value of N

addi $a0, $a0, -2 # N-2

  jal fib

6. Clean up the stack and return the result.

  lw $t0, 8($sp) # retrieve first function result

add $v0, $v0, $t0

  lw $ra, 0($sp) # retrieve return address

addi $sp, $sp, 12

jr $ra

Add a comment
Know the answer?
Add Answer to:
MIPS (MARS CODE) Please covert this C++ code to MIPS code and leave comments on each...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT