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.

How to use this article

  1. Read the task and the expected output of each level. If the program reads from the keyboard, the inputs appear in the output.
  2. 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.
  3. 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.
  4. 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:

  1. The check and the change of V[i] are done by a leaf subroutine apply(V, i): the address of the array in $a0 and the index in $a1. It returns nothing: it changes the array in memory.
  2. A second leaf subroutine show(V) displays the array (up to the 0) on one line. main calls 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 and ways(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:

An unbalanced stack: round reads the wrong slotFour words of stack. At 0x7fffffec sits round's $ra, which goes back to main. Below it are the return addresses saved by the three turns, because each one reserved 8 bytes and freed 4. $sp is at 0x7fffffe0, so lw $ra, 0($sp) loads 0x00400060, a line of round itself.The stack when round is about to read its $ra (Snippet 3)7fffffec00400028round's $ra (back to main)la $a0, tend7fffffe800400050leftovers of turn 1li $a0, 147fffffe400400058leftovers of turn 2li $a0, 67fffffe000400060leftovers of turn 3lw $ra, 0($sp)$sp = 7fffffe0round expects $sp at 7fffffec, but three turns that free 4 out of 8 have left it 12 bytes lower.
The coral slot is the one round reads; the green one is the one it should read.

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 readsWhere it jumps
10x7fffffe00x00400060ro_exit again
20x7fffffe40x00400058li $a0, 6: another “Hit for 6”
30x7fffffe40x00400060ro_exit again
40x7fffffe80x00400050li $a0, 14: “Hit for 14” and “Hit for 6”
50x7fffffe40x00400060ro_exit again
60x7fffffe80x00400058another “Hit for 6”
70x7fffffe80x00400060ro_exit again
80x7fffffec0x00400028main, 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, average doesn’t need $a1: it reads N from 0($a0) and the values from 4($a0) onwards. It’s the format of exercises 7.2 to 7.4 in the manual.
  • average moves $a0. It uses it as a pointer (addi $a0, $a0, 4 before each lw). The convention allows it and main doesn’t need it afterwards, because in the next round it loads it again from the table rounds.
  • Two results, two registers. div leaves quotient and remainder at once; mflo and mfhi put them in $v0 and $v1. In main, move $s1, $v0 and move $s2, $v1 go right after the jal, before any syscall.
  • The table of rounds avoids repeating the call-and-print block: rounds($t0) with $t0 = i · 4 gives 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)
151212
24719
332039
42948
511563
Exit0—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 the if is replaced by three lines (la $a0, V, move $a1, $s0 and jal apply). It’s what the optional parts of practical exams ask for: the same algorithm, with one part in a subroutine.
  • i, N and the count are in $s0, $s1 and $s2. They already were in the original program; if they had been in $t, going to subroutines would mean moving them, because apply uses $t0 and $t1.
  • apply is 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).
  • show copies $a0 into $t0 on its first line, because it needs $a0 for 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.

iV[i]Even?CallV[i] afterwards
040Yesapply(V, 0)25
112No—12
233Yesapply(V, 2)18
38No—8
427Yesapply(V, 4)12
550No—50
69Yesapply(V, 6)1
70—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 from combo in the theory, where the base case also reserves and frees.
  • Three words in the frame: $ra at 8($sp), n at 4($sp) (because after the first call it’s needed to work out n − 2) and the first result at 0($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, addi and sw on calls, and uses $t0 only 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.

Two recursive calls per levelCall tree of ways(4), written f(4). Each node with n greater than 1 calls f(n – 1) on the left and f(n – 2) on the right; the green leaves, f(1) and f(0), return 1. Adding upwards: f(2) = 2, f(3) = 3 and f(4) = 5, in 9 calls.The calls of ways(4), written f(4)f(1)= 1f(0)= 1f(2)= 2f(1)= 1f(3)= 3f(1)= 1f(0)= 1f(2)= 2f(4)= 5ways(4): 9 calls. With 6 energy the tree has 25 and the result is 13.
While the right branch is being worked out, the result of the left one has to wait on the stack.

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.

Question 1Single choice

A jal strip_nl is at address 0x00400048. What does $ra hold right after it runs?

  1. 0x0040004c
  2. 0x00400048
  3. The address of strip_nl
  4. It doesn’t change: jal only 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.

Question 2Match

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.

Question 3True or false

About the register convention, true or false?

  1. If the caller needs a $t after a jal, it has to save it itself before the call.
  2. A subroutine can use $s0 without saving it if it is a leaf.
  3. On return from a subroutine, $a0 always has the same value as before the call.
  4. 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.

Question 4Single choice

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
  1. 8
  2. 13
  3. 18
  4. 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.

Question 5Order

Put in order the instructions of a non-leaf subroutine that uses $s0.

  1. addi $sp, $sp, -8
  2. Body, with its jal
  3. addi $sp, $sp, 8
  4. lw $s0, 0($sp) and lw $ra, 4($sp)
  5. sw $ra, 4($sp) and sw $s0, 0($sp)
  6. jr $ra
Solution

Correct order:

  1. addi $sp, $sp, -8
  2. sw $ra, 4($sp) and sw $s0, 0($sp)
  3. Body, with its jal
  4. lw $s0, 0($sp) and lw $ra, 4($sp)
  5. addi $sp, $sp, 8
  6. 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.

Question 6Fill in the gaps

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).

