Branches, conditionals and loops in MIPS — theory with a wave of enemies, “and” and “or” conditions and the loop template (and the counter that counted backwards)

Third IC1 lab session. I already knew how to store my game’s wave of enemies in .data and how to add and subtract without fear, so the task looked short: count how many enemies fall to a single sword hit. My sword takes away 40 HP, so the ones with 40 or less fall. I wrote the loop, put the condition exactly as I thought it, “if hp <= hit”, and pressed F5:

# hook.s: the enemies that fall in one hit (or so I thought)
        .data
wave:   .word 35, 80, 40, 120, 15, 60, 90, 200   # each enemy's HP
n:      .word 8                # how many enemies there are
hit:    .word 40               # my sword's damage
txt:    .asciiz "Enemies that fall in one hit: "

        .text
        .globl main
main:   la   $t0, wave         # pointer to the first enemy
        lw   $t1, n            # $t1 = 8, the loop limit
        lw   $t5, hit          # $t5 = 40
        li   $t2, 0            # i = 0
        li   $s0, 0            # counter = 0
loop:   beq  $t2, $t1, end     # if i == n, the wave is over
        lw   $t3, 0($t0)       # $t3 = enemy i's HP
        ble  $t3, $t5, next    # if hp <= hit... do I skip it?
        addi $s0, $s0, 1       # counter = counter + 1
next:
        addi $t0, $t0, 4       # next enemy (one word = 4 bytes)
        addi $t2, $t2, 1       # i = i + 1
        j    loop              # back to the start of the loop
end:    li   $v0, 4            # print the text
        la   $a0, txt
        syscall
        li   $v0, 1            # print the counter
        move $a0, $s0
        syscall
        li   $v0, 10           # end of the program
        syscall

In the console:

Enemies that fall in one hit: 5

Five? The wave has eight enemies and only three have 40 HP or less (35, 40 and 15). Not a single error or warning: the program was counting exactly the ones that did not fall. The bug was one single instruction, ble $t3, $t5, next. I read it as “if hp <= hit, count it”, but in assembly a branch does not run what is below it: it skips it. With ble, the enemies that fell in one hit jumped over the addi and the counter only added the ones that resisted: 5 = 8 − 3.

Today is about everything that makes a MIPS program take decisions: the branches that really exist (beq, bne and j), how to compare with slt, the pseudo-instructions blt, bgt, ble and bge, if-then and if-then-else with the opposite condition, compound conditions with “and” and with “or”, and the three loops: for, while and do-while. The example that comes with us is the wave of enemies: eight words with each one’s HP. If you come from load, arithmetic and logic in MIPS, you already have everything you need; and when you finish, in the practice we build three complete programs with it.

Before you start. From the previous topic, load, arithmetic and logic in MIPS, you need four things: storing data in .data with .word and .asciiz; bringing it into a register with la, lw and li; adding with add and addi; and printing with syscall ($v0 = 4 for a text, 1 for an integer and 10 to finish). And one idea that takes center stage here: every instruction takes 4 bytes and has its own address in memory. That is all. The topic goes in this order: the three real branches; “less than” with slt and the pseudo-instructions; the if and the if-else with the opposite condition, also with “and” and “or”; and the three loops, with the template that fixes the counter from the start. If you get lost at any point, go back to the same question: which address does the PC go to after this instruction?

Why we need to jump

Until now, all our programs were a list of instructions that ran from top to bottom, one after another. The processor does it with a special register, the PC (Program Counter), which holds the address of the next instruction. Since every MIPS instruction is 4 bytes long, after each one the PC adds 4: 0x00400024, 0x00400028, 0x0040002c…

To take a decision (“if the enemy falls, count it”) or to repeat something (“do this with the eight enemies”) we have to break that straight line: replace the PC with another address. That is exactly what a branch instruction does. And the address you jump to is marked with a label, which is not an instruction at all: it is just a name for the address of the instruction next to it.

Why there is no if or while in assembly

In Java you write if (hp <= hit) { ... } and the braces mark a block: what is inside goes together, as if inside a box. In memory there are no boxes. The program is a row of 4-byte words, one after another, and after each instruction the processor asks itself just one question: which one is next? And that question only has two possible answers:

  • The one below: the PC adds 4. That is what happens almost every time.
  • Any other one: a branch instruction puts a new address in the PC.

An if or a while is neither of the two: it is a way of arranging code meant for whoever reads it, and that is why the processor does not have them. When you compile in Java or C, the compiler does what you are going to do by hand in this topic: it breaks every structure down into branches and labels.

In pseudocodeWhat is left in MIPSWhy
if (condition) then … endifA forward branch that skips the then partIf the condition does not hold, the PC has to go over the body
… else …One more label and a j at the end of the then partThe then part cannot carry on and walk into the else
while / forA forward branch that cuts it and a backward jGoing back up means putting a smaller address in the PC
do … whileA single conditional branch backwardsThe question goes at the end, after the body
The closing brace, the endifA labelIt is just the name of an address: it takes no memory and does nothing

Read every branch as “go to”, never as “do”. beq $t0, $zero, defeated does not run defeated: it changes the PC so that the next instruction is the one at that address.

Let’s see it with the smallest possible program: an enemy with 0 HP.

# jump.s: the PC does not always move 4 by 4
        .data
hp:     .word 0                    # the enemy's HP after the hit
alive:  .asciiz "Still standing\n"
fallen: .asciiz "Enemy defeated\n"

        .text
        .globl main
main:   lw   $t0, hp               # $t0 = 0
        beq  $t0, $zero, defeated  # if hp == 0, jump to defeated
        li   $v0, 4                # (this only runs if it is still alive)
        la   $a0, alive
        syscall
        j    quit                  # unconditional jump: I do not go through defeated
defeated:
        li   $v0, 4
        la   $a0, fallen
        syscall
