Subroutines in MIPS — exercises with the average of a round, a poison you have to turn into subroutines and the combos that fit in your energy (and the counter that only saw 4 combos with 6 energy)
The last exercise I set myself before the exam was to count in how many ways the energy of a turn can be spent with light hits (they cost 1) and heavy hits (they cost 2). With 3 energy there are three: light-light-light, light-heavy and heavy-light. It is a recursion with two calls: the ways for n are those for n − 1 (if I start with a light one) plus those for n − 2 (if I start with a heavy one). I saved $ra and n in the frame, as always. And the result of the first call, while I made the second, I left in a $t. Why waste stack on a number?
wa_rec: addi $sp, $sp, -12 # $ra, n and the first result
sw $ra, 8($sp)
sw $a0, 4($sp)
addi $a0, $a0, -1
jal ways # $v0 = ways(n - 1)
wa_mid:
move $t1, $v0 # I leave it in a $t (so I thought)
lw $a0, 4($sp)
addi $a0, $a0, -2
jal ways # $v0 = ways(n - 2)
add $v0, $v0, $t1 # ways(n - 1) + ways(n - 2)
lw $ra, 8($sp)
addi $sp, $sp, 12
jr $ra
With 6 energy there are 4 possible combos (25 calls)
Four combos with 6 energy. With just 4 energy there are already five (I checked by hand), so something was very wrong. The bug: the second call, ways(n − 2), is recursive, and inside it more move $t1, $v0 are done. When it comes back, $t1 no longer holds my first result, but the last one left by some call further down. The stack was working; what wasn’t working was trusting a $t across a jal, even if that jal was to myself.
So this topic’s rule also applies to recursion: what you need after a call goes on the stack (or in a saved $s), never in a $t. Today’s three exercises put it to the test with data from the fight: an average with two results, a finished program you have to split into subroutines (like the optional part of a practical exam) and the combo counter, done properly.
Table of Contents
How to use this article
- Read the task and the expected output of each level. If the program reads from the keyboard, the inputs appear in the output.
- Write your program in Notepad++ (or in the site’s environment) and test it in QtSpim with that data and with other data that tries to break it.
- If you get stuck, open the hint. Don’t look at the solution until your program works or you’ve been at it for a good while.
- Before the solutions there are the three “What’s wrong here?” snippets: predict what comes out before reading the explanation.
Level 1 · Basic: the average of a round
Each round of the fight is stored as an array of words with a special format: the first word says how many hits there were and the following ones are the damage of each hit. There are two rounds:
round1: .word 5, 12, 7, 20, 9, 15 # 5 hits: 12, 7, 20, 9 and 15 round2: .word 3, 30, 25, 41 # 3 hits: 30, 25 and 41
Write a leaf subroutine average that gets in $a0 the address of a round and returns two results: in $v0 the integer average of the damage and in $v1 the remainder of the division. main has to call it for both rounds (better with a loop and a table with the addresses of the rounds than with repeated code) and print:
Round 1: average 12 (remainder 3) Round 2: average 32 (remainder 0)
div $t2, $t0 leaves the quotient in LO and the remainder in HI: mflo $v0 and mfhi $v1. The first value is at 4($a0), not at 0($a0). And in main, copy $v0 and $v1 to two $s before the first syscall.
Level 2 · Intermediate: the poison, now with subroutines
This program already works. It goes through the life of the enemies in a wave (the 0 marks the end) and, to those in an even position, it applies a poison: if they have more than 15, it takes 15 off; otherwise it leaves them with 1 (the poison doesn’t kill). At the end it says how many it poisoned:
# original.s: the poison without a subroutine (the program in the task)
.data
V: .word 40, 12, 33, 8, 27, 50, 9, 0 # each enemy's life; the 0 marks the end
N: .word 8
tpois: .asciiz "Poisoned: "
.text
.globl main
main: lw $s1, N
li $s0, 0 # i
li $s2, 0 # count
while:
bge $s0, $s1, done # i <= N - 1 ...
sll $t0, $s0, 2
lw $t1, V($t0)
beqz $t1, done # ... and V[i] <> 0
andi $t2, $s0, 1
bnez $t2, next # only the even positions
ble $t1, 15, one # if V[i] > 15: V[i] = V[i] - 15
addi $t1, $t1, -15
j store
one: li $t1, 1 # otherwise: it is left with 1 (poison doesn't kill)
store: sw $t1, V($t0)
addi $s2, $s2, 1
next:
addi $s0, $s0, 1
j while
done: la $a0, tpois
li $v0, 4
syscall
move $a0, $s2
li $v0, 1
syscall
li $v0, 10
syscall
Poisoned: 4
Change it so that:
- The check and the change of
V[i]are done by a leaf subroutineapply(V, i): the address of the array in$a0and the index in$a1. It returns nothing: it changes the array in memory. - A second leaf subroutine
show(V)displays the array (up to the 0) on one line.maincalls it before and after the poison.
The output has to be:
Before: 40 12 33 8 27 50 9 After: 25 12 18 8 12 50 1 Poisoned: 4
apply works out the address of V[i] itself: sll of the index and add with the base it gets in $a0. main‘s loop has to keep working after each jal: which registers hold i, N and the count?
Level 3 · Challenge: the combos for your energy
Write the recursive subroutine ways(n) from the hook, done properly: it returns in $v0 in how many ways exactly n energy can be spent with hits costing 1 or 2, where the order matters.
ways(0)= 1 andways(1)= 1 (base cases).ways(n)=ways(n − 1)+ways(n − 2)if n > 1.
Also, count in a memory word calls how many times ways is called in total. For 6 energy:
With 6 energy there are 13 possible combos (25 calls)
The frame needs three words: $ra, n and the result of the first call. The base case calls nobody, so it can go back without touching the stack. To check by hand: f(2) = 2, f(3) = 3, f(4) = 5, f(5) = 8 and f(6) = 13.
What’s wrong here?
Three snippets with a subroutine bug each. Before reading the explanation, predict what comes out.
Snippet 1
main keeps Kira’s gold in $s0 and her life in $s1. The shop uses those two registers for its sums, so it saves and restores them. What does it print?
# Snippet 1: the shop that swapped gold for life
.data
tgold: .asciiz "Gold: "
tlife: .asciiz " Life: "
.text
.globl main
main: li $s0, 120 # gold
li $s1, 40 # life
jal shop
la $a0, tgold
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
la $a0, tlife
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
li $v0, 10
syscall
# shop: does its sums with $s0 and $s1, so it saves them
shop: addi $sp, $sp, -8
sw $s0, 4($sp)
sw $s1, 0($sp)
li $s0, 7 # the shop's sums
li $s1, 3
lw $s0, 0($sp) # restore...
lw $s1, 4($sp)
addi $sp, $sp, 8
jr $ra
This is what comes out:
Gold: 40 Life: 120
The gold and the life have swapped places. shop saves $s0 at 4($sp) and $s1 at 0($sp), but when restoring it reads $s0 from 0($sp) (where the life was) and $s1 from 4($sp) (where the gold was). The stack is perfectly balanced (it reserves 8 and frees 8), so there is no error and no loop: just two swapped values, which is the worst kind, because it doesn’t jump out at you.
Writing the epilogue “backwards” from the prologue thinking of the order of a stack (last in, first out) and accidentally swapping the offsets. With sw/lw and offsets, the order of the instructions doesn’t matter; what matters is that each register comes back from its own slot.
The fix is two lines:
lw $s1, 0($sp) # restore: $s1 was at 0 lw $s0, 4($sp) # and $s0 at 4
Gold: 120 Life: 40
Write the epilogue by copying the prologue’s lines and changing sw to lw. That way the offsets match by construction, and then you just add the addi that frees and the jr $ra.
Snippet 2
hits works out how many hits of 5 damage are needed to take off 23 life. main keeps Kira’s level (7) in $s0. What does it print?
# Snippet 2: the level that reset itself
.data
tlevel: .asciiz "Hero level: "
thit: .asciiz "Hits: "
nl: .asciiz "\n"
.text
.globl main
main: li $s0, 7 # Kira's level
li $a0, 23 # total damage
li $a1, 5 # damage per hit
jal hits
move $s1, $v0
la $a0, thit
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
la $a0, nl
li $v0, 4
syscall
la $a0, tlevel
syscall
move $a0, $s0 # should be 7
li $v0, 1
syscall
li $v0, 10
syscall
# hits: how many hits of $a1 are needed for $a0 damage (rounding up)
hits: li $s0, 0 # counter... in an $s I don't save
hi_next:
blez $a0, hi_end
sub $a0, $a0, $a1
addi $s0, $s0, 1
j hi_next
hi_end: move $v0, $s0
jr $ra
This is what comes out:
Hits: 5 Hero level: 5
The number of hits is right (23 → 18 → 13 → 8 → 3 → −2: five subtractions), but Kira has gone down from level 7 to level 5. hits uses $s0 as a counter without saving it, and the convention says the opposite: whoever uses an $s hands it back intact. Here the bug isn’t main‘s, which did well to keep the level in an $s; it is the subroutine’s.
Using $s inside a subroutine “because it’s safer” and not saving it. An $s is safe for the caller; for the subroutine, it is an obligation to save and restore.
There are two correct fixes: save $s0 on the stack (prologue and epilogue) or, since hits is a leaf, use a $t, which doesn’t have to be handed back. The second is shorter:
hits: li $t0, 0 # counter in a $t: nobody expects it to be kept
hi_next:
blez $a0, hi_end
sub $a0, $a0, $a1
addi $t0, $t0, 1
j hi_next
hi_end: move $v0, $t0
jr $ra
Hits: 5 Hero level: 7
Snippet 3
round makes three turns in a row. turn prints the hit and, just in case, saves $ra and $s0. What does it print?
# Snippet 3: the round that didn't know how to go back
.data
thit: .asciiz "Hit for "
tend: .asciiz "End of the round\n"
.text
.globl main
main: jal round
la $a0, tend
li $v0, 4
syscall
li $v0, 10
syscall
# round: three turns in a row; it calls turn, so it saves its $ra
round: addi $sp, $sp, -4
sw $ra, 0($sp)
li $a0, 9
jal turn
li $a0, 14
jal turn
li $a0, 6
jal turn
ro_exit:
lw $ra, 0($sp) # my way back... if $sp is where I left it
addi $sp, $sp, 4
jr $ra
# turn: prints "Hit for N" ($a0 = damage). Saves $ra and $s0, although it only uses $s0.
turn: addi $sp, $sp, -8 # I reserve 8 bytes...
sw $ra, 4($sp)
sw $s0, 0($sp)
move $s0, $a0
la $a0, thit
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
li $a0, 10
li $v0, 11
syscall
lw $s0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 4 # ...and I free 4
jr $ra
This is what comes out:
Hit for 9 Hit for 14 Hit for 6 Hit for 6 Hit for 14 Hit for 6 Hit for 6 End of the round
Seven hits instead of three! And the program ends, which is the most puzzling part. The bug is in turn‘s last line: it reserves 8 bytes and frees 4. Each turn leaves $sp 4 bytes lower, so after three turns round looks for its $ra 12 bytes below where it saved it:
In that slot is the return address saved by the third turn, which points to round‘s own ro_exit line. From there, each lw $ra reads a return address saved by some turn, each addi $sp, $sp, 4 goes up one slot and the program jumps to lines of round that repeat turns. These are the eight times it goes through ro_exit in the run:
| Time | $sp | $ra it reads | Where it jumps |
|---|---|---|---|
| 1 | 0x7fffffe0 | 0x00400060 | ro_exit again |
| 2 | 0x7fffffe4 | 0x00400058 | li $a0, 6: another “Hit for 6” |
| 3 | 0x7fffffe4 | 0x00400060 | ro_exit again |
| 4 | 0x7fffffe8 | 0x00400050 | li $a0, 14: “Hit for 14” and “Hit for 6” |
| 5 | 0x7fffffe4 | 0x00400060 | ro_exit again |
| 6 | 0x7fffffe8 | 0x00400058 | another “Hit for 6” |
| 7 | 0x7fffffe8 | 0x00400060 | ro_exit again |
| 8 | 0x7fffffec | 0x00400028 | main, at last: “End of the round” |
That it ends at all is pure luck: on the eighth round, $sp lands exactly on the slot where round saved the way back to main. With other data or one more turn, the program could jump anywhere.
Freeing a different amount from what was reserved. The bug doesn’t show up in the subroutine that makes it (turn goes back fine, because it reads its $ra before the addi), but in the one that called it, one or several calls later.
The fix is a number:
lw $s0, 0($sp) lw $ra, 4($sp) addi $sp, $sp, 8 # I reserve 8, I free 8 jr $ra
Hit for 9 Hit for 14 Hit for 6 End of the round
Solutions
Level 1 solution
# level1.s: the average damage of each round (level 1 solution)
.data
round1: .word 5, 12, 7, 20, 9, 15 # first N, then the N hits
round2: .word 3, 30, 25, 41
rounds: .word round1, round2 # table with the addresses of the rounds
tround: .asciiz "Round "
tavg: .asciiz ": average "
trem: .asciiz " (remainder "
close: .asciiz ")\n"
.text
.globl main
main: li $s0, 0 # i: current round
mloop:
bge $s0, 2, mdone
sll $t0, $s0, 2
lw $a0, rounds($t0) # $a0 = address of round i
jal average # $v0 = quotient, $v1 = remainder
move $s1, $v0 # both results, out of $v0/$v1
move $s2, $v1
la $a0, tround
li $v0, 4
syscall
addi $a0, $s0, 1 # round number: i + 1
li $v0, 1
syscall
la $a0, tavg
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
la $a0, trem
li $v0, 4
syscall
move $a0, $s2
li $v0, 1
syscall
la $a0, close
li $v0, 4
syscall
addi $s0, $s0, 1
j mloop
mdone: li $v0, 10
syscall
# average: array with N in the first word and the N values after it
# Input: $a0 = address of the array. Output: $v0 = integer average, $v1 = remainder. Uses $t0-$t2.
average: lw $t0, 0($a0) # $t0 = N
move $t1, $t0 # $t1 = how many are left to add
li $t2, 0 # $t2 = sum
av_sum:
blez $t1, av_div
addi $a0, $a0, 4 # the first value is at 4($a0)
lw $t3, 0($a0)
add $t2, $t2, $t3
addi $t1, $t1, -1
j av_sum
av_div: div $t2, $t0 # LO = quotient, HI = remainder
mflo $v0
mfhi $v1
jr $ra
Round 1: average 12 (remainder 3) Round 2: average 32 (remainder 0)
The approach, before the code: the first thing is to pin down the contract of average, which is the comment line that goes above it: what it gets (an address), what it returns (two numbers) and which registers it overwrites. With that written down, main and average can be done separately. Inside average there are three steps: read N, add up N values and divide only once, at the end.
The obvious path would be to pass N in $a1 as well as the address. Here it’s not needed: N is already in the first word of the round, and asking for it separately forces main to read it before each call, which is exactly the work you wanted to take out of main.
Why it’s done this way:
- A single address as the argument. As the array carries its length in the first word,
averagedoesn’t need$a1: it reads N from0($a0)and the values from4($a0)onwards. It’s the format of exercises 7.2 to 7.4 in the manual. averagemoves$a0. It uses it as a pointer (addi $a0, $a0, 4before eachlw). The convention allows it andmaindoesn’t need it afterwards, because in the next round it loads it again from the tablerounds.- Two results, two registers.
divleaves quotient and remainder at once;mfloandmfhiput them in$v0and$v1. Inmain,move $s1, $v0andmove $s2, $v1go right after thejal, before any syscall. - The table of rounds avoids repeating the call-and-print block:
rounds($t0)with$t0 = i · 4gives the address of round i, like the menu in topic 5.
The sums: round 1, 12 + 7 + 20 + 9 + 15 = 63 and 63 / 5 = 12 remainder 3 (5 · 12 = 60). Round 2, 30 + 25 + 41 = 96 and 96 / 3 = 32 remainder 0.
Round of av_sum (round 1) | $t1 (left) | Value | $t2 (sum) |
|---|---|---|---|
| 1 | 5 | 12 | 12 |
| 2 | 4 | 7 | 19 |
| 3 | 3 | 20 | 39 |
| 4 | 2 | 9 | 48 |
| 5 | 1 | 15 | 63 |
| Exit | 0 | — | 63 → div |
Doing the lw before the addi $a0, $a0, 4. The first “value” added is N and the last hit is left out: in round 1 the sum is 5 + 12 + 7 + 20 + 9 = 53 and you get Round 1: average 10 (remainder 3); in round 2, Round 2: average 19 (remainder 1).
Removing the two move after the jal and printing $v0 and $v1 directly. You get Round 1: average 4 (remainder 3) and Round 2: average 4 (remainder 0): the li $v0, 4 that prints “: average ” overwrites the average, and the number that comes out is the code of that syscall. The remainder comes out right because no syscall touches $v1.
Level 2 solution
# level2.s: the poison with the subroutines apply and show (level 2 solution)
.data
V: .word 40, 12, 33, 8, 27, 50, 9, 0 # each enemy's life; the 0 marks the end
N: .word 8
tbefore: .asciiz "Before: "
tafter: .asciiz "After: "
tpois: .asciiz "Poisoned: "
.text
.globl main
main: la $a0, tbefore
li $v0, 4
syscall
la $a0, V
jal show
lw $s1, N
li $s0, 0 # i
li $s2, 0 # count
while:
bge $s0, $s1, done # i <= N - 1 ...
sll $t0, $s0, 2
lw $t1, V($t0)
beqz $t1, done # ... and V[i] <> 0
andi $t2, $s0, 1
bnez $t2, next # only the even positions
la $a0, V # apply(V, i)
move $a1, $s0
jal apply
addi $s2, $s2, 1
next:
addi $s0, $s0, 1 # i and the count are in $s: apply doesn't touch them
j while
done: la $a0, tafter
li $v0, 4
syscall
la $a0, V
jal show
la $a0, tpois
li $v0, 4
syscall
move $a0, $s2
li $v0, 1
syscall
li $v0, 10
syscall
# apply: if V[i] > 15, V[i] = V[i] - 15; otherwise, V[i] = 1
# Input: $a0 = address of V, $a1 = i. Returns nothing. Uses $t0 and $t1.
apply: sll $t0, $a1, 2 # i * 4
add $t0, $a0, $t0 # $t0 = &V[i]
lw $t1, 0($t0)
ble $t1, 15, ap_one
addi $t1, $t1, -15
j ap_store
ap_one: li $t1, 1
ap_store:
sw $t1, 0($t0)
jr $ra
# show: the numbers of an array ending in 0, separated by spaces
# Input: $a0 = address of the array. Uses $t0.
show:
move $t0, $a0
sh_next:
lw $a0, 0($t0)
beqz $a0, sh_end
li $v0, 1
syscall
li $a0, ' '
li $v0, 11
syscall
addi $t0, $t0, 4
j sh_next
sh_end: li $a0, 10
li $v0, 11
syscall
jr $ra
Before: 40 12 33 8 27 50 9 After: 25 12 18 8 12 50 1 Poisoned: 4
The approach, before the code: when you’re given a program that already works, you don’t rewrite it; you cut it. First you mark the piece that goes into the subroutine (from ble $t1, 15, one to the sw). Then you look at what that piece uses from outside: $t1 with V[i] and $t0 with i · 4. In principle, those would be the arguments; but the task fixes apply(V, i), so apply works out the address and reads V[i] again on its own. And finally you check what main needs after the jal: i, N and the count.
Why not the path that looks shorter, passing V[i] in $a0 and getting the new value back in $v0: it would work, but the sw would stay in main and the subroutine would only do the sums. With the address, apply changes the array in memory by itself, as the task asks.
Why it’s done this way:
main‘s loop doesn’t change: only the block of theifis replaced by three lines (la $a0, V,move $a1, $s0andjal apply). It’s what the optional parts of practical exams ask for: the same algorithm, with one part in a subroutine.i,Nand the count are in$s0,$s1and$s2. They already were in the original program; if they had been in$t, going to subroutines would mean moving them, becauseapplyuses$t0and$t1.applyis a leaf and only uses$t, so it doesn’t need the stack. It gets the base and the index, as in the task, and works out the address itself (sll+add).showcopies$a0into$t0on its first line, because it needs$a0for the syscalls of each number and each space.
The sums: even positions 0, 2, 4 and 6. 40 − 15 = 25, 33 − 15 = 18, 27 − 15 = 12, and 9 is not greater than 15, so it becomes 1. Four poisoned; 12, 8 and 50 (positions 1, 3 and 5) don’t change.
i | V[i] | Even? | Call | V[i] afterwards |
|---|---|---|---|---|
| 0 | 40 | Yes | apply(V, 0) | 25 |
| 1 | 12 | No | — | 12 |
| 2 | 33 | Yes | apply(V, 2) | 18 |
| 3 | 8 | No | — | 8 |
| 4 | 27 | Yes | apply(V, 4) | 12 |
| 5 | 50 | No | — | 50 |
| 6 | 9 | Yes | apply(V, 6) | 1 |
| 7 | 0 | — | end of the loop | — |
Keeping i in $t0 inside main. apply does add $t0, $a0, $t0 and, when it comes back, $t0 holds the address of V[0], 0x10010000: after the addi, i is already far greater than N and the bge exits straight away. Only enemy 0 is poisoned: After: 25 12 33 8 27 50 9 and Poisoned: 1.
Level 3 solution
# level3.s: how many combos fit in your energy (level 3 solution)
# ways(n) = 1 if n <= 1; ways(n) = ways(n - 1) + ways(n - 2)
.data
calls: .word 0 # how many times ways is called
ta: .asciiz "With 6 energy there are "
tb: .asciiz " possible combos ("
tc: .asciiz " calls)"
.text
.globl main
main: li $a0, 6
jal ways
move $s0, $v0
la $a0, ta
li $v0, 4
syscall
move $a0, $s0
li $v0, 1
syscall
la $a0, tb
li $v0, 4
syscall
lw $a0, calls
li $v0, 1
syscall
la $a0, tc
li $v0, 4
syscall
li $v0, 10
syscall
# ways: $a0 = energy -> $v0 = combos of light (1) and heavy (2) hits that use it all up
ways: lw $t0, calls # one more call
addi $t0, $t0, 1
sw $t0, calls
bgt $a0, 1, wa_rec
li $v0, 1 # base case: with 0 or 1 energy, one way
jr $ra # a leaf in this case: I haven't touched the stack
wa_rec: addi $sp, $sp, -12 # $ra, n and the first result
sw $ra, 8($sp)
sw $a0, 4($sp)
addi $a0, $a0, -1
jal ways # $v0 = ways(n - 1)
wa_mid:
sw $v0, 0($sp) # I save it: the next call overwrites $v0
lw $a0, 4($sp)
addi $a0, $a0, -2
jal ways # $v0 = ways(n - 2)
lw $t0, 0($sp)
add $v0, $v0, $t0 # ways(n - 1) + ways(n - 2)
lw $ra, 8($sp)
addi $sp, $sp, 12
jr $ra
With 6 energy there are 13 possible combos (25 calls)
The approach, before the code: ask yourself what each call needs after its first jal. It needs $ra, to go back; n, to work out n − 2; and ways(n − 1), to add it at the end. Everything else can be lost. Those three things are the frame: three words, 12 bytes. Making this list first is what avoids the bug in the hook: there, the first result was left off the list and ended up in a $t.
Why it’s done this way:
- The base case doesn’t touch the stack. If n ≤ 1 it returns 1 and goes back: it is a leaf on that path, so it doesn’t need to save anything. The frame is only reserved on the recursive path (
wa_rec), and that path frees it. It’s another valid way, different fromcomboin the theory, where the base case also reserves and frees. - Three words in the frame:
$raat8($sp), n at4($sp)(because after the first call it’s needed to work out n − 2) and the first result at0($sp)(because the second call overwrites$v0, and any$t). - The counter lives in memory, not in a register, because every call has to see it. Each call does
lw,addiandswoncalls, and uses$t0only for a moment.
Checking the 25 calls: if C(n) is the number of calls for n, C(0) = C(1) = 1 and C(n) = 1 + C(n − 1) + C(n − 2). C(2) = 3, C(3) = 5, C(4) = 9, C(5) = 15 and C(6) = 25.
For ways(4), the result of the first call, ways(3) = 3, waits at 0($sp) of its frame while ways(2) = 2 is worked out; then they’re added: 3 + 2 = 5.
Removing the lw $a0, 4($sp) thinking that $a0 is still n − 1. When ways(n − 1) comes back, $a0 holds whatever the last call below left there (a 1 or a negative number), so the second call gets −1, −3, −5… and always falls into the base case. ways(n) becomes ways(n − 1) + 1, which gives n: you get With 6 energy there are 6 possible combos (11 calls). The clue: the calls change too.
What if the first result goes into $s0?
If you do move $s0, $v0 and don’t save $s0, the same thing happens as in the hook: the calls inside also write to $s0, and you get With 6 energy there are 4 possible combos (25 calls). An $s isn’t kept by itself; it’s kept because every subroutine that uses it saves it.
If you also add sw $s0, 0($sp) to the prologue and lw $s0, 0($sp) before the lw $ra, you get 13 with 25 calls again. It works, but the frame still has three words: you’ve swapped “saving the result” for “saving $s0“.
Practice quiz
Twelve questions on the whole topic: jal and jr $ra, the register convention, the stack, leaf and non-leaf and recursion. It doesn’t count for anything: it’s there to show you what you’ve got clear and what you haven’t, so you can repeat it as many times as you like. Each answer comes with its explanation.
A jal strip_nl is at address 0x00400048. What does $ra hold right after it runs?
0x0040004c0x00400048- The address of
strip_nl - It doesn’t change:
jalonly jumps
Solution
Answer: 0x0040004c
jal saves in $ra the address of the next instruction (the jal’s + 4) and jumps to the label. The jr $ra at the end of the subroutine goes back to that address.
Match each register with its role in the MIPS convention.
| $a0-$a3 | |
| $v0-$v1 | |
| $t0-$t9 | |
| $s0-$s7 | |
| $ra | |
| $sp |
Definitions:
- Points to the last word in use on the stack
- The subroutine may change them without warning
- Return address written by jal
- Pointer to the static data segment
- Arguments of the subroutine
- The subroutine hands them back as they were
- Results of the subroutine
Solution
- $a0-$a3 → Arguments of the subroutine
- $v0-$v1 → Results of the subroutine
- $t0-$t9 → The subroutine may change them without warning
- $s0-$s7 → The subroutine hands them back as they were
- $ra → Return address written by jal
- $sp → Points to the last word in use on the stack
The spare one describes $gp, the global pointer, which is not used in IC1 subroutines.
About the register convention, true or false?
- If the caller needs a $t after a jal, it has to save it itself before the call.
- A subroutine can use $s0 without saving it if it is a leaf.
- On return from a subroutine, $a0 always has the same value as before the call.
- On return from a subroutine, $sp has to hold the same value as before the call.
Solution
- T — If the caller needs a $t after a jal, it has to save it itself before the call.
- F — A subroutine can use $s0 without saving it if it is a leaf.
- F — On return from a subroutine, $a0 always has the same value as before the call.
- T — On return from a subroutine, $sp has to hold the same value as before the call.
Any subroutine, leaf or not, hands the $s back intact: if it uses them, it saves them. The $a, like the $t, may be changed (biggest in the practice uses them as pointer and counter). $sp always comes back to the same value.
What does this program print?
main: li $t0, 5
li $s0, 8
jal double
add $a0, $t0, $s0
li $v0, 1
syscall
li $v0, 10
syscall
double: sll $t0, $a0, 1
jr $ra- 8
- 13
- 18
- 16
Solution
Answer: 8
main trusts that $t0 = 5 will still be there after the jal, but double uses $t0 for its result. As $a0 is 0, it leaves $t0 = 0 and the sum is 0 + 8 = 8. Whatever has to survive a jal goes in an $s.
Put in order the instructions of a non-leaf subroutine that uses $s0.
- addi $sp, $sp, -8
- Body, with its jal
- addi $sp, $sp, 8
- lw $s0, 0($sp) and lw $ra, 4($sp)
- sw $ra, 4($sp) and sw $s0, 0($sp)
- jr $ra
Solution
Correct order:
- addi $sp, $sp, -8
- sw $ra, 4($sp) and sw $s0, 0($sp)
- Body, with its jal
- lw $s0, 0($sp) and lw $ra, 4($sp)
- addi $sp, $sp, 8
- jr $ra
First you reserve and save (prologue), then the body can jal and use $s0, and at the end you restore, free the same amount you reserved and go back.
Fill in the push and pop of $s0 one at a time, as in the lab manual.
Push: addi $sp, $sp, ____ and sw $s0, ____($sp). Pop: ____ $s0, 0($sp) and addi $sp, $sp, ____.
Words:
- 4
- 4
- 8
- 0
- -4
- sw
- lw
- -8
Solution
Push: addi $sp, $sp, -4 and sw $s0, 0($sp). Pop: lw $s0, 0($sp) and addi $sp, $sp, 4.
To save, you first reserve (subtracting 4 from $sp) and then write at 0($sp). To take out, you first read and then free (adding 4).
$sp is 0x7ffffff0 and a subroutine does addi $sp, $sp, -12. Where does $sp end up and at which offsets can it save?
0x7fffffe4; at 0($sp), 4($sp) and 8($sp)0x7ffffffc; at 0($sp), 4($sp) and 8($sp)0x7fffffe4; at -4($sp), -8($sp) and -12($sp)0x7fffffe8; at 0($sp) and 4($sp)
Solution
Answer: 0x7fffffe4; at 0($sp), 4($sp) and 8($sp)
Reserving means subtracting from $sp; after that, the reserved words are those between $sp and its previous value: 0($sp), 4($sp) and 8($sp).
A subroutine does jal attack and then jal bar, but doesn’t save $ra. What happens when it reaches its jr $ra?
- It jumps to the instruction after its jal bar and the program never gets back to the caller
- It goes back to the caller, because jr $ra always goes back to main
- QtSpim gives an address error
- It goes back to the instruction after jal attack
Solution
Answer: It jumps to the instruction after its jal bar and the program never gets back to the caller
The way back to the caller is lost at the first jal inside. In the theory, the turn without $ra keeps jumping to its own tu_back line forever.
With the combo subroutine from the theory (combo(0) = 0 and combo(n) = 10 · n + combo(n − 1)), what does this program print?
main: li $a0, 3
jal combo
move $a0, $v0
li $v0, 1
syscall
li $v0, 10
syscall
combo: addi $sp, $sp, -8
sw $ra, 4($sp)
sw $a0, 0($sp)
bnez $a0, next
li $v0, 0
addi $sp, $sp, 8
jr $ra
next: addi $a0, $a0, -1
jal combo
lw $a0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 8
mul $t0, $a0, 10
add $v0, $v0, $t0
jr $raSolution
Answer: 60
combo(3) = 30 + combo(2) = 30 + 20 + combo(1) = 30 + 20 + 10 + combo(0) = 60.
A recursive subroutine f(n) works out n * f(n - 1). What must it save in its frame before the jal f? (Tick all.)
- $ra
- n (its $a0)
- $v0
- $t0
Solution
Answer: $ra · n (its $a0)
What goes in the frame is whatever is needed after the call: the way back and the original n. It is the fact of the lecture notes.
The prologue does sw $s0, 4($sp) and sw $s1, 0($sp). Which is the right epilogue?
- lw $s1, 0($sp) / lw $s0, 4($sp) / addi $sp, $sp, 8
- lw $s0, 0($sp) / lw $s1, 4($sp) / addi $sp, $sp, 8
- addi $sp, $sp, 8 / lw $s1, 0($sp) / lw $s0, 4($sp)
- lw $s1, 0($sp) / lw $s0, 4($sp) / addi $sp, $sp, 4
Solution
Answer: lw $s1, 0($sp) / lw $s0, 4($sp) / addi $sp, $sp, 8
With offsets, the order of the lw doesn’t matter as long as each reads its own slot; what does matter is freeing after reading and freeing the same amount you reserved.
power(base, n) reserves a 12-byte frame per call and calls itself down to n = 0. For power(3, 4), how many bytes below its starting value does $sp get?
- 60
- 48
- 12
- 81
Solution
Answer: 60
At the bottom of the recursion all the frames live together: one per pending call. It is what the practice draws: $sp goes down from 0x7ffffff0 to 0x7fffffb4.
Try it in QtSpim (or right here)
This is Snippet 3, the round that didn’t know how to go back. Open it in QtSpim or in the environment below:
Loading the MIPS environment… If it doesn’t appear, copy round.s into your QtSpim.
Things to look at:
- Run it and count the hits: seven instead of three.
- Put a breakpoint on
ro_exitand run it: at each stop, compare$spwith the table above. The first time it’s 12 bytes below whereroundsaved its$ra. - At each stop, step one instruction (F10) and look at
$ra: you’ll see the addresses in the table,0x00400060,0x00400058… - Change the
addi $sp, $sp, 4at the end ofturntoaddi $sp, $sp, 8and run it again: three hits, “End of the round”, andro_exitonly stops once. - With the fix in place, remove
turn‘ssw $ra, 4($sp)andlw $ra, 4($sp). Does it work? (Yes:turndoesn’t dojal, so its$radoesn’t change. Saving it was unnecessary.)
Cheat sheet: Subroutines in MIPS
The essentials in 30 seconds
jal labelsaves the next address in$raand jumps;jr $ragoes back.- Arguments in
$a0–$a3; results in$v0and$v1(move them out before any syscall). $tand$a: the subroutine may change them.$s: it hands them back intact (if it uses them, it saves them).- Stack: grows downwards. Reserve = subtract from
$sp; free = add the same. - Non-leaf (does
jal) → saves$ra. Recursive → also whatever it needs after the call.
I want to…
| I want to… | Code | Result |
|---|---|---|
| Call a subroutine | jal name | $ra = address of the jal + 4 |
| Go back | jr $ra | Carries on after the jal |
| Pass three values | li $a0, … / li $a1, … / li $a2, … | The subroutine reads them from $a0–$a2 |
| Return two values | move $v0, … / move $v1, … | The caller copies them to $s straight away |
| Pass an array | la $a0, V (and $a1 = length) | The subroutine walks from $a0 |
| Return where something is | move $v1, $a0 (an address) | The caller reads or writes at 0($v1) |
Save $ra and $s0 | addi $sp, $sp, -8 / sw $ra, 4($sp) / sw $s0, 0($sp) | 8-byte frame |
| Restore them | lw $s0, 0($sp) / lw $ra, 4($sp) / addi $sp, $sp, 8 | $sp as it was |
| A 16-byte local buffer | addi $sp, $sp, -20 / sw $ra, 16($sp) / move $a0, $sp | The buffer is 0($sp)..15($sp) |
Templates
Leaf subroutine (only $t):
leaf: # ... uses $a0-$a3 and $t0-$t9 ...
move $v0, $t0 # result
jr $ra
Non-leaf subroutine that uses $s0:
nonleaf: addi $sp, $sp, -8
sw $ra, 4($sp)
sw $s0, 0($sp)
# ... body with jal ...
lw $s0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 8
jr $ra
Recursive with a base case:
rec: addi $sp, $sp, -8
sw $ra, 4($sp)
sw $a0, 0($sp) # what I need afterwards
bnez $a0, rec_next
li $v0, 0 # base case
addi $sp, $sp, 8 # here too
jr $ra
rec_next:
addi $a0, $a0, -1
jal rec
lw $a0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 8
# ... combine $v0 with $a0 ...
jr $ra
Templates from the exercises
| Exercise | Key | Result |
|---|---|---|
| Average of a round | lw $t0, 0($a0) = N; div + mflo $v0 + mfhi $v1 | 12 (remainder 3) and 32 (remainder 0) |
| Poison with subroutines | apply(V, i): sll $t0, $a1, 2 + add $t0, $a0, $t0 | 25 12 18 8 12 50 1; 4 poisoned |
| Energy combos | 12-byte frame: $ra, n and the first result | 13 combos, 25 calls |
Mistakes that come up most
| Symptom | Likely cause |
|---|---|
| The program never ends | A non-leaf without sw $ra/lw $ra |
A caller’s counter changes after a jal | It was in a $t; move it to an $s |
A caller’s $s changes after a jal | The subroutine used that $s without saving it |
| Two values swapped on return | Different offsets in sw and lw |
| Bits of the program repeat or it goes back to odd places | Unbalanced $sp: freed a different amount from what was reserved |
| Recursion with an absurd result | What is used after the call isn’t in the frame |
| Everything comes out 0 in a recursion that multiplies | The base case returns 0 instead of 1 |
Before you hand it in, ask yourself
- Does each subroutine have a comment with what it gets, what it returns and the registers it uses?
- Does each subroutine that does
jalsave and restore$ra? - Does each
addi $sp, $sp, -Nhave itsaddi $sp, $sp, Non every exit path? - Is whatever the caller needs after a
jalin an$s(or in memory) and not in a$t, an$aor$v0?
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?IC1 practical mock exam — MIPS in QtSpim with other data, subroutines and keyboard input (and why part 1 decides almost everything)