Question 7Single choice

$sp is 0x7ffffff0 and a subroutine does addi $sp, $sp, -12. Where does $sp end up and at which offsets can it save?

  1. 0x7fffffe4; at 0($sp), 4($sp) and 8($sp)
  2. 0x7ffffffc; at 0($sp), 4($sp) and 8($sp)
  3. 0x7fffffe4; at -4($sp), -8($sp) and -12($sp)
  4. 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).

Question 8Single choice

A subroutine does jal attack and then jal bar, but doesn’t save $ra. What happens when it reaches its jr $ra?

  1. It jumps to the instruction after its jal bar and the program never gets back to the caller
  2. It goes back to the caller, because jr $ra always goes back to main
  3. QtSpim gives an address error
  4. 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.

Question 9Short answer

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 $ra
Solution

Answer: 60

combo(3) = 30 + combo(2) = 30 + 20 + combo(1) = 30 + 20 + 10 + combo(0) = 60.

Question 10Multiple · wrong ticks subtract

A recursive subroutine f(n) works out n * f(n - 1). What must it save in its frame before the jal f? (Tick all.)

  1. $ra
  2. n (its $a0)
  3. $v0
  4. $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.

Question 11Single choice

The prologue does sw $s0, 4($sp) and sw $s1, 0($sp). Which is the right epilogue?

  1. lw $s1, 0($sp) / lw $s0, 4($sp) / addi $sp, $sp, 8
  2. lw $s0, 0($sp) / lw $s1, 4($sp) / addi $sp, $sp, 8
  3. addi $sp, $sp, 8 / lw $s1, 0($sp) / lw $s0, 4($sp)
  4. 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.

Question 12Single choice

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?

  1. 60
  2. 48
  3. 12
  4. 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:

  1. Run it and count the hits: seven instead of three.
  2. Put a breakpoint on ro_exit and run it: at each stop, compare $sp with the table above. The first time it’s 12 bytes below where round saved its $ra.
  3. At each stop, step one instruction (F10) and look at $ra: you’ll see the addresses in the table, 0x00400060, 0x00400058…
  4. Change the addi $sp, $sp, 4 at the end of turn to addi $sp, $sp, 8 and run it again: three hits, “End of the round”, and ro_exit only stops once.
  5. With the fix in place, remove turn‘s sw $ra, 4($sp) and lw $ra, 4($sp). Does it work? (Yes: turn doesn’t do jal, so its $ra doesn’t change. Saving it was unnecessary.)
IC1 exam coming up?The theory and MIPS packs with new solved exams, their cheat sheets, blank exams and .s solutions, for free.See the pack

Cheat sheet: Subroutines in MIPS

The essentials in 30 seconds

  • jal label saves the next address in $ra and jumps; jr $ra goes back.
  • Arguments in $a0–$a3; results in $v0 and $v1 (move them out before any syscall).
  • $t and $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…CodeResult
Call a subroutinejal name$ra = address of the jal + 4
Go backjr $raCarries on after the jal
Pass three valuesli $a0, … / li $a1, … / li $a2, …The subroutine reads them from $a0–$a2
Return two valuesmove $v0, … / move $v1, …The caller copies them to $s straight away
Pass an arrayla $a0, V (and $a1 = length)The subroutine walks from $a0
Return where something ismove $v1, $a0 (an address)The caller reads or writes at 0($v1)
Save $ra and $s0addi $sp, $sp, -8 / sw $ra, 4($sp) / sw $s0, 0($sp)8-byte frame
Restore themlw $s0, 0($sp) / lw $ra, 4($sp) / addi $sp, $sp, 8$sp as it was
A 16-byte local bufferaddi $sp, $sp, -20 / sw $ra, 16($sp) / move $a0, $spThe 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

ExerciseKeyResult
Average of a roundlw $t0, 0($a0) = N; div + mflo $v0 + mfhi $v112 (remainder 3) and 32 (remainder 0)
Poison with subroutinesapply(V, i): sll $t0, $a1, 2 + add $t0, $a0, $t025 12 18 8 12 50 1; 4 poisoned
Energy combos12-byte frame: $ra, n and the first result13 combos, 25 calls

Mistakes that come up most

SymptomLikely cause
The program never endsA non-leaf without sw $ra/lw $ra
A caller’s counter changes after a jalIt was in a $t; move it to an $s
A caller’s $s changes after a jalThe subroutine used that $s without saving it
Two values swapped on returnDifferent offsets in sw and lw
Bits of the program repeat or it goes back to odd placesUnbalanced $sp: freed a different amount from what was reserved
Recursion with an absurd resultWhat is used after the call isn’t in the frame
Everything comes out 0 in a recursion that multipliesThe base case returns 0 instead of 1

Before you hand it in, ask yourself

  1. Does each subroutine have a comment with what it gets, what it returns and the registers it uses?
  2. Does each subroutine that does jal save and restore $ra?
  3. Does each addi $sp, $sp, -N have its addi $sp, $sp, N on every exit path?
  4. Is whatever the caller needs after a jal in an $s (or in memory) and not in a $t, an $a or $v0?
Keep goingAll MIPS articles

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)