quit:   li   $v0, 10               # end of the program
        syscall

Output:

Enemy defeated

And here is the interesting part: QtSpim’s text segment (the dumps in this article come from the same SPIM core that QtSpim uses). Our main starts at 0x00400024:

[00400024] 3c011001  lui $1, 4097                   ; 9: lw $t0, hp # $t0 = 0
[00400028] 8c280000  lw $8, 0($1)
[0040002c] 11000006  beq $8, $0, 24 [defeated-0x0040002c] ; 10: beq $t0, $zero, defeated # if hp == 0, jump to defeated
[00400030] 34020004  ori $2, $0, 4                  ; 11: li $v0, 4 # (this only runs if it is still alive)
[00400034] 3c011001  lui $1, 4097 [alive]           ; 12: la $a0, alive
[00400038] 34240004  ori $4, $1, 4 [alive]
[0040003c] 0000000c  syscall                        ; 13: syscall
[00400040] 08100015  j 0x00400054 [quit]            ; 14: j quit # unconditional jump: I do not go through defeated
[00400044] 34020004  ori $2, $0, 4                  ; 16: li $v0, 4
[00400048] 3c011001  lui $1, 4097 [fallen]          ; 17: la $a0, fallen
[0040004c] 34240014  ori $4, $1, 20 [fallen]
[00400050] 0000000c  syscall                        ; 18: syscall
[00400054] 3402000a  ori $2, $0, 10                 ; 19: li $v0, 10 # end of the program

Look at three things:

  • The label defeated does not show up as an instruction: it is the address 0x00400044, the one of the li $v0, 4 below it. That is why the beq shows [defeated-0x0040002c] and a 24: from the branch to the label there are 24 bytes, six instructions.
  • j quit already carries the full address, 0x00400054.
  • Since the HP is 0, the beq jumps and the PC goes from 0x0040002c to 0x00400044 without touching “Still standing”.

The assembler works out the address of every label by itself. How that distance is stored inside the 32 bits of the instruction (the I format of beq and the 26 bits of j) is covered in the instruction set topic. To write programs, you only need the label name right.

Check you’ve got it: in jump.s, change the HP to 5. Which addresses does the PC go through, and what is printed?

Only “Still standing” is printed. The PC starts at 0x00400024 and goes down 4 by 4 through the lw (which is two instructions, at 0x00400024 and 0x00400028) to the beq at 0x0040002c. Since 5 is not 0, the beq does not jump and the PC carries on through 0x00400030, 0x00400034, 0x00400038 and the syscall at 0x0040003c, which prints “Still standing”. Then it reaches the j quit at 0x00400040, which puts 0x00400054 in the PC: the four instructions of defeated (from 0x00400044 to 0x00400050) do not run. Without that j, the PC would walk into defeated and both sentences would come out.

beq, bne and j: the branches that really exist

The MIPS processor only has three instructions to control the flow of programs like ours:

InstructionWhat it doesExample with the wave
beq rs, rt, labelJumps if rs == rt (branch if equal)beq $t2, $t1, end: if I have already looked at the n enemies, I leave
bne rs, rt, labelJumps if rs != rt (branch if not equal)bne $t2, $t1, noenergy: if I did not reach the end, it was something else
j labelAlways jumps (jump)j loop: back to the start of the loop

beq and bne are conditional branches: if the condition does not hold, nothing happens and the program carries on with the instruction below. j is an unconditional jump: it asks nothing.

What about “less than” or “greater or equal”? Here comes the curious part: MIPS does not have blt or bge in hardware. Checking whether two numbers are equal is very fast (you just look at whether every bit matches), but deciding whether one is less than the other needs almost a full subtraction. If the processor had to do that inside the branch instruction itself, that extra work would lengthen the clock cycle… of every instruction. So the designers chose the common case (beq and bne) and left “less than” to another instruction: slt.

beq $t0, $zero, label is the way to ask “is it zero?”. You will see it so often that the assembler gives it a short name, beqz.

slt: comparing without jumping

slt (set on less than) compares two registers and leaves the answer in a third one: a 1 if the first is less than the second, a 0 otherwise. It does not jump anywhere: it only writes a number. It has three sisters:

InstructionWhat it does
slt rd, rs, rtrd = 1 if rs < rt (signed); otherwise rd = 0
slti rt, rs, immediateThe same, with a number instead of a register
sltu rd, rs, rtLike slt, but unsigned
sltiu rt, rs, immediateLike slti, unsigned

With an enemy’s HP (35) and the sword’s hit (40):

# compare.s: slt does not jump, it answers with a 1 or a 0
        .data
hp:     .word 35                    # the enemy's HP
hit:    .word 40                    # the sword's damage
c1:     .asciiz "slt  (hp < hit):      "
c2:     .asciiz "slti (hp < 20):       "
c3:     .asciiz "slt  (hit < hp):      "
c4:     .asciiz "slt  (-1 < 1):        "
c5:     .asciiz "sltu (-1 < 1):        "
nl:     .asciiz "\n"

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 35
        lw   $t5, hit               # $t5 = 40
        slt  $s0, $t3, $t5          # 35 < 40? yes: $s0 = 1
        slti $s1, $t3, 20           # 35 < 20? no: $s1 = 0
        slt  $s2, $t5, $t3          # 40 < 35? no: it is "hp > hit" with the order swapped
        li   $t6, -1                # $t6 = 0xffffffff
        li   $t7, 1                 # $t7 = 0x00000001
        slt  $s3, $t6, $t7          # signed: -1 < 1, yes
        sltu $s4, $t6, $t7          # unsigned: 4294967295 < 1, no
        li   $v0, 4                 # --- from here on, print ---
        la   $a0, c1
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 4
        la   $a0, nl
        syscall
        li   $v0, 4
        la   $a0, c2
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, nl
        syscall
        li   $v0, 4
        la   $a0, c3
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, nl
        syscall
        li   $v0, 4
        la   $a0, c4
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, nl
        syscall
        li   $v0, 4
        la   $a0, c5
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 10                # end of the program
        syscall

