In MIPS, there are only two types of instructions for controlling program flow, branches and jumps. As a MIPS program executes, the instructions are run sequentially from top to bottom and will only stop once they reach the end or encounter a branch or jump.
Labels allow us to assign a human-readable name to a particular place in code. Labels point to a specific line of code, they do not encapsulate code in any way from the code surrounding it. Take this example:
LOOP: slt $t0, $t1, $t2
beq $t0, $zero, EXIT
... more instructions here
j LOOP
EXIT: addi $t7, $t3, 3
...
Here, LOOP
labels the first instruction, slti
. The assembler has no idea that LOOP
is labeling a section of code that makes up the body of the loop, it just knows that j LOOP
means "jump to that instruction and start executing from there".
This misconception that MIPS has true "code sections" causes a lot of confusion. MIPS code runs from top-to-bottom: labels just make it easier to tell the computer how far to hop back upstream (or downstream).
beq
, bne
, blez
, and others are all branch instructions. These will jump to a label only if a particular condition is met. Taking the same code as earlier:
LOOP: slt $t0, $t1, $t2
beq $t0, $zero, EXIT
... more instructions here
j LOOP
EXIT: addi $t7, $t3, 3
...
The second line, beq
, tells the computer to do the following:
- Compare $t0 and $zero.
- If they're the same, jump to
EXIT
- If they're not the same, continue to the next instruction
Colloquially, when a branch instruction leads to a jump (in beq
's case, this means the registers contained equal values), the branch is said to be "taken". In the code example above, the branch gets "taken" if and only if $t1 ≮ $t2
, which can be re-written as $t2 ≤ $t1
.