Subroutines in MIPS — theory with a turn-based fight, jal and jr $ra, the stack with $sp and a combo that calls itself (and the weapon it kept asking me for)
Sixth IC1 lab session. I already knew how to read from the keyboard, and I had seen the loop that removes the \n from read_string so many times that I copied it without thinking. For the fight I needed three names: the hero, the enemy and the weapon. So I copied the loop three times, changing the labels: q1/f1, q2/f2, q3/f3. This is what I wrote:
# hook.s: the names for the fight (the '\n' loop copied three times)
.data
hero: .space 16 # buffer: up to 15 characters + '\0'
rival: .space 16
weapon: .space 16
ph: .asciiz "Hero: "
pr: .asciiz "Enemy: "
pw: .asciiz "Weapon: "
vs: .asciiz " versus "
with: .asciiz " with "
.text
.globl main
main: la $a0, ph # --- 1. the hero ---
li $v0, 4 # print_string
syscall
la $a0, hero
li $a1, 16
li $v0, 8 # read_string
syscall
la $t0, hero # remove its '\n' (first copy)
q1: lbu $t1, 0($t0)
beq $t1, 10, f1 # 10 = '\n'
beqz $t1, f1 # '\0': there was no newline
addi $t0, $t0, 1
j q1
f1: sb $zero, 0($t0)
la $a0, pr # --- 2. the enemy ---
li $v0, 4
syscall
la $a0, rival
li $a1, 16
li $v0, 8
syscall
la $t0, rival # second copy: q1 -> q2, f1 -> f2
q2: lbu $t1, 0($t0)
beq $t1, 10, f2
beqz $t1, f2
addi $t0, $t0, 1
j q2
f2: sb $zero, 0($t0)
la $a0, pw # --- 3. the weapon ---
li $v0, 4
syscall
la $a0, weapon
li $a1, 16
li $v0, 8
syscall
la $t0, weapon # third copy...
q3: lbu $t1, 0($t0)
beq $t1, 10, f2 # ...and this f2 didn't get changed
beqz $t1, f3
addi $t0, $t0, 1
j q3
f3: sb $zero, 0($t0)
la $a0, hero # --- 4. the banner ---
li $v0, 4
syscall
la $a0, vs
syscall
la $a0, rival
syscall
la $a0, with
syscall
la $a0, weapon
syscall
li $v0, 10 # exit
syscall
I loaded it, pressed F5, typed Kira, Rey Slime and Sword… and the console asked me for the weapon again. And again. And again:
Hero: Kira Enemy: Rey Slime Weapon: Sword Weapon: Sword Weapon: Sword Weapon:
QtSpim waited for a new weapon every time I pressed Enter. What had happened? In the third copy I changed q2 to q3 and the f2 of the beqz to f3… but I missed the one in beq $t1, 10, f2. So, when it found the \n of the weapon, the program jumped to f2, the label of the second loop, wrote the '\0' and carried on with whatever came after f2: the weapon question! An infinite loop I had built myself with copy and paste.
That lesson is the idea behind this whole topic: if a piece of code repeats, you write it once and call it. That is a subroutine. Today we learn to call it with jal and come back with jr $ra, to pass arguments in $a0–$a3 and collect results in $v0 and $v1, the $t versus $s convention (who saves what), the stack with $sp to save registers, the difference between leaf and non-leaf subroutines, recursion and local data on the stack. I’m coming from System calls in MIPS, so I’ll take syscalls, read_string and its \n as known. The running example is a turn-based fight between Kira and a slime, and everything is tested in QtSpim (if you don’t have it handy yet, see how to use QtSpim). At the end you have the site’s MIPS environment embedded.
Table of Contents
Before you start. You need three things from the earlier topics. First, lw and sw with an offset: 4($sp) is “the word that starts 4 bytes above the address held in $sp“, from Load, arithmetic and logic in MIPS. Second, that all a jump does is change the address of the next instruction to run, from Branches, conditionals and loops in MIPS. Third, syscalls and the newline that read_string leaves behind, from MIPS system calls. The topic goes in this order: first, what a subroutine is and how you go there and back (jal and jr $ra); then, where the data comes in and where the results go out ($a and $v); next, who has to look after each register ($t versus $s); and with that, the stack, which is where you keep whatever must not get lost, with its three uses: subroutines that call others, recursion and local data. If you get lost, go back to the same question every time: which value do I need after this jal, and where is it kept in the meantime?
What a subroutine is
A subroutine (or procedure) is a self-contained piece of code that does one specific job and can be called from several places. Whoever calls it gives it the data, it does its work and hands control back (and, if needed, a result) right where it was called. In C it would be a function; in MIPS it is a label, some instructions and a jr $ra at the end.
This is the same program as the hook, with the \n loop written only once, as a subroutine strip_nl:
# call.s: the '\n' loop written only once, as a subroutine
.data
hero: .space 16
rival: .space 16
weapon: .space 16
ph: .asciiz "Hero: "
pr: .asciiz "Enemy: "
pw: .asciiz "Weapon: "
vs: .asciiz " versus "
with: .asciiz " with "
.text
.globl main
main: la $a0, ph # --- the hero ---
li $v0, 4
syscall
la $a0, hero
li $a1, 16
li $v0, 8 # read_string
syscall
la $a0, hero # argument: the string
jal strip_nl # going: $ra = the instruction below
la $a0, pr # --- the enemy ---
li $v0, 4
syscall
la $a0, rival
li $a1, 16
li $v0, 8
syscall
la $a0, rival
jal strip_nl # the same subroutine, another string
la $a0, pw # --- the weapon ---
li $v0, 4
syscall
la $a0, weapon
li $a1, 16
li $v0, 8
syscall
la $a0, weapon
jal strip_nl
la $a0, hero # --- the banner ---
li $v0, 4
syscall
la $a0, vs
syscall
la $a0, rival
syscall
la $a0, with
syscall
la $a0, weapon
syscall
li $v0, 10 # exit
syscall
# strip_nl: changes the '\n' at the end of a string to '\0'
# Input: $a0 = address of the string. Uses $t0 and $t1. Returns nothing.
strip_nl:
move $t0, $a0 # $t0 walks through the string
qn_look:
lbu $t1, 0($t0)
beq $t1, 10, qn_strip # 10 = '\n'
beqz $t1, qn_end # '\0': there was no newline
addi $t0, $t0, 1
j qn_look
qn_strip:
sb $zero, 0($t0) # the '\n' becomes the end
qn_end: jr $ra # back: to the address saved in $ra
With the same three inputs, the output is the one I wanted from the start:
Hero: Kira Enemy: Rey Slime Weapon: Sword Kira versus Rey Slime with Sword
Look at what has changed. Before each call I put in $a0 the address of the string in question (hero, rival or weapon); then, jal strip_nl. The subroutine knows nothing about heroes or weapons: it gets an address, looks for the \n and changes it to '\0'. If tomorrow the loop has a bug, it gets fixed in a single place. And there are no q1, q2 or q3 to change by hand any more.
The lab manual gives four reasons to use subroutines, and all four show up in this example:
- Shorter programs: the loop appears once, not three times.
- Easier to fix: a change in
strip_nlworks for every call. - They save registers: the subroutine uses
$t0and$t1only while it works. - Modular development: someone else can write
strip_nlwithout knowing the rest of the program, just its “contract” (what it gets and what it does).
That is why every subroutine in this article starts with a two-line comment: what it does, what it gets, what it returns and which registers it uses. In the exam it is the first thing the marker looks at.
Every call follows the same six steps (the ones in the lecture notes):
- Put the parameters where the subroutine expects them (
$a0–$a3). - Transfer control to the subroutine (
jal). - Reserve space if it needs it (on the stack).
- Do its work.
- Leave the results where the caller expects them (
$v0,$v1). - Go back to the place of the call (
jr $ra).
main is a subroutine too: QtSpim’s start-up code calls it with jal main. That is why programs end with li $v0, 10 + syscall and not with jr $ra: we overwrite main‘s $ra at the first jal.
jal and jr $ra: there and back
How does strip_nl know where to go back to if it is called from three different places? The answer is in jal (jump and link). It does two things at once:
- It saves in
$ra(return address, register 31) the address of the instruction after thejal. - It jumps to the label.
And jr $ra (jump register) copies the value of $ra into the program counter, so execution carries on right after the jal that made the call. Look at it in the text segment of call.s, as QtSpim shows it:
[00400044] 3c041001 lui $4, 4097 [hero] ; 20: la $a0, hero # argument: the string [00400048] 0c10003c jal 0x004000f0 [strip_nl] ; 21: jal strip_nl # going: $ra = the instruction below [0040004c] 3c011001 lui $1, 4097 [pr] ; 22: la $a0, pr # --- the enemy ---
The jal is at 0x00400048; each instruction takes 4 bytes, so the next one is at 0x0040004c, and that is what ends up in $ra. If you stop the program on entering strip_nl (with a breakpoint) in each of the three calls, $ra holds different things:
| Call | The jal is at | $ra on entering strip_nl |
|---|---|---|
| 1 (hero) | 0x00400048 | 0x0040004c |
| 2 (enemy) | 0x00400078 | 0x0040007c |
| 3 (weapon) | 0x004000a8 | 0x004000ac |
The subroutine is the same one, at 0x004000f0, but each time it goes back to a different place. It doesn’t know who called it: it just looks at $ra.
One call, instruction by instruction
First, in words. The processor has a special register, the program counter (PC), holding the address of the instruction that runs next. Normally it moves on 4 at a time; all a jump does is write a different address into it. jal is a jump that, before jumping, notes down in $ra the place it will have to come back to, like slipping a bookmark in before you go and look something up in the glossary. jr $ra is the trip back: it copies the bookmark into the PC. Neither of them looks at who is calling whom: jal writes the address right after it, and jr reads whatever is in $ra at that moment.
This is how the first call in call.s goes, with Kira already in the buffer. The PC column is the address of the next instruction to run:
| Moment | PC | $ra | Why |
|---|---|---|---|
Just before the jal | 0x00400048 | 0x00400018 | $ra still holds main‘s way back to the start-up code, which called it with the jal main at 0x00400014 |
After jal strip_nl | 0x004000f0 | 0x0040004c | Two things at once: $ra = 0x00400048 + 4, and the PC jumps to the label |
During the qn_look loop | From 0x004000f4 to 0x00400108 | 0x0040004c | It walks through K, i, r and a up to the newline; nothing in the body writes to $ra |
After sb $zero, 0($t0) | 0x00400110 | 0x0040004c | The newline is now '\0'; next comes the jr |
After jr $ra | 0x0040004c | 0x0040004c | Copies $ra into the PC; $ra doesn’t change |
Look at the $ra column: it only changes in the jal row. If there were another jal inside strip_nl, the 0x0040004c would disappear. That is the problem the stack solves, further down.
Check you’ve got it: right after the jr $ra of the third call, what is $ra?
0x004000ac, the same as on entry. jr $ra reads $ra, it doesn’t write it: it only copies its value into the PC. That is why the value stays there until the next jal, and why a second jr $ra with no jal in between would go back to the same place again. It is exactly what happens to the broken turn further down, which jumps to tu_back over and over.
Calling with j strip_nl instead of jal strip_nl. j jumps but doesn’t touch $ra, so the jr $ra at the end goes back to wherever $ra last pointed. If it is the program’s first call, $ra still holds main‘s way back to the start-up code.
jal is a J-format instruction (like j) and jr is R-format. jr also lets you jump to a computed address, for example with a table of code addresses in a switch. How they are encoded comes in the instruction set topic.
Arguments and results: $a0-$a3 and $v0-$v1
strip_nl got one value and returned nothing. Normally a subroutine gets several and returns something. The MIPS convention says where each thing goes:
- Arguments:
$a0,$a1,$a2and$a3, in that order. If more are needed, they go on the stack (or you pass the address of an array holding them all). - Results:
$v0and, if there are two, also$v1.
In the fight, an attack needs three values (Kira’s attack, the slime’s defence and its life) and produces two (the life it has left and the damage done):
# convention.s: three arguments in $a0-$a2 and two results in $v0 and $v1
.data
tdmg: .asciiz "Damage: "
tlife: .asciiz " Enemy life: "
nl: .asciiz "\n"
.text
.globl main
main: li $a0, 14 # Kira's attack
li $a1, 5 # the slime's defence
li $a2, 40 # the slime's life
jal attack
move $s0, $v0 # new life: out of $v0 straight away
move $s1, $v1 # damage
jal report
li $a0, 4 # a weak hit: attack 4
li $a1, 5 # against the same defence
move $a2, $s0 # on the life it had left
jal attack
move $s0, $v0
move $s1, $v1
jal report
li $v0, 10 # exit
syscall
# attack: damage = attack - defence (at least 1); life = life - damage (at least 0)
# Input: $a0 = attack, $a1 = defence, $a2 = life. Output: $v0 = new life, $v1 = damage
attack: sub $v1, $a0, $a1 # damage
bgt $v1, 0, at_sub # if it's positive, fine
li $v1, 1 # a hit always takes 1
at_sub:
sub $v0, $a2, $v1 # life - damage
bge $v0, 0, at_end
li $v0, 0 # life doesn't go below 0
at_end: jr $ra
# report: prints "Damage: X Enemy life: Y" with $s1 = damage and $s0 = life
report:
la $a0, tdmg
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
la $a0, tlife
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
la $a0, nl
li $v0, 4
syscall
jr $ra
Damage: 9 Enemy life: 31 Damage: 1 Enemy life: 30
Let’s check the sums. First hit: 14 − 5 = 9 damage and 40 − 9 = 31 life. Second hit: 4 − 5 = −1, which is not a valid damage, so the rule raises it to 1; and 31 − 1 = 30. Both outputs add up.
Why the move $s0, $v0 right after the jal? Same reason as in the previous topic: $v0 is also the syscall code register. If I called report before copying the result, its first li $v0, 4 would wipe it. Whatever a subroutine returns in $v0/$v1 gets moved out of there straight away.
And why does report read from $s0 and $s1 and not from $a0? Because report needs $a0 for its own syscalls. There is a catch here that you will see in the notes and the manual: the convention says where arguments and results go, but it doesn’t force anything else. report could get the damage in $a0 and the life in $a1 and copy them somewhere else before printing. I preferred to have it use main‘s $s so the example stays short; in the practice you’ll see the cleaner way.
A subroutine can return a value or an address. Both appear in the lab manual:
| It returns… | Example | When it is handy |
|---|---|---|
A value in $v0 | attack: the life left | When the caller only cares about the number |
Two values in $v0 and $v1 | attack: life and damage; or a quotient and its remainder | When the job produces two values at once |
An address in $v1 (or $v0) | the manual’s r_maximo: where the largest is | When the caller wants to change that value in memory (swap it, wipe it) |
| Nothing (it changes memory) | strip_nl: writes the '\0' | When the result is a string or an array |
To pass a whole array you don’t need one register per element: its address in $a0 and its length in $a1 are enough. Another way the manual uses is to store the length in the array’s first word (.word 3, 5, 2, 7: three elements, 5, 2 and 7); then the subroutine only needs the address.
$t versus $s: who saves what
Now the turn-based fight. main keeps count of the turn, prints the slime’s life as a bar of # and takes 9 off it each turn. The bar is drawn by a subroutine bar. I kept the turn number in $t0… and bar also uses $t0 to count hashes:
# lost.s: the turn number lives in $t0... and bar uses $t0 too
.data
tturn: .asciiz "Turn "
colon: .asciiz ": "
nl: .asciiz "\n"
.text
.globl main
main: li $t0, 1 # turn = 1
li $s1, 40 # the slime's life
loop: blez $s1, done # while it has life left
la $a0, tturn
li $v0, 4
syscall
move $a0, $t0 # the turn number
li $v0, 1
syscall
la $a0, colon
li $v0, 4
syscall
move $a0, $s1
jal bar # draws the life
addi $s1, $s1, -9 # Kira takes 9 off it
addi $t0, $t0, 1 # turn + 1 (or so I think)
j loop
done: li $v0, 10
syscall
# bar: prints a '#' for every 5 points of life ($a0 = life). Uses $t0.
bar: div $t0, $a0, 5 # $t0 = how many '#'
ba_next:
blez $t0, ba_end
li $a0, '#'
li $v0, 11 # print_char
syscall
addi $t0, $t0, -1
j ba_next
ba_end: li $a0, 10 # '\n'
li $v0, 11
syscall
jr $ra
Turn 1: ######## Turn 1: ###### Turn 1: #### Turn 1: ## Turn 1:
Always turn 1! bar leaves $t0 at 0 when it finishes drawing, and main‘s addi $t0, $t0, 1 takes it to 1 again and again. Nobody did anything “wrong” inside bar: the $t are its to use. The bug is main‘s, which trusted a $t to survive a jal.
This is what the lecture notes’ register convention says:
$t0–$t9, short-lived temporaries: the called subroutine may change them. If the caller wants to keep one after the call, it saves it beforehand.$s0–$s7, long-lived temporaries: the called subroutine may use them, but it has to save their value before changing them and restore it before going back.
Why the split is like this
The convention is a contract between two parties that don’t know each other: the caller and the called subroutine. If nobody saved anything, every jal would be a lottery, as in lost.s. If one of the two saved everything, you would use more stack than needed. The split makes the one who knows whether it is needed do the saving:
| Registers | Can the subroutine change them? | Who saves them? | Why |
|---|---|---|---|
$t0–$t9 | Yes, without warning | The caller, before the jal, if it needs them afterwards | Only the caller knows whether it needs that value later. That way a leaf like bar uses $t0 without touching the stack |
$s0–$s7 | Yes, but handing them back as they were | The subroutine, on the stack, if it uses them | The caller takes it for granted that they survive; only the subroutine knows whether it touches them |
$a0–$a3 | Yes | The caller, if it wants them afterwards | They are the subroutine’s input, and it usually uses them up: bar overwrites its $a0 with the '#' |
$v0–$v1 | Yes: that is where it leaves the result | Nobody: you copy them straight away | The next syscall or the next jal overwrites them |
$ra | Every jal it makes | The subroutine that is going to make a jal | It is its own way back, and the jal would wipe it |
For the subroutine, the $t come free and every $s costs an sw on the way in and an lw on the way out. That is why short leaves stick to $t, and long-lived values (the turn, the gold, the potions) go in $s.
The fix is to move the turn to $s0. Only three lines of the loop change:
main: li $s0, 1 # turn = 1, in an $s
li $s1, 40 # the slime's life
loop: blez $s1, done # while it has life left
la $a0, tturn
li $v0, 4
syscall
move $a0, $s0 # the turn number
li $v0, 1
syscall
la $a0, colon
li $v0, 4
syscall
move $a0, $s1
jal bar # draws the life
addi $s1, $s1, -9 # Kira takes 9 off it
addi $s0, $s0, 1 # turn + 1: now it works
j loop
Turn 1: ######## Turn 2: ###### Turn 3: #### Turn 4: ## Turn 5:
Now the turn goes up: 1, 2, 3, 4 and 5. Life goes down 9 at a time (40, 31, 22, 13 and 4) and each bar has one # per 5 points: 40 / 5 = 8, 31 / 5 = 6, 22 / 5 = 4, 13 / 5 = 2 and 4 / 5 = 0, which is why the last turn draws nothing. After the fifth, 4 − 9 = −5 and the loop ends.
Keeping in a $t a counter, an accumulator or a pointer that has to stay alive after a jal. It works as long as the subroutine doesn’t use that $t, and as soon as someone changes it, it fails somewhere that has nothing to do with it. Whatever crosses a jal goes in an $s.
And what if the subroutine needs an $s? Then it has to save it before using it and leave it as it was before going back. Save it where? On the stack.
In the lab manual you’ll see another style: the subroutine r_maximo saves every register it uses ($ra, $a0, $a1, $t0 and $t1), even though the convention doesn’t ask for it. Both ways work:
| Style | What the subroutine saves | Upside | Downside |
|---|---|---|---|
| Convention (notes) | Only the $s it uses, and $ra if it does jal | Fewer instructions | The caller has to remember to save its $t and $a |
| “Save it all” (manual) | Everything it touches, $t and $a included | The caller doesn’t worry about anything | More sw/lw and more stack on every call |
In the exam either is fine as long as it is consistent. In this topic we follow the convention, which is the one in the notes.
The stack: $sp, reserve, save and free
The stack is an area of memory that works like a pile of plates: the last thing you put on is the first thing you take off (LIFO). In MIPS it sits at the top of memory and grows downwards, towards lower addresses. The register $sp (stack pointer, number 29) always points to the last word in use.
Why you need a stack
In words, before looking at any instruction. While a subroutine only calls leaves, everything fits in registers. The problem appears when one subroutine calls another, like the turn further down, which calls attack: at that moment there are two ways back alive at once, turn‘s back to main and attack‘s back to turn, and there is only one $ra. The jal attack writes the second over the first. The same goes for the $s: if heal wants to use $s0, main‘s gold has to be somewhere in the meantime.
Why not keep it in a .data variable, one per subroutine? That works as long as no subroutine calls itself, but recursion breaks it: combo(4) calls combo(3), which calls combo(2), and each one has its own way back and its own n alive at the same time. One variable is not enough, and how many you need depends on the n you call it with, which you don’t know when you write the program.
So you need a memory that grows with every call and shrinks with every return. And the order fits by itself: the last subroutine in is the first one out. attack finishes before turn, and turn before main. That is exactly what a pile of plates does, so whatever each call saved is always on top when it is time to get it back.
The two operations are the ones in the notes:
- Save (push): first reserve, by subtracting from
$sp; then write withsw. - Take out (pop): first read with
lw; then free, by adding to$sp.
In the fight, Kira drinks her potions with a subroutine heal that does its sums in $s0 and $s1. But main keeps the gold and the potions in the bag in those registers, so heal saves them on entry and restores them on the way out:
# stack.s: a subroutine that uses $s0 and $s1 and saves them on the stack
.data
tlife: .asciiz "Life after healing: "
tgold: .asciiz "\nGold (still intact): "
tpot: .asciiz "\nPotions in the bag: "
.text
.globl main
main: li $s0, 120 # Kira's gold: main counts on it
li $s1, 3 # potions in the bag
li $a0, 52 # current life
move $a1, $s1 # drinks them all
jal heal
move $t2, $v0 # the new life, out of $v0
la $a0, tlife
li $v0, 4
syscall
move $a0, $t2
li $v0, 1
syscall
la $a0, tgold
li $v0, 4
syscall
move $a0, $s0 # 120: heal used it, but gave it back
li $v0, 1
syscall
la $a0, tpot
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
li $v0, 10
syscall
# heal: each potion adds 15 life, without going over 100
# Input: $a0 = life, $a1 = potions. Output: $v0 = new life. Uses $s0 and $s1.
heal: addi $sp, $sp, -8 # reserve 2 words
sw $s0, 4($sp) # save my caller's $s
sw $s1, 0($sp)
he_body:
move $s0, $a1 # $s0 = potions left
move $s1, $a0 # $s1 = life
he_next:
blez $s0, he_done
addi $s1, $s1, 15 # +15 per potion
ble $s1, 100, he_cont
li $s1, 100 # cap: 100
he_cont:
addi $s0, $s0, -1
j he_next
he_done:
move $v0, $s1 # the result
lw $s1, 0($sp) # restore in reverse order
lw $s0, 4($sp)
addi $sp, $sp, 8 # free the 2 words
he_back:
jr $ra
Life after healing: 97 Gold (still intact): 120 Potions in the bag: 3
The sums: 52 + 15 = 67, 67 + 15 = 82 and 82 + 15 = 97, without going over 100. And the important bit: the gold is still 120 and the potions still 3, even though heal used $s0 and $s1 for something else. Look at it on the stack:
Step by step, with the values from the run:
| Moment | $sp | 0x7fffffec | 0x7fffffe8 |
|---|---|---|---|
On entering heal | 0x7ffffff0 | (free) | (free) |
After addi $sp, $sp, -8 and both sw | 0x7fffffe8 | 120 ($s0) | 3 ($s1) |
After the lw and addi $sp, $sp, 8 | 0x7ffffff0 | 120 (free) | 3 (free) |
Why 4($sp) and 0($sp)? Because, after reserving 8 bytes, $sp points to the start of the gap. The first word is at 0($sp) and the second at 4($sp). Reserving in one go and writing with offsets is the same as one push per register (like the manual, addi -4 + sw each time), but with fewer instructions. Pick one way and always use it the same.
Why “in reverse order”? On a real stack you take things out in the opposite order to how you put them in. With offsets the order of the lw doesn’t matter, as long as each register reads from the slot where it was saved. If you swap the offsets, $s0 gets $s1‘s value and the other way round (you’ll see it in the exercises).
heal’s frame, instruction by instruction
The table above shows three snapshots. This is the whole film, with what is in each slot and in the two registers after every instruction:
| Instruction | $sp | 0x7fffffec | 0x7fffffe8 | $s0 | $s1 | Why |
|---|---|---|---|---|---|---|
| (on entry) | 0x7ffffff0 | free | free | 120 | 3 | They are main‘s gold and potions |
addi $sp, $sp, -8 | 0x7fffffe8 | reserved | reserved | 120 | 3 | Reserving writes nothing: it only moves $sp down 2 words |
sw $s0, 4($sp) | 0x7fffffe8 | 120 | reserved | 120 | 3 | 0x7fffffe8 + 4 = 0x7fffffec, the upper slot |
sw $s1, 0($sp) | 0x7fffffe8 | 120 | 3 | 120 | 3 | 0x7fffffe8 + 0, the lower one |
Body (he_body to he_done) | 0x7fffffe8 | 120 | 3 | 0 | 97 | heal uses its $s to count; main‘s copies are still in memory |
move $v0, $s1 | 0x7fffffe8 | 120 | 3 | 0 | 97 | The result goes out before restoring: $v0 = 97 |
lw $s1, 0($sp) | 0x7fffffe8 | 120 | 3 | 0 | 3 | It reads from the same slot its sw wrote to |
lw $s0, 4($sp) | 0x7fffffe8 | 120 | 3 | 120 | 3 | And main gets its gold back |
addi $sp, $sp, 8 | 0x7ffffff0 | 120 (free) | 3 (free) | 120 | 3 | Freeing doesn’t erase either: the values stay there until another sw overwrites them |
jr $ra | 0x7ffffff0 | free | free | 120 | 3 | Goes back to 0x00400038, main‘s move $t2, $v0 |
The final $sp is the starting one, and so are the $s: that is leaving the stack as you found it.
Check you’ve got it: what does stack.s print if the move $v0, $s1 goes after the two lw?
It prints Life after healing: 3, with the gold and potions fine (120 and 3). After the lw $s1, 0($sp), $s1 no longer holds heal‘s life (97) but main‘s potions (3), and that is what the move copies. The epilogue hands the $s back to the caller just as they were, so whatever the subroutine wants to return has to be in $v0 before it starts.
Reserving and not freeing (or freeing a different amount). The subroutine seems to work, but it goes back with $sp changed and the caller reads its saved data from the wrong slot. Golden rule: each addi $sp, $sp, -N has its addi $sp, $sp, N on every exit path.
The starting value of $sp depends on the simulator. In this article’s run it starts at 0x7ffffff0; in your QtSpim you’ll get another address close to 0x7fffffff, because system things are kept above the stack (your computer’s environment variables). What matters is not the address but the distance: here, 8 bytes. In QtSpim, the stack shows up in the data window (User Stack).
Leaf and non-leaf subroutines
If you draw the calls as a tree (main calls turn, turn calls attack and bar), leaf subroutines are the ones that call nobody: attack, bar, strip_nl. Non-leaf ones call others. And here is the detail that breaks most programs: every jal writes to $ra. If turn does jal attack, it loses the address to get back to main… unless it saved it on the stack first.
This is the fight with a subroutine turn that does the attack and draws the bar:
# nonleaf.s: turn calls attack and bar, so it saves its $ra
.data
tturn: .asciiz "Turn "
colon: .asciiz ": "
.text
.globl main
main: li $s0, 1 # turn
li $s1, 40 # the slime's life
mloop: blez $s1, mdone
la $a0, tturn
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
la $a0, colon
li $v0, 4
syscall
li $a0, 14 # Kira's attack
li $a1, 5 # the slime's defence
move $a2, $s1 # its life
jal turn
move $s1, $v0 # new life
addi $s0, $s0, 1
j mloop
mdone: li $v0, 10
syscall
# turn: applies an attack and draws the life that is left
# Input: $a0 = attack, $a1 = defence, $a2 = life. Output: $v0 = new life
turn: addi $sp, $sp, -8
sw $ra, 4($sp) # I'm going to jal: I save my way back
sw $s0, 0($sp) # and the $s0 I'm going to use
tu_inside:
jal attack # $v0 = new life, $v1 = damage
move $s0, $v0 # I keep it: bar doesn't touch the $s
move $a0, $v0
jal bar
move $v0, $s0 # turn's result
lw $s0, 0($sp)
lw $ra, 4($sp) # my way back, the real one
addi $sp, $sp, 8
jr $ra
# attack: $a0 = attack, $a1 = defence, $a2 = life -> $v0 = new life, $v1 = damage
attack: sub $v1, $a0, $a1
bgt $v1, 0, at_sub
li $v1, 1
at_sub:
sub $v0, $a2, $v1
bge $v0, 0, at_end
li $v0, 0
at_end: jr $ra
# bar: a '#' for every 5 of life ($a0) and a newline. Uses $t0.
bar: div $t0, $a0, 5
ba_next:
blez $t0, ba_end
li $a0, '#'
li $v0, 11
syscall
addi $t0, $t0, -1
j ba_next
ba_end: li $a0, 10
li $v0, 11
syscall
jr $ra
Turn 1: ###### Turn 2: #### Turn 3: ## Turn 4: Turn 5:
On entering turn the first time, $ra is 0x00400068 (the line of main right after jal turn). The first two instructions save it at 4($sp) together with $s0, and in the epilogue it is restored before the jr $ra. In between, the jal attack and jal bar can trample $ra as much as they like.
Tracing turn, with the stack
This is how the first turn of nonleaf.s goes (turn 1 in main‘s $s0, life 40), with $sp starting at 0x7ffffff0:
| Step | Instruction | $ra afterwards | $sp | Stack | Why |
|---|---|---|---|---|---|
| 1 | jal turn (in main, 0x00400064) | 0x00400068 | 0x7ffffff0 | empty | The way back to main is only in $ra |
| 2 | addi $sp, $sp, -8, sw $ra, 4($sp) and sw $s0, 0($sp) | 0x00400068 | 0x7fffffe8 | 0x7fffffec = 0x00400068, 0x7fffffe8 = 1 | Now the way back to main has a copy in memory |
| 3 | jal attack (0x00400088) | 0x0040008c | 0x7fffffe8 | unchanged | It overwrites $ra, but that no longer matters |
| 4 | attack‘s jr $ra | 0x0040008c | 0x7fffffe8 | unchanged | Back in turn with $v0 = 31 |
| 5 | move $s0, $v0 | 0x0040008c | 0x7fffffe8 | unchanged | The new life, safe from bar |
| 6 | jal bar (0x00400094) and its jr $ra | 0x00400098 | 0x7fffffe8 | unchanged | On the way back, $v0 is 11: the code of bar‘s last syscall |
| 7 | move $v0, $s0 | 0x00400098 | 0x7fffffe8 | unchanged | That is why the result is rebuilt from $s0 (31) |
| 8 | lw $s0, 0($sp) and lw $ra, 4($sp) | 0x00400068 | 0x7fffffe8 | read | $s0 goes back to 1 and $ra to the way back to main |
| 9 | addi $sp, $sp, 8 and jr $ra | 0x00400068 | 0x7ffffff0 | free | Jumps to 0x00400068, main‘s move $s1, $v0 |
Compare it with the broken program coming up next: there, step 2 doesn’t exist, and at the end $ra still holds bar‘s way back.
And if I don’t save it? This is what happens if I remove the sw $ra and the lw $ra (here, so you only see that bug, turn keeps the life in $t3 instead of $s0, because bar only uses $t0):
turn: jal attack # $ra = the way back to turn: main's is lost
move $t3, $v0 # bar only uses $t0
move $a0, $v0
jal bar # $ra = the way back to turn, again
tu_back:
move $v0, $t3
jr $ra # jumps to tu_back... forever
Turn 1: ######
The bar for turn 1 is printed and the program keeps thinking forever: in this article’s single run I stopped it at 5 million instructions. Why? Follow $ra:
| Step | Instruction | $ra afterwards |
|---|---|---|
| 1 | jal turn (in main) | 0x00400068 (back to main) |
| 2 | jal attack (in turn) | 0x00400080 (back to turn) |
| 3 | jal bar (in turn) | 0x0040008c (tu_back) |
| 4 | jr $ra (at the end of turn) | jumps to 0x0040008c, which is tu_back… |
| 5 | move $v0, $t3 and jr $ra again | …and jumps to 0x0040008c again, forever |
The way back to main was lost at step 2. In QtSpim you’ll have to press Pause or Stop.
A subroutine that does jal and doesn’t save $ra. The symptom is unmistakable: the program never ends or goes back somewhere odd, almost always to the line after its last jal. If your subroutine has a jal inside, its first two lines are reserving stack and sw $ra.
The template of a non-leaf subroutine has three parts (the manual calls them saving, body and restoring):
name: addi $sp, $sp, -8 # prologue: reserve
sw $ra, 4($sp) # save my way back
sw $s0, 0($sp) # and each $s I'm going to use
# ... body: here I can already jal and use $s0 ...
lw $s0, 0($sp) # epilogue: restore
lw $ra, 4($sp)
addi $sp, $sp, 8 # free the same amount I reserved
jr $ra
A leaf subroutine that only uses $t needs none of this: it comes in, works and jr $ra. That is why attack and bar don’t touch the stack.
Recursion: a subroutine that calls itself
A recursive subroutine calls itself with a smaller problem until it reaches a base case that is solved without calls. For the stack it is nothing special: it is a non-leaf subroutine that calls itself, so it saves its $ra and everything it needs after the call.
In the fight, Kira has a combo: hit number n deals 10 · n, and the n-hit combo is that hit plus the combo of n − 1. Combo(0) = 0, because with no hits there is no damage:
# combo.s: the damage of a combo, with a subroutine that calls itself
# combo(n) = 0 if n = 0; combo(n) = 10*n + combo(n - 1) if n > 0
.data
tcombo: .asciiz "4-hit combo: "
.text
.globl main
main: li $a0, 4 # 4-hit combo
jal combo
move $s0, $v0
la $a0, tcombo
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
li $v0, 10
syscall
# combo: $a0 = n -> $v0 = total damage of the n-hit combo
combo: addi $sp, $sp, -8 # my frame: 2 words
sw $ra, 4($sp) # I call myself: I save my way back
sw $a0, 0($sp) # and my n, which I need afterwards
co_base:
bnez $a0, co_next # n > 0: recursive case
li $v0, 0 # base case: combo(0) = 0
addi $sp, $sp, 8 # the frame is freed here too
jr $ra
co_next:
addi $a0, $a0, -1 # n - 1
jal combo # $v0 = combo(n - 1)
co_back:
lw $a0, 0($sp) # I restore my n
lw $ra, 4($sp) # and my way back
addi $sp, $sp, 8
mul $t0, $a0, 10 # hit n deals 10*n
add $v0, $v0, $t0 # combo(n) = 10*n + combo(n - 1)
jr $ra
4-hit combo: 100
Sum: 10 + 20 + 30 + 40 = 100. Look at the two things saved in the frame and why:
$ra, becausecombodoesjal comboand that would overwrite it.$a0(its n), because before the call it changes it to n − 1 and afterwards it needs the original n to add 10 · n.
This is the state of the stack at the bottom, when combo(0) reaches the base case:
Each call has its own 8-byte frame with its n and its $ra. On the way back, they unwind from the bottom up:
| Call | $sp in its frame | Saved n | Returns |
|---|---|---|---|
combo(4) | 0x7fffffe8 | 4 | 40 + 60 = 100 |
combo(3) | 0x7fffffe0 | 3 | 30 + 30 = 60 |
combo(2) | 0x7fffffd8 | 2 | 20 + 10 = 30 |
combo(1) | 0x7fffffd0 | 1 | 10 + 0 = 10 |
combo(0) | 0x7fffffc8 | 0 | 0 (base case) |
The full trace: down and up
The table above is the snapshot at the bottom. This is the film: first you go down (each call reserves its frame, saves and calls) and then you come up (each one restores, frees and adds):
| Step | What happens | $a0 | $sp | Stack | $v0 | Why |
|---|---|---|---|---|---|---|
| 1 | main does jal combo | 4 | 0x7ffffff0 | empty | $ra = 0x0040002c, the way back to main | |
| 2 | combo(4) saves and calls | 4, then 3 | 0x7fffffe8 | 0x7fffffec = 0x0040002c, 0x7fffffe8 = 4 | It saves before changing $a0 and before its jal | |
| 3 | combo(3) saves and calls | 3, then 2 | 0x7fffffe0 | 0x7fffffe4 = 0x00400074, 0x7fffffe0 = 3 | Its way back is co_back (0x00400074), inside combo(4) | |
| 4 | combo(2) saves and calls | 2, then 1 | 0x7fffffd8 | 0x7fffffdc = 0x00400074, 0x7fffffd8 = 2 | The same way back: every recursive call comes from the same jal | |
| 5 | combo(1) saves and calls | 1, then 0 | 0x7fffffd0 | 0x7fffffd4 = 0x00400074, 0x7fffffd0 = 1 | Each frame, 8 bytes lower | |
| 6 | combo(0): base case | 0 | 0x7fffffc8, and back to 0x7fffffd0 | 0x7fffffcc = 0x00400074, 0x7fffffc8 = 0 | 0 | It doesn’t call: it frees and does jr $ra to co_back |
| 7 | combo(1) restores and adds | 1 | 0x7fffffd8 | reads 1 and 0x00400074 | 0 + 10 = 10 | It arrives with $a0 = 0; the lw gives it back its 1 |
| 8 | combo(2) restores and adds | 2 | 0x7fffffe0 | reads 2 and 0x00400074 | 10 + 20 = 30 | Up one frame: $sp + 8 |
| 9 | combo(3) restores and adds | 3 | 0x7fffffe8 | reads 3 and 0x00400074 | 30 + 30 = 60 | One more frame up |
| 10 | combo(4) restores and adds | 4 | 0x7ffffff0 | reads 4 and 0x0040002c | 60 + 40 = 100 | Its lw $ra brings back the way back to main, saved in step 2 |
Notice two things. The way back 0x00400074 is saved four times, and combo(0)‘s copy is never read: the base case makes no jal, so it returns with the $ra it has in the register. And $sp goes down 8 on every step down and up 8 on every step up: five reservations, five releases, and it ends at 0x7ffffff0, where it started.
Check you’ve got it: with li $a0, 5 in main, how many frames are there at the bottom and how far down does $sp go?
Six frames, one for each n from 5 to 0, and $sp goes down to 0x7fffffc0: 6 · 8 = 48 bytes below 0x7ffffff0. The result is 150 (10 + 20 + 30 + 40 + 50). How much stack you use depends on the data you pass in, and that is why a fixed variable per subroutine would not be enough.
The base case also reserves and frees its frame. The notes do the same with the factorial (fact): if you change the base case to “return 1” and the addition to a mul, you get exactly that structure.
Forgetting to free the frame in the base case. The base case usually leaves through another jr $ra halfway through the subroutine, and it is easy to write only the li $v0, … and the jr. Every exit path needs its addi $sp, $sp, 8.
Before writing a recursive one, answer two questions: what is the base case (the one that doesn’t call)? and what do I need after the call? The second answer is what goes in the frame, besides $ra.
Local data on the stack
The stack doesn’t only hold registers. A subroutine can reserve space for its local data: variables it only needs while it works, like a buffer to read a name into. On return, that space is freed and the next call reuses it:
# local.s: a local buffer on the stack (nobody else needs it outside)
.data
pname: .asciiz "Ally's name: "
twelc: .asciiz "Joins the party: "
excl: .asciiz "!\n"
.text
.globl main
main: jal recruit
jal recruit # two allies, the same local buffer
li $v0, 10
syscall
# recruit: asks for a name in a 16-byte buffer on the stack and greets it
recruit:
addi $sp, $sp, -20 # 4 for $ra + 16 of buffer
sw $ra, 16($sp)
la $a0, pname
li $v0, 4
syscall
move $a0, $sp # the buffer starts at 0($sp)
li $a1, 16
li $v0, 8 # read_string onto the stack
syscall
move $a0, $sp
jal strip_nl
re_read:
la $a0, twelc
li $v0, 4
syscall
move $a0, $sp # print from the stack
syscall
la $a0, excl
syscall
lw $ra, 16($sp)
addi $sp, $sp, 20 # the buffer disappears here
jr $ra
# strip_nl: $a0 = string; changes its final '\n' to '\0'. Uses $t0 and $t1.
strip_nl:
move $t0, $a0
qn_look:
lbu $t1, 0($t0)
beq $t1, 10, qn_strip
beqz $t1, qn_end
addi $t0, $t0, 1
j qn_look
qn_strip:
sb $zero, 0($t0)
qn_end: jr $ra
Ally's name: Lia Joins the party: Lia! Ally's name: Brom Joins the party: Brom!
recruit reserves 20 bytes: 16 for the buffer (at 0($sp) to 15($sp)) and 4 for its $ra (at 16($sp)). read_string writes the name straight onto the stack. If you stop at re_read in the first call, the word at 0x7fffffdc is 0x0061694c: bytes 4c, 69, 61 and 00, which are L, i, a and '\0' read backwards because MIPS in QtSpim is little endian (the lowest-address byte is the rightmost one in the word).
This is the notes’ activation record (procedure frame): the part of the stack that belongs to one call, with its saved arguments, its return address, its $s and its local data. Some compilers also use $fp (frame pointer) to mark the start of the record, because $sp can move while the subroutine works. In IC1, $sp and fixed offsets are enough.
The stack as storage: turning a word round
As the last thing in is the first thing out, the stack is also handy to reverse things without a second index. I push the letters of “Slime” one by one and take them out in the opposite order:
# reverse.s: the stack as storage: the last thing in is the first thing out
.data
name: .asciiz "Slime"
reversed:.space 16
trev: .asciiz "Reversed: "
.text
.globl main
main: la $t0, name
li $t2, 0 # how many letters I have pushed
pile: lbu $t1, 0($t0)
beqz $t1, unpile
addi $sp, $sp, -4 # push: one word per letter
sw $t1, 0($sp)
addi $t2, $t2, 1
addi $t0, $t0, 1
j pile
unpile:
la $t0, reversed
take: beqz $t2, close
lw $t1, 0($sp) # pop: the last one in comes out
addi $sp, $sp, 4
sb $t1, 0($t0)
addi $t0, $t0, 1
addi $t2, $t2, -1
j take
close: sb $zero, 0($t0)
la $a0, trev
li $v0, 4
syscall
la $a0, reversed
syscall
li $v0, 10
syscall
Reversed: emilS
In go S, l, i, m, e (the e ends up on top) and out come e, m, i, l, S. Each letter takes a whole word so that $sp stays aligned to 4. At the end, $sp goes back exactly where it was: five addi -4 and five addi 4. It is the idea of exercise 7.10 in the manual.
When subroutines go wrong
| Symptom | Likely cause |
|---|---|
The program never ends or goes back to the line after a jal | A non-leaf subroutine that didn’t save $ra |
A counter or a pointer changes “by itself” after a jal | It was in a $t (or an $a) and the subroutine used it |
The caller finds its $s changed | The subroutine used an $s without saving and restoring it |
| Two values come out swapped after the call | The epilogue’s lw read from different slots than the sw |
| Everything is fine until the second or third call, then it goes back to odd places | $sp doesn’t come back the same: one amount was reserved and another freed, or an exit path doesn’t free |
The result comes out with the value of a li $v0 | A syscall was called before copying $v0 |
| The recursion gives an absurd result | What is used after the call wasn’t saved in the frame (the n, the first result) |
Try it in QtSpim (or right here)
This is the recursive combo. Open it in QtSpim or in the environment below and go step by step:
Loading the MIPS environment… If it doesn’t appear, copy combo.s into your QtSpim.
Things to look at:
- Run it and check “4-hit combo: 100”. Then change
main‘sli $a0, 4toli $a0, 5: you should get 150 (100 + 50). - Reload and go instruction by instruction (F10 in QtSpim). Each time you go through the
jal combo, watch$spdrop by 8 and$a0by 1. - Keep going when it reaches the base case:
$v0takes 0, 10, 30, 60 and 100, and$spgoes up 8 at a time back to its starting value. - In QtSpim, open the stack (User Stack in the data window) at the bottom of the recursion: you’ll see the five n (4, 3, 2, 1, 0) and the return addresses.
- Delete the line
addi $sp, $sp, 8from the base case and run it. Surprise: it still prints 100. Don’t trust it: step with F10 and you’ll seecombo(1)goes twice throughco_back, the first time reading the frame the base case left behind (with n = 0 and a return toco_back). Here it works by luck, with 81 instructions instead of 75. In the exercises you’ll see an unbalanced stack that isn’t so lucky.
Summary
| Concept | The essentials |
|---|---|
| Subroutine | Code written once and called from several places; a comment says what it gets, what it returns and what it uses |
jal label | $ra = address of the jal + 4, and jump |
jr $ra | Go back to the address in $ra |
| Arguments and results | $a0–$a3 and $v0–$v1; you can return one value, two or an address |
$t and $a | The subroutine may change them: if the caller wants them afterwards, it saves them |
$s | The subroutine hands them back intact: if it uses them, it saves them on the stack |
| Stack | Grows downwards; addi $sp, $sp, -N + sw to save, lw + addi $sp, $sp, N to restore |
| Leaf / non-leaf | The non-leaf one does jal, so it saves $ra |
| Recursion | One frame per call with $ra and whatever is needed afterwards; a base case that frees too |
| Local data | Reserved in the frame and gone on return |
Three ideas to take away
jalwrites to$ra, always. If your subroutine does ajal, its own way back is lost unless you saved it on the stack beforehand.- Whatever has to survive a
jalgoes in an$s. And whoever uses an$ssaves it and hands it back as it was. - Leave the stack as you found it. What you reserve you free, on every exit path, and each register comes back from the slot where you saved it.
In the subroutines practice we build the fight in three programs: the banner with four leaf subroutines (and one that isn’t), the turn order with a subroutine that returns the address of the fastest, and the recursive spell that leaves a trace of every level on the console.
Next step: practiceSubroutines in MIPS — practice with QtSpim: the fight banner, the turn order and a recursive spell (and the level 4 spell that did 0 damage)Did this article help you? Here is how you can support SergioLearns →