Output:

slt  (hp < hit):      1
slti (hp < 20):       0
slt  (hit < hp):      0
slt  (-1 < 1):        1
sltu (-1 < 1):        0

Line by line:

  • slt $s0, $t3, $t5: 35 < 40? Yes, so 1.
  • slti $s1, $t3, 20: 35 < 20? No: 0.
  • slt $s2, $t5, $t3: here is the greater-than trick. MIPS has no sgt, but “hp > hit” is the same as “hit < hp”. You just swap the registers. It gives 0 because 35 is not greater than 40.
  • The last two compare the same bits: 0xffffffff and 0x00000001. Signed, 0xffffffff is −1 and −1 < 1, so slt gives 1. Unsigned, 0xffffffff is 4,294,967,295, which is not less than 1, and sltu gives 0.

Comparing data that can be negative with sltu (or with its pseudo-instructions bltu, bgtu…). A −1 turns into the biggest 32-bit number and the comparison comes out the other way round, with no warning at all. HP, damage or a temperature go with slt.

So how do I jump “if hp < hit”? By putting both pieces together: slt leaves a 1 or a 0 and bne jumps if that register is not 0.

slt  $t0, $t3, $t5        # $t0 = 1 if hp < hit
bne  $t0, $zero, less     # if $t0 != 0, jump to less

slt + beq/bne: the four comparisons with the wave

slt only answers “is the first one less than the second?”. With that and the two real branches you get all four comparisons, thanks to two tricks:

  • Swapping the order of the registers: “hp > hit” is the same as “hit < hp”.
  • Looking at the 0 instead of the 1: “hp >= hit” is “it is not true that hp < hit”, so you jump when slt leaves a 0. That is what beq $t0, $zero is for; to jump on the 1, bne $t0, $zero.

With the example’s HP ($t3 = 35) and the hit ($t5 = 40):

I want to jump if…slt I write$t0 with 35 and 40BranchJumps?Why
hp < hitslt $t0, $t3, $t51bne $t0, $zero, lblYes35 < 40: the 1 is exactly the answer I was after
hp > hitslt $t0, $t5, $t30bne $t0, $zero, lblNoOrder swapped: it asks whether 40 < 35
hp <= hitslt $t0, $t5, $t30beq $t0, $zero, lblYes<= is “it is not true that hit < hp”: you jump on the 0
hp >= hitslt $t0, $t3, $t51beq $t0, $zero, lblNo>= is “it is not true that hp < hit”: on the 1 you do not jump

To choose between beq and bne, ask yourself which slt value you want to make you jump. If it is the 1 (the comparison with < holds), bne $t0, $zero; if it is the 0, beq $t0, $zero. And if the condition has an equals sign (<= or >=), it is always the 0.

Check you’ve got it: with hp = 40 and hit = 40, which of the four jump?

hp <= hit and hp >= hit jump; neither the < one nor the > one does. With two equal numbers, slt gives 0 in both orders, because 40 is not less than 40. The two rows with bne were waiting for a 1 and do not jump; the two with beq were waiting for a 0 and jump. The 40 is exactly the enemy that separates “falls in one hit” from “resists”, and that is why it is the one you always have to test.

Two instructions every time you want to compare. Luckily, you do not have to write them yourself.

Pseudo-instructions: blt, bgt, ble, bge and friends

SPIM’s assembler lets you write branches the processor does not have and replaces them with real instructions. They are pseudo-instructions, like li, la or move, which you already know:

Pseudo-instructionJumps if…
blt rs, rt, labelrs < rt
bgt rs, rt, labelrs > rt
ble rs, rt, labelrs <= rt
bge rs, rt, labelrs >= rt
beqz rs, labelrs == 0
bnez rs, labelrs != 0
b labelalways (like j)

To see what the assembler does with them, this program prints nothing: each branch goes to the next line, so it does not matter whether it is taken or not. What matters is the text segment:

# pseudo.s: what SPIM writes when you ask for a branch MIPS does not have
        .data
hp:     .word 35
hit:    .word 40

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 35
        lw   $t5, hit               # $t5 = 40
        blt  $t3, $t5, p1           # if hp <  hit
p1:     bgt  $t3, $t5, p2           # if hp >  hit
p2:     ble  $t3, $t5, p3           # if hp <= hit
p3:     bge  $t3, $t5, p4           # if hp >= hit
p4:     beqz $t3, p5                # if hp == 0
p5:     bnez $t3, p6                # if hp != 0
p6:     bgt  $t3, 100, p7           # compare with a number
p7:     b    p8                     # unconditional branch (like j)
p8:     li   $v0, 10                # end of the program
        syscall

What SPIM really puts in memory:

[00400024] 3c011001  lui $1, 4097                   ; 8: lw $t3, hp # $t3 = 35
[00400028] 8c2b0000  lw $11, 0($1)
[0040002c] 3c011001  lui $1, 4097                   ; 9: lw $t5, hit # $t5 = 40
[00400030] 8c2d0004  lw $13, 4($1)
[00400034] 016d082a  slt $1, $11, $13               ; 10: blt $t3, $t5, p1 # if hp < hit
[00400038] 14200001  bne $1, $0, 4 [p1-0x00400038]
[0040003c] 01ab082a  slt $1, $13, $11               ; 11: bgt $t3, $t5, p2 # if hp > hit
[00400040] 14200001  bne $1, $0, 4 [p2-0x00400040]
[00400044] 01ab082a  slt $1, $13, $11               ; 12: ble $t3, $t5, p3 # if hp <= hit
[00400048] 10200001  beq $1, $0, 4 [p3-0x00400048]
[0040004c] 016d082a  slt $1, $11, $13               ; 13: bge $t3, $t5, p4 # if hp >= hit
[00400050] 10200001  beq $1, $0, 4 [p4-0x00400050]
[00400054] 11600001  beq $11, $0, 4 [p5-0x00400054] ; 14: beqz $t3, p5 # if hp == 0
[00400058] 15600001  bne $11, $0, 4 [p6-0x00400058] ; 15: bnez $t3, p6 # if hp != 0
[0040005c] 29610065  slti $1, $11, 101              ; 16: bgt $t3, 100, p7 # compare with a number
[00400060] 10200001  beq $1, $0, 4 [p7-0x00400060]
[00400064] 04010001  bgez $0 4 [p8-0x00400064]      ; 17: b p8 # unconditional branch (like j)
[00400068] 3402000a  ori $2, $0, 10                 ; 18: li $v0, 10 # end of the program

