Skip to content

Instantly share code, notes, and snippets.

@stevenpetryk
Last active March 25, 2016 23:31
Show Gist options
  • Save stevenpetryk/36abb464e4a17dbbeb95 to your computer and use it in GitHub Desktop.
Save stevenpetryk/36abb464e4a17dbbeb95 to your computer and use it in GitHub Desktop.

Labels and branches in MIPS

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

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

Branch instructions

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:

  1. Compare $t0 and $zero.
  2. If they're the same, jump to EXIT
  3. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment