CS61C Spring 1999

Section 23 TA: Gek Siong Low (cs61c-tb)

Things to consider when writing a MIPS function

1. Allocate registers

Which registers am I using? Which variables do they map to? This decision will affect which registers I need to save on the stack, and when I need to update/reload them.

2. Am I caller or callee or both?

If I am going to call some other function, I need to save registers on the stack, especially $ra.

3. Before calling other functions, think:

What registers do I need to use after jal? Are they preserved? MIPS convention guarantees only $s registers and $sp are preserved. Other registers you must save them prior to the jal (even if you know they are not used by the function you are calling), and restore them after that function has returned.

4. Before returning to the caller:

Restore the registers first, especially $ra (if you saved it). This is the #1 reason why your program hangs. Then restore the stack pointer (count carefully!) This is probably the #2 reason.

5. Within a loop

If I am reloading certain registers from the stack while in a loop (because I am calling some functions within it), if I change their values, I must also update the ones on the stack. Otherwise I may well go into an infinite loop.

If I am reloading certain registers all the time in a loop, I may be better off by putting them in saved registers instead. Then all I need to do is to save those $s registers at the start of the function, and restore them at the end, instead of reloading my registers every iteration of the loop.

6. Rule of thumb for selecting $s or $t registers

$s registers are a good choice most of the time since you just need to save them on the stack once at the start and restore them once at the end. It's best to use $t registers for really temporary stuff, because every time you call some other function you must save/reload $t registers, unless you don't need the value anymore.

7. Arguments

Just a reminder: First 4 arguments are placed in $a0-$a3, the rest on the stack

The $fp register can be used to mark the spot where arguments end and local variables begin, but if you use it you must also remember to save/restore $fp when you call some other function, because the other function can use $fp as well.

8. Arrays in C

Arrays in C are passed by reference. There is a difference between a[100] and a[] (local variables). a[100] is an element on the stack, or if it is part of a declaration, an allocation of the stack space for the array. a[] is the address of the first element of the array, i.e. &a[0]. Same goes for just plain a.

Written by: Gek Siong Low (cs61c-tb), Spring 1999