Every comparison pseudo-instruction becomes two real instructions: an slt that writes into $1 and a beq or bne that looks at $1. If you look closely, everything comes from two ideas:

PseudoBecomesWhy
blt a, bslt $1, a, b + bne $1, $0a < b as it is
bgt a, bslt $1, b, a + bne $1, $0the order swapped: b < a
ble a, bslt $1, b, a + beq $1, $0a <= b is “it is not true that b < a”
bge a, bslt $1, a, b + beq $1, $0a >= b is “it is not true that a < b”
beqz abeq a, $0one single real instruction
bgt a, 100slti $1, a, 101 + beq $1, $0a > 100 is “it is not true that a < 101”

And b p8 ends up as a bgez $0: “jump if 0 >= 0”, which always holds.

Register $1 has a name of its own: $at (assembler temporary). It is reserved for the assembler, which uses it in these translations (and in lw $t3, hp, as you can see in the first two lines: lui $1, 4097). That is why you never keep anything in $at: the next blt would overwrite it without asking.

In the exam you can use pseudo-instructions without fear: QtSpim understands them and they make the code much easier to read. What you do want is to know what they become, because in the text segment you will see slt and bne, not your bgt.

If-then: jumping with the opposite condition

On to the first structure. In pseudocode:

if (hp <= hit) then
    print "Falls in one hit"
endif
print "Next enemy"

Here is the idea that took me an afternoon to get (and that caused the counter at the start): in assembly you do not tell the processor “if it holds, do this”. You tell it “if it does NOT hold, skip this”. The branch goes to the label endif and the then part stays below, between the branch and the label. That is why the branch condition is the opposite of the if condition:

# if.s: if the enemy falls in one hit, I say so
        .data
hp:     .word 35                    # the enemy's HP
hit:    .word 40                    # the sword's damage
falls:  .asciiz "Falls in one hit\n"
onward: .asciiz "Next enemy\n"

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 35
        lw   $t5, hit               # $t5 = 40
        bgt  $t3, $t5, endif        # opposite of (hp <= hit): skip the then part
        li   $v0, 4                 # then: it falls in one hit
        la   $a0, falls
        syscall
endif:  li   $v0, 4                 # this always runs
        la   $a0, onward
        syscall
        li   $v0, 10
        syscall

Output:

Falls in one hit
Next enemy

With 35 HP, “hp > hit” does not hold, the bgt does not jump and the then part runs. With 90, the bgt would jump straight to endif and only “Next enemy” would come out.

How to invert a condition

Inverting is not flipping the symbol around: it is finding the condition that holds exactly when the if condition does not. Between them they have to share out every case, leaving none out and with none falling into both. The case that decides it is the equal one. With the hit of 40:

If conditionOppositeBranch to endifWith hp = 40Why
hp <= hithp > hitbgt $t3, $t5, endifNo jump: the then part runs40 <= 40 is true, so the 40 has to stay in the then part
hp < hithp >= hitbge $t3, $t5, endifJumps40 < 40 is false: the 40 goes with the opposite
hp == hithp != hitbne $t3, $t5, endifNo jumpOnly the 40 gets into the then part
hp != hithp == hitbeq $t3, $t5, endifJumpsThe 40 is the only one that skips the then part

The short rule: the equals sign changes sides. If the if condition has it (<=, >=), the opposite does not (>, <), and the other way round. Equal and not equal swap with each other.

Inverting <= into >=. In the hook’s counter, bge $t3, $t5, next also skips the enemy with 40, which does fall in one hit, and the program prints 2 instead of 3. Since the number looks like the right one, only testing the boundary value gives it away.

The table so you do not have to think about it every time:

In the if you write…The branch to endif is…
a == bbne a, b, endif
a != bbeq a, b, endif
a < bbge a, b, endif
a <= bbgt a, b, endif
a > bble a, b, endif
a >= bblt a, b, endif
a == 0bnez a, endif
a != 0beqz a, endif

Writing the branch with the if condition, as I did in the hook. The program assembles, runs and gives a number, but it is the opposite one: it counts the ones it should have skipped.

If-then-else: the j you cannot leave out

If there is also something to do when the condition does not hold, we need one more label: else. The branch with the opposite condition goes to else, and the then part ends with a j endif so it does not walk into it.

if (hp <= hit) then
    print "Falls in one hit"
else
    print "Resists: more hits needed"
endif
print "End of turn"
If-then and if-then-else in MIPSTwo flowcharts. On the left, if hp <= hit the program prints "Falls in one hit"; otherwise the branch bgt $t3, $t5, endif goes straight to endif. On the right, the no branch jumps with bgt to else (Resists) and the yes branch ends with j endif so it does not fall into else; both branches meet at endif.if … then … endifhp <= hit?YesFalls in one hitendif:Next enemyNobgt $t3, $t5,endifif … then … else … endifhp <= hit?YesFalls in one hitj endifendif:End of turnNobgt $t3, $t5,elseelse:Resists
The branch is written with the opposite condition (hp > hit) and goes to the label that skips the then part; the else also needs a j endif.

