25.12.2012 Views

MIPS Assembly Language Programming

MIPS Assembly Language Programming

MIPS Assembly Language Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.1. FUNCTION ENVIRONMENTS AND LINKAGE 45<br />

(a) Put the return value, if any, into register $v0.<br />

(b) Restore callee-saved registers.<br />

(c) Jump back to $ra, using the jr instruction.<br />

5. To clean up after a function call, the caller must:<br />

(a) Restore the caller-saved registers.<br />

(b) If any arguments were passed on the stack (instead of in $a0-$a3), pop<br />

them off of the stack.<br />

(c) Extract the return value, if any, from register $v0.<br />

The convention used by the programs in this document is that a function stores<br />

$fp at the top of its stack frame, followed by $ra, then any of the callee-saved registers<br />

($s0 - $s7), and finally any of the caller-saved registers ($t0 - $t9) that need to be<br />

preserved.<br />

3.1.1 Computing Fibonacci Numbers<br />

The Fibonacci sequence has the following recursive definition: let F (n) be the nth<br />

element (where n ≥ 0) in the sequence:<br />

• If n < 2, then F (n) ≡ 1. (the base case)<br />

• Otherwise, F (n) = F (n − 1) + F (n − 2). (the recursive case)<br />

This definition leads directly to a recursive algorithm for computing the nth Fibonacci<br />

number. As you may have realized, particularly if you’ve seen this sequence<br />

before, there are much more efficient ways to compute the nth Fibonacci number.<br />

Nevertheless, this algorithm is often used to demonstrate recursion– so here we go<br />

again.<br />

In order to demonstrate a few different aspects of the <strong>MIPS</strong> function calling conventions,<br />

however, we’ll implement the fib function in a few different ways.<br />

3.1.1.1 Using Saved Registers: fib-s.asm<br />

The first way that we’ll code this will use callee-saved registers to hold all of the local<br />

variables.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!