Look at the right-hand drawing: the yes branch has one more box, the j endif. In code:

# ifelse.s: it falls in one hit or it resists, but never both
        .data
hp:     .word 90                    # the enemy's HP
hit:    .word 40                    # the sword's damage
falls:  .asciiz "Falls in one hit\n"
resist: .asciiz "Resists: more hits needed\n"
turn:   .asciiz "End of turn\n"

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 90
        lw   $t5, hit               # $t5 = 40
        bgt  $t3, $t5, else         # opposite of (hp <= hit): go to else
        li   $v0, 4                 # then
        la   $a0, falls
        syscall
        j    endif                  # without this jump, it would fall into else too
else:   li   $v0, 4                 # else
        la   $a0, resist
        syscall
endif:  li   $v0, 4                 # both branches meet here
        la   $a0, turn
        syscall
        li   $v0, 10
        syscall

Output:

Resists: more hits needed
End of turn

90 is greater than 40, the bgt jumps to else and “Resists” is printed. Both branches meet at endif and “End of turn” always comes out.

And what happens if you forget the j endif? With 35 HP the then part runs… and then the else, because the else label is not a wall: it is just the address of the next instruction. Both sentences would come out. You will see it live in the exercises.

Before writing an if-else, put the three fixed pieces first: the branch with the opposite to else, the j endif at the end of the then part and both labels. Then fill in the two bodies.

The wave’s if-else, step by step

To translate any if-else, always do the same steps in the same order. With the one in ifelse.s:

StepWhat you writeWhy
1. Copy the if conditionhp <= hitIt is the one that decides when the then part runs
2. Invert ithp > hitThe branch has to happen when the then part must not run
3. Choose the targetelseIf there is an else, you jump there; if not, to endif
4. Write the branchbgt $t3, $t5, elseOpposite condition plus target
5. Below it, the then partprint “Falls in one hit”You only get here if the branch was not taken, that is, if hp <= hit
6. Close the then partj endifWithout it, the PC would keep adding 4 and walk into the else
7. The else: label and its bodyprint “Resists: more hits needed”You only get here with the branch from step 4
8. The endif: labelprint “End of turn”Both branches meet here
Check you’ve got it: which branch do you write if the if-else were the other way round: if (hp > hit) then “Resists” else “Falls in one hit”?

ble $t3, $t5, else. The if condition is now hp > hit, and its opposite keeps the equals sign: hp <= hit, which in MIPS is ble. Below it goes the “Resists”, then the j endif, and at else the “Falls in one hit”. With 90, the ble does not jump and “Resists” comes out; with 35 and with 40 it jumps to else and “Falls in one hit” comes out. The 40 is where you see whether you got it right: with blt, the 40 would not jump and the program would say that an enemy that falls in one hit resists.

Compound conditions with “and”

An enemy is a “two-hit” enemy if it has more than 40 HP (it does not fall to one) and at most 80 (it falls to the second). In pseudocode, if (hp > 40) and (hp <= 80).

With an “and”, one of the two conditions failing is enough not to run the then part. So it is written with two branches with the opposite condition, and both go to the same endif:

# and.s: a two-hit enemy has more than 40 HP AND at most 80
        .data
hp:     .word 60                    # the enemy's HP
two:    .asciiz "Two-hit enemy\n"
end_t:  .asciiz "End of the check\n"

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 60
        ble  $t3, 40, endif         # opposite of (hp > 40): the "and" no longer holds
        bgt  $t3, 80, endif         # opposite of (hp <= 80): neither
        li   $v0, 4                 # then: both hold
        la   $a0, two
        syscall
endif:  li   $v0, 4
        la   $a0, end_t
        syscall
        li   $v0, 10
        syscall

Output:

Two-hit enemy
End of the check

With 60: ble $t3, 40, endif does not jump (60 is not <= 40), bgt $t3, 80, endif does not either (60 is not > 80), and we reach the then part. With 35 it would leave at the first branch; with 120, at the second.

Compound conditions with “or”

My ice spell freezes the small enemies (hp < 40) or the very big ones (hp >= 120), which are slow. With an “or”, one holding is enough. That changes the pattern:

  1. The first condition jumps as it is to the then part: if it holds, there is no need to look at the other one.
  2. The last one jumps with the opposite to endif: if it does not hold either, none holds.

And that is why a new label appears, then, in front of the body:

# or.s: ice freezes the small ones (hp < 40) OR the very big ones (hp >= 120)
        .data
hp:     .word 120                 # the enemy's HP
frozen: .asciiz "Can be frozen\n"
end_t:  .asciiz "End of the check\n"

        .text
        .globl main
main:   lw   $t3, hp              # $t3 = 120
        blt  $t3, 40, then        # condition AS IT IS: if it holds, good enough
        blt  $t3, 120, endif      # opposite of the second one: if not either, out
then:
        li   $v0, 4               # then: one of the two holds (or both)
        la   $a0, frozen
        syscall
endif:  li   $v0, 4
        la   $a0, end_t
        syscall
        li   $v0, 10
        syscall

Output:

Can be frozen
End of the check

With 120, the first blt does not jump (120 is not < 40), but the second does not either (120 is not < 120), so we fall into the then part. With 15 the first one would have jumped straight to then; with 60 the second would have jumped to endif.

"And" condition versus "or" conditionTwo columns of code. In the "and", both instructions jump with the opposite condition to the same endif: one failing is enough not to count. In the "or", the first one jumps with the condition as it is to then and only the second jumps with the opposite to endif. Below, what happens with HP of 60, 35 and 120 in the "and" and 15, 120 and 60 in the "or"."and": 40 < hp <= 80ble $t3, 40, endifbgt $t3, 80, endifaddi $s0, $s0, 1endif: …With data from the wave:hp 60: passes both and countshp 35: leaves at the first onehp 120: leaves at the second one"or": hp < 40 or hp >= 120blt $t3, 40, thenblt $t3, 120, endifthen: addi $s0, $s0, 1endif: …With data from the wave:hp 15: gets in with the first onehp 120: fails the 1st, gets in with the 2ndhp 60: fails both and leaves
In the "and" every branch goes to the exit; in the "or", all but the last one go to then.

The drawing puts both ideas together: in the “and” every arrow goes to the exit; in the “or”, all but the last go to then. If it is hard to remember, think about what you need to decide: in an “and”, a single “no” decides; in an “or”, a single “yes” decides.

Writing an “or” as if it were an “and”, with both opposites jumping to endif. With two separate ranges (less than 40 and 120 or more) no number passes both, so the counter stays at 0.

Mixing them: (a and b) or c

Labs and exams mix both. The enemies that drop a potion are the two-hit ones or the final boss: if ((hp > 40) and (hp <= 80)) or (hp >= 200). It is solved piece by piece:

  • If the first part of the “and” fails (hp <= 40), the “and” no longer holds, but the other side of the “or” is still left: the branch goes to an intermediate label, other.
  • If the whole “and” holds, that is enough: jump to then.
  • The last condition (hp >= 200) goes with the opposite to endif.
# mixed.s: two-hit enemies (40 < hp <= 80) or the boss (hp >= 200) drop a potion
        .data
hp:     .word 200                 # the enemy's HP
potion: .asciiz "Drops a potion\n"
end_t:  .asciiz "End of the check\n"

        .text
        .globl main
main:   lw   $t3, hp              # $t3 = 200
        ble  $t3, 40, other       # the "and" fails: the other side of the "or" is still left
        ble  $t3, 80, then        # the whole "and" holds: good enough
other:  blt  $t3, 200, endif      # opposite of (hp >= 200): nothing holds
then:
        li   $v0, 4               # then
        la   $a0, potion
        syscall
endif:  li   $v0, 4
        la   $a0, end_t
        syscall
        li   $v0, 10
        syscall

Output:

Drops a potion
End of the check

With 200: the first ble does not jump, the second does not either (200 is not <= 80), we reach other, and since 200 is not < 200, we get into the then part.

With a mixed condition, draw the flowchart first with one diamond per condition. Each “no” and “yes” arrow becomes a branch, and the labels come out by themselves: the destination of each arrow.

Loops: for, while and do-while

A MIPS loop has nothing new: it is a backward jump (j loop) that repeats a piece of code and a forward branch that breaks it when it is time. What changes between the three kinds is where the condition is checked.

The for loop: walking through the wave

The most common case in IC1: walking through an array of words. You need four registers, always with the same role:

RegisterRoleAt the startEvery lap
$t0pointer to the current elementla $t0, waveaddi $t0, $t0, 4
$t1how many elements there arelw $t1, ndoes not change
$t2the index ili $t2, 0addi $t2, $t2, 1
$s0the result (sum, count…)li $s0, 0depends on the problem

This is how we add up the HP of the whole wave:

# for.s: the wave's total HP, enemy by enemy
        .data
wave:   .word 35, 80, 40, 120, 15, 60, 90, 200   # each enemy's HP
n:      .word 8                    # how many enemies there are
txt:    .asciiz "Total HP of the wave: "

        .text
        .globl main
main:   la   $t0, wave             # pointer to the first enemy
        lw   $t1, n                # $t1 = 8
        li   $t2, 0                # i = 0
        li   $s0, 0                # total = 0
for:    beq  $t2, $t1, endfor      # stop condition: i == n
        lw   $t3, 0($t0)           # enemy i's HP
        add  $s0, $s0, $t3         # total = total + hp
        addi $t0, $t0, 4           # the pointer moves one word
        addi $t2, $t2, 1           # i = i + 1
        j    for                   # and another lap
endfor:
        li   $v0, 4
        la   $a0, txt
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 10
        syscall

Output:

Total HP of the wave: 640

35 + 80 + 40 + 120 + 15 + 60 + 90 + 200 = 640. The stop condition goes at the top, before reading: beq $t2, $t1, endfor. With i starting at 0, in the lap where i is 8 there is nobody left to read and we leave. The laps that run are i = 0, 1, …, 7: eight, exactly the enemies there are.

Why +4 on the pointer? Because each HP value is a word (.word) and takes 4 bytes: enemy 0 is at wave + 0, enemy 1 at wave + 4, enemy 7 at wave + 28. The index counts enemies; the pointer, bytes.

With i from 0, stopping with bgt $t2, $t1, end (“if i > n”). It lets the lap with i = n through and reads the word right after the array: one lap too many. With i from 0, the stop is beq (or bge); bgt only fits if i goes from 1 to n, as in the example in the lab book.

The trace of for.s, lap by lap

First, the translation in words. In pseudocode: “for i from 0 while i < n: total = total + wave[i]”. To carry on, i < n; the opposite, the one that takes you out of the loop, is i >= n. Since i goes up 1 by 1 from 0, the first time it stops being less than n it is exactly n, so beq $t2, $t1, endfor is enough (bge would do the same). And the last thing in the body is the j for, which takes the PC back to the beq to ask again.

Now the trace. In QtSpim, .data starts at 0x10010000, so that is where wave is and where $t0 points at the start. Each row is a lap: the registers as they are when reaching the beq, and the total after the add:

Lap$t2 (i)$t0 (pointer)beq jumps?$t3 (hp)$s0 (total)Why
100x10010000No (0 is not 8)3535First enemy, at wave + 0
210x10010004No80115The pointer has added 4 and the index 1
320x10010008No40155Again +4 and +1
430x1001000cNo12027512 in hexadecimal is c
540x10010010No1529016 in hexadecimal is 10
650x10010014No60350+4 and +1
760x10010018No90440+4 and +1
870x1001001cNo200640Last enemy, at wave + 28
—80x10010020Yes (8 is 8)—640It leaves without reading: at wave + 32 there is already n, not an enemy

The pointer and the index always move together: if in your trace one of them stands still in a row, that is where the bug is.

Check you’ve got it: how many times does the beq in for.s run, and how many times the j for?

The beq, 9 times; the j for, 8. The beq runs at the start of every lap (8) and once more, with i = 8, which is the one that jumps to endfor. The j for only runs at the end of a complete lap, so there is one per enemy. It is the count for any loop with the stop at the top: n + 1 checks and n backward jumps.

The while loop with a compound condition

Now I attack the enemies in order while there are enemies left and I have energy for the next one (each one costs me as much energy as its HP; I start with 200). It is the kind of loop that shows up most in the lab exams: a counter condition and another one that can stop early.

# while.s: I attack while there are enemies left AND I have energy for the next one
        .data
wave:   .word 35, 80, 40, 120, 15, 60, 90, 200   # each enemy's HP
n:      .word 8                     # how many enemies there are
energy:  .word 200                  # each enemy costs me as much energy as its HP
t_def:  .asciiz "Enemies defeated: "
t_ene:  .asciiz "\nEnergy I have left: "

        .text
        .globl main
main:   la   $t0, wave              # pointer to the first enemy
        lw   $t1, n                 # $t1 = 8
        lw   $s1, energy            # $s1 = 200
        li   $t2, 0                 # i = 0 (it also counts the defeated)
while:
        beq  $t2, $t1, endw         # opposite of (i < n): no enemies left
        lw   $t3, 0($t0)            # enemy i's HP
        blt  $s1, $t3, endw         # opposite of (energy >= hp): not enough
        sub  $s1, $s1, $t3          # I spend the energy it costs
        addi $t0, $t0, 4            # next enemy
        addi $t2, $t2, 1            # i = i + 1
        j    while
endw:   li   $v0, 4
        la   $a0, t_def
        syscall
        li   $v0, 1
        move $a0, $t2
        syscall
        li   $v0, 4
        la   $a0, t_ene
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 10
        syscall

Output:

Enemies defeated: 3
Energy I have left: 45

The while condition is an “and”, so it is written like any “and”: two branches with the opposite, both to the exit (endw). The first looks at the counter; the second, at the energy. Lap by lap:

LapiHPenergy >= HP?energy after
1035200 >= 35, yes165
2180165 >= 80, yes85
324085 >= 40, yes45
4312045 >= 120, no: leaves45

When it leaves, i is 3: the lap counter is also the number of enemies defeated.

The order of both checks matters. The counter goes first and the one that reads from the array second: if there are no enemies left, you do not want to read the HP of an enemy that does not exist.

The do-while loop

In a do-while the body comes first and the condition at the end, so it runs at least once. I hit an enemy with 90 HP until it falls:

# dowhile.s: I hit until the enemy falls (there is always at least one hit)
        .data
hp:     .word 90                    # the enemy's HP
hit:    .word 40                    # the sword's damage
t_hits: .asciiz "Hits to defeat it: "
t_hp:   .asciiz "\nHP at the end: "

        .text
        .globl main
main:   lw   $t3, hp                # $t3 = 90
        lw   $t5, hit               # $t5 = 40
        li   $s0, 0                 # hits = 0
do:     sub  $t3, $t3, $t5          # one hit: hp = hp - hit
        addi $s0, $s0, 1            # hits = hits + 1
        bgtz $t3, do                # while hp > 0, another hit
        li   $v0, 4
        la   $a0, t_hits
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 4
        la   $a0, t_hp
        syscall
        li   $v0, 1
        move $a0, $t3
        syscall
        li   $v0, 10
        syscall

Output:

Hits to defeat it: 3
HP at the end: -30

90 − 40 = 50, 50 − 40 = 10, 10 − 40 = −30: three hits, and the HP ends at −30 (the last hit was more than needed). Notice that here the branch that repeats is the conditional one (bgtz, “branch if greater than zero”, a real MIPS instruction) and no j is needed: if the condition holds, it goes back up; if not, it carries on down. One branch less per lap.

for / whiledo-while
Where it is checkedat the top, before the bodyat the bottom, after the body
Minimum laps01
Branchesa conditional one that leaves + j that goes backa conditional one that goes back
When to use itwalking through an array (it may be empty)repeating until something happens, like hitting until it falls

The loop-with-if template

With everything together we can now fix the counter from the start. The same program, with just one change: the branch goes with the opposite condition, bgt.

loop:   beq  $t2, $t1, end     # if i == n, the wave is over
        lw   $t3, 0($t0)       # $t3 = enemy i's HP
        bgt  $t3, $t5, next    # OPPOSITE condition: if hp > hit, it does not count
        addi $s0, $s0, 1       # counter = counter + 1
next:
        addi $t0, $t0, 4       # next enemy (one word = 4 bytes)
        addi $t2, $t2, 1       # i = i + 1
        j    loop              # back to the start of the loop

Output:

Enemies that fall in one hit: 3

Now yes: 35, 40 and 15. And this is how the loop looks in the text segment:

The loop of fall.s in the text segmentThe loop instructions from address 0x00400040 (loop) to 0x00400060 (end). beq jumps forward to end when i == n, the bne that comes from bgt jumps to next when the HP is greater than the hit, and j goes back to loop.AddressWhat is really in memory00400040beq $10, $9, 32loop:00400044lw $11, 0($8)00400048slt $1, $13, $110040004cbne $1, $0, 800400050addi $16, $16, 100400054addi $8, $8, 4next:00400058addi $10, $10, 10040005cj 0x0040004000400060ori $2, $0, 4end:i == n:exithp > hit:not countedj loop:another lapThe one-line bgt is two real instructions (slt + bne). The addresses are the ones QtSpim shows.
A loop in MIPS is a backward jump (j loop) and at least one forward branch that breaks it (beq … end).

This shape (stop at the top, read, if with the opposite, move pointer and index, j to the start) is the template you will use most in IC1. Almost every walk-through-an-array exercise is this same thing with another body.

The template’s bugs, in the trace

Almost everything that goes wrong in a loop with an if is the condition inverted badly or the jump back in the wrong place. With the hook’s counter you can see them enemy by enemy. First, the condition:

HPFalls in one hit?ble (the hook): counts?bge (equals sign inverted badly): counts?bgt (right): counts?
35YesNoYesYes
80NoYesNoNo
40YesNoNoYes
120NoYesNoNo
15YesNoYesYes
60NoYesNoNo
90NoYesNoNo
200NoYesNoNo
Total3523

The ble column is the exact opposite of the right one: the addi only runs when there is no jump, and the ble does not jump precisely with the ones that resist. The bge one fails in a single row, the 40 one.

Then, the jump back. With the condition already fixed (bgt):

Bug in the jump backWhat comes outWhy
You forget the j loop“Enemies that fall in one hit: 1”After the first enemy (35, which counts), the PC keeps adding 4 and falls into end: the loop does a single lap
The loop label is one line lower, on the lwIt never ends, and when the pointer reaches 0x10020000 the Bad address warnings startThe j goes back below the stop: the beq only runs the first time and nothing cuts the loop, which keeps reading whatever is after the array

When SPIM complains

Branches have a mistake all of their own: the misspelt label. This program jumps to endiff (with two f’s), but the label is called endif:

# error.s: a misspelt label
        .data
hp:     .word 35
hit:    .word 40

        .text
        .globl main
main:   lw   $t3, hp
        lw   $t5, hit
        bgt  $t3, $t5, endiff       # the label is called endif...
        addi $t3, $t3, 1
endif:  li   $v0, 10
        syscall

SPIM loads it without complaining. The warning comes when it runs, right when it reaches the branch:

Instruction references undefined symbol at 0x00400038
  [0x00400038]	0x14200000  bne $1, $0, 0 [endiff-0x00400034]

The message gives you the address (0x00400038), the instruction and the name that does not exist: endiff. And if you look at the offset of the bne, you will see a 0: the assembler did not know where to jump.

Other usual scares:

SymptomLikely cause
The result is exactly the opposite (5 instead of 3)The branch carries the if condition instead of the opposite
Both sentences of the if-else come outThe j endif at the end of the then part is missing
The “or” counter stays at 0Both conditions of the “or” jump to endif
One lap too many and a strange valueThe stop does not match the index (bgt with i from 0)
It never ends and Bad address warnings appearThe index does not move (its addi is missing) and the pointer leaves the data
Instruction references undefined symbolThe branch label does not exist (misspelt)

Try it in QtSpim (or right here)

Branches make sense when you watch the PC move. Open QtSpim (or the playground below, which works the same) with the loop template:

Loading the MIPS playground… If it does not show up, copy fall.s into your QtSpim.

  1. Load fall.s and run it step by step with F10. Watch the PC in the register panel: it keeps adding 4 until the j loop, and then it suddenly goes back to 0x00400040.
  2. In the first lap (HP 35), right after the slt $1, $13, $11, register $1 ($at) is 0: that slt is the translated bgt, with the registers swapped, and it asks “hit < hp?”, 40 < 35, which is false. The bne does not jump and the enemy counts. In the second lap (HP 80), $at is 1 and the bne jumps to next.
  3. Put a breakpoint on the addi $s0, $s0, 1 and press F5 several times: it only stops three times, with the enemies 35, 40 and 15.
  4. Change the bgt to bge and run it: you get 2, because the enemy with 40 no longer counts. That is how much the = matters.
  5. Change the stop beq $t2, $t1, end to bgt $t2, $t1, end: you get 4. There is one lap too many (with i = 8) that reads the word after the array, n, which is 8… and 8 also “falls in one hit”.
  6. Delete the addi $t2, $t2, 1 and run it: the index never reaches 8, the pointer keeps moving through memory and ends up leaving the data segment. SPIM starts warning with Bad address in data/stack read: 0x10020000 and the program does not end until you stop it.

Summary

ConceptThe essentials
Real branchesbeq (if ==), bne (if !=) and j (always); a label is just an address
sltDoes not jump: leaves 1 if less and 0 otherwise; slti with a number; sltu unsigned
Greater thanSwap the order: a > b is b < a
Pseudo-instructionsblt, bgt, ble, bge = slt + beq/bne with $at; beqz/bnez = beq/bne with $zero
If-thenBranch with the opposite condition to endif
If-then-elseOpposite to else and j endif at the end of the then part
“and”Every opposite jumps to endif
“or”All but the last jump as they are to then; the last one, with the opposite, to endif
For / while loopStop at the top with a forward branch, j back; pointer +4 per word
Do-whileBody first; the conditional branch at the end goes back up

Three ideas to take away

  1. In assembly a branch does not run what is below it: it skips it. That is why an if is written with the opposite condition, the one that takes you to endif.
  2. The processor only knows how to jump if two registers are equal or different. Everything else (<, >, <=, >=) is slt + beq/bne, and the assembler does it for you with $at.
  3. A loop is a backward jump and a forward branch that breaks it. Take care of the stop (beq with i from 0) and make sure the index and the pointer move every lap.

In the branches, conditionals and loops practice we take the wave to three complete programs: a report enemy by enemy with if-else, three spells with “and” and “or” conditions, and a fight that stops when the energy runs out.

Next step: practiceBranches, conditionals and loops in MIPS — practice in QtSpim: the wave report, three spells with “and” and “or” and a fight that stops in time (and the hero who ended with negative energy)

Did this article help you? Here is how you can support SergioLearns →