Load, arithmetic and logic in MIPS — theory with a hero’s sheet, lb versus lbu, hi and lo and bit masks (and the poison that healed me)

Second IC1 lab session. I already knew how to store my character’s sheet in .data, so that day’s task looked like a walk in the park: apply a poison that takes away 15 HP. I stored the poison as a negative byte, added it to the HP and that was it:

# hook.s: the poison that healed me
        .data
hp:     .half 100                  # the hero's HP
poison: .byte -15                  # the poison takes away 15 HP
txt:    .asciiz "HP after the poison: "
        .text
        .globl main
main:   lh   $t0, hp               # $t0 = 100
        lbu  $t1, poison           # $t1 = the poison (-15?)
        add  $t0, $t0, $t1         # hp = hp + poison
        li   $v0, 4
        la   $a0, txt
        syscall
        li   $v0, 1                # print the HP that is left
        move $a0, $t0
        syscall
        li   $v0, 10
        syscall

Assemble, F5, and on the console:

HP after the poison: 341

341? My hero had 100 HP, drank a poison and ended up with more than three times as much. No error, no warning. The bug was a single letter: the u in lbu. That byte held a -15 (f1 in hexadecimal), but lbu reads it unsigned and turns it into 241. 100 + 241 = 341. With lb, which keeps the sign, it would have been 100 − 15 = 85.

Today is about everything you do with the data once it is in memory: reading and writing it with the right size (lw, lh, lb, lbu, sw, sh, sb), loading big constants, adding and subtracting without the result wrapping around, multiplying and dividing with the hi and lo registers, and touching single bits with masks and shifts. Our running example is the hero’s sheet: gold, HP, level, strength and awards. If you are new here, start with the theory of MIPS program structure and data, where we saw how that data is laid out in memory; and when you finish, the load, arithmetic and logic practice has three complete programs waiting for you in QtSpim.

Before you start. From the earlier topics you need three things. First, the theory of MIPS program structure and data: how data is stored in .data with .word, .half, .byte and .asciiz, that a label such as sheet is the name of an address, and that la gives you the address and lw what is inside it. Second, reading the Data tab in little endian and going from hexadecimal to binary 4 bits at a time (c is 1100, b is 1011). Third, two’s complement: in a byte, −2 is fe, and the leftmost bit says whether the number is negative. The topic goes in this order: the golden rule and how each address is computed; how many bytes each load reads, signed or unsigned, alignment and stores; big constants and the pseudoinstructions (li, la, move); adding, subtracting and overflow, and hi and lo; and finally, the bits: logic operations, masks and shifts. If at any point you get lost, go back to the same question: is the data in a register or in memory, and how many bits am I looking at?

The golden rule of MIPS: you compute in registers

MIPS is a load/store architecture: arithmetic and logic instructions only work with registers. There is no “add whatever is at this memory address”. To operate on a value that lives in memory there are always three steps:

  1. Load the value from memory into a register (lw, lh, lb…).
  2. Operate in registers (add, sub, and, sll…).
  3. Store the result from the register back to memory (sw, sh, sb).

Why the round trip? Because registers are 32 slots inside the processor, extremely fast, and memory has millions of positions outside it. Reading memory costs more, so MIPS makes you do it on purpose.

Register and memory, in plain words

The whole topic rests on this difference. A register is a 32-bit slot inside the processor, with its own name ($t0, $s0, $zero…): there are 32 of them, and they are the only thing the processor can add, compare or shift bits with. Memory is a very long row of one-byte slots outside the processor, each with its own house number: the address. A label such as sheet is not data, it is the name of one of those houses (0x10010000).

RegisterMemoryWhy it matters
Where it isInside the processorOutside, on the other side of the busGoing to memory takes longer than using a register
How you name itBy its number: $t0 is 8, $s0 is 16By its address: 0x10010000, or a labelA register number fits in 5 bits; an address needs 32
Size of each slot32 bits, always1 byte; a word takes 4 slots in a rowThat is why you have to say how many bytes you want when you read (lw, lh, lb)
What you can do with itOperate: add, subtract, compare, shiftOnly read and writeHence the golden rule: load, operate and store

With the sheet: the gold (2750) lives in memory, at 0x10010000. To pay 500 to the trainer, lw $t2, 0($s0) brings it into a register, addi $t2, $t2, -500 subtracts there and sw $t2, 0($s0) puts 2250 back in its slot.

Operating on the register and forgetting the sw. The register holds 2250, but the sheet still says 2750: until you store, the change only exists inside the processor.

Every load and store has the same shape: instruction $register, offset($base). The address accessed is the contents of $base plus the offset, a signed 16-bit number written as is.

        la   $s0, sheet            # $s0 = 0x10010000, the address of the sheet
        lw   $t0, 0($s0)           # reads the word at 0x10010000 + 0
        lh   $t1, 6($s0)           # reads the halfword at 0x10010000 + 6

That is how any data structure works in assembly: a base address in a register and each field at a fixed distance from it. When you write hero.hp in C, the compiler does exactly this.

The address, computed step by step

offset($base) reads like this: “go to the address I have in $base, move forward that many bytes and read (or write) from there”. The processor does the addition when it executes; you choose the base and the offset. With the sheet you will see in full in the next section (gold at +0, the two HP values at +4 and +6, and level, luck, strength and awards at +8, +9, +10 and +11):

LineBaseOffsetAddressBytes it touchesWhy
la $s0, sheet———nonela does not read memory: it leaves the number 0x10010000 in $s0
lw $t0, 0($s0)0x1001000000x10010000from …00 to …03Gold is the first field: base + 0
lh $t1, 6($s0)0x1001000060x10010006…06 and …07Before it come the gold (4 bytes) and the max HP (2): 4 + 2 = 6
lb $t2, 9($s0)0x1001000090x10010009only …09Luck comes right after the level, which is at +8
sw $t2, 0($s0)0x1001000000x10010000from …00 to …03Same calculation as the lw, but it writes: this is how the gold goes back after paying

The base does not change in any line: what tells one field from another is the offset. And the offset is signed: if $s1 pointed to the level (0x10010008), the gold would be read with lw $t0, -8($s1), because 0x10010008 − 8 = 0x10010000. With 16 bits it reaches from −32768 to 32767 bytes around the base.

The lw $t0, gold with a label we used in topic 1 is a pseudoinstruction: the assembler turns it into a lui that puts the address in $at and an lw with an offset on $at. Underneath it is always offset($base).

How much you read: lw, lh and lb

The instruction decides how many bytes you read from the computed address:

InstructionReadsThe address must beFor data of type
lw4 bytes (a word)a multiple of 4.word
lh / lhu2 bytes (a halfword)even.half
lb / lbu1 byteanything.byte, characters of a string

Here is the hero’s full sheet. It is 12 bytes: gold in a word, the two HP values in halfwords and four one-byte values. The program reads each field with the instruction of its size:

# load.s: the hero's sheet and four ways to read it
        .data
sheet:  .word 2750                 # +0  gold (4 bytes)
        .half 120                  # +4  max HP (2 bytes)
        .half 85                   # +6  current HP (2 bytes)
        .byte 7                    # +8  level
        .byte -2                   # +9  luck: can be negative
        .byte 200                  # +10 strength: 0 to 255, unsigned
        .byte 0x0B                 # +11 awards: eight switches
t_gold: .asciiz "Gold (lw):        "
t_hp:   .asciiz "\nHP (lh):          "
t_luck: .asciiz "\nLuck (lb):        "
t_plb:  .asciiz "\nStrength (lb):    "
t_plbu: .asciiz "\nStrength (lbu):   "
        .text
        .globl main
main:   la   $s0, sheet            # $s0 = base address of the sheet
        lw   $t0, 0($s0)           # gold: 4 bytes from sheet+0
        lh   $t1, 6($s0)           # current HP: 2 bytes from sheet+6, signed
        lb   $t2, 9($s0)           # luck: 1 signed byte
        lb   $t3, 10($s0)          # strength read as signed...
        lbu  $t4, 10($s0)          # ...and as unsigned
        li   $v0, 4
        la   $a0, t_gold
        syscall
        li   $v0, 1
        move $a0, $t0
        syscall
        li   $v0, 4
        la   $a0, t_hp
        syscall
        li   $v0, 1
        move $a0, $t1
        syscall
        li   $v0, 4
        la   $a0, t_luck
        syscall
        li   $v0, 1
        move $a0, $t2
        syscall
        li   $v0, 4
        la   $a0, t_plb
        syscall
        li   $v0, 1
        move $a0, $t3
        syscall
        li   $v0, 4
        la   $a0, t_plbu
        syscall
        li   $v0, 1
        move $a0, $t4
        syscall
        li   $v0, 10
        syscall
Gold (lw):        2750
HP (lh):          85
Luck (lb):        -2
Strength (lb):    -56
Strength (lbu):   200

Look at the drawing: each field sits at a fixed offset from $s0, and the dump in QtSpim’s Data tab shows it byte by byte (remember QtSpim is little endian: the least significant byte of each word goes on the left).

[10010000]    00000abe  00550078  0bc8fe07  646c6f47    . . . . x . U . . . . . G o l d
The hero's sheet in memoryTwelve bytes from 0x10010000: gold in the word at +0 (be 0a 00 00), max HP at +4 (78 00), current HP at +6 (55 00) and four bytes at +8: level 07, luck fe, strength c8 and awards 0b. Next to them, the offset and the instruction that reads each field.+0+1+2+30x10010000be0a00000x10010004780055000x1001000807fec80b+0goldlw $t0, 0($s0)+4max HPlh …, 4($s0)+6current HPlh $t1, 6($s0)+8levellbu …, 8($s0)+9lucklb $t2, 9($s0)+10strengthlbu $t4, 10($s0)+11awardslbu …, 11($s0)$s0 = 0x10010000: everything is measured from the baseAddress = $s0 + offset. Each row is one word; +0 to +3 from left to right.
Each field is read with the instruction of its size: lw 4 bytes, lh 2 and lb/lbu 1.

Between the lines:

  • lw $t0, 0($s0) reads the four bytes be 0a 00 00, which in little endian are 0x00000abe = 2750.
  • lh $t1, 6($s0) reads 55 00 from address 0x10010006: 0x0055 = 85. Had you written lh $t1, 4($s0), you would get the max HP, 120.
  • lb $t2, 9($s0) reads the byte fe, which is −2 in two’s complement.
  • And now the interesting part: the same byte c8 comes out as −56 with lb and as 200 with lbu. Which one is right? It depends on what you stored.
Check you’ve got it: with the same $s0, what address do lhu $t5, 4($s0) and lb $t6, 11($s0) compute, and what value do they leave?

lhu $t5, 4($s0) computes 0x10010000 + 4 = 0x10010004, which is even, so there is no alignment problem. It reads 78 00, which in little endian is 0x0078 = 120: the max HP. lb $t6, 11($s0) computes 0x1001000B and reads one byte, 0b. Its bit 7 is 0 (0000 1011), so the sign fills with zeros and you get 11: the awards. Here lb and lbu give the same; they only differ when bit 7 is 1.

Signed or unsigned: lb versus lbu

A register has 32 bits, but lb only brings 8 from memory. What fills the top 24? That is the difference:

  • lb (load byte) does sign extension: it copies bit 7 of the byte into the top 24 bits. If the byte starts with 1, the register fills with ones and the number is negative.
  • lbu (load byte unsigned) fills with zeros: the register is always between 0 and 255.
lb versus lbuThe byte c8 (1100 1000) has bit 7 set. lb copies that bit into the top 24 bits and the register becomes ffffffc8, which is -56; lbu fills them with zeros and it becomes 000000c8, which is 200.In memory (strength, sheet+10)c811001000bit 7 = 1lb $t3, 10($s0)copies bit 7 into the top 24ffffffc8= 0xffffffc8= -56lbu $t4, 10($s0)fills the top 24 with zeros000000c8= 0x000000c8= 200
The byte is the same; what changes is what fills the top 24 bits.

c8 is 1100 1000: its bit 7 is 1. lb turns it into 0xffffffc8, which is −56; lbu, into 0x000000c8, which is 200. lh and lhu do the same, but copying bit 15 of the halfword.

Your valueStored withRead withWhy
Can be negative (luck, a poison, a temperature).byte -2lbThe sign must be kept
Never negative (strength 0-255, an ASCII character, a bit field).byte 200lbuWith lb, anything above 127 comes out negative
Signed / unsigned halfword.halflh / lhuSame idea with 16 bits

Reading a signed value with lbu (my 341 poison) or an unsigned value with lb (the −56 strength). Neither gives an error: the program carries on with a number that looks valid. Before writing the load, ask yourself whether that byte can be negative.

lw has no u version because it already brings all 32 bits: there is nothing left to fill.

Alignment: lw only at multiples of 4

In topic 1 we saw that SPIM places each .word at a multiple of 4 and each .half at an even address. It is not a whim: the processor requires it when you read or write. What happens if you ask for a word at an address that is not a multiple of 4?

# align.s: a word that does not start at a multiple of 4
        .data
sheet:  .word 2750                 # +0 gold
        .half 120                  # +4 max HP
        .half 85                   # +6 current HP
        .text
        .globl main
main:   la   $s0, sheet
        lw   $t0, 6($s0)           # I want the current HP... with lw
        li   $v0, 1
        move $a0, $t0
        syscall
        li   $v0, 10
        syscall

The console:

  Exception 4  [Address error in inst/data fetch]  occurred and ignored
0

And in QtSpim’s messages panel:

Exception occurred at PC=0x00400028
  Unaligned address in inst/data fetch: 0x10010006

The requested address is 0x10010000 + 6 = 0x10010006, which is not a multiple of 4. The processor raises exception 4 (Address error in inst/data fetch), SPIM’s handler logs it, skips the instruction and the program goes on: that is why $t0 stays at 0 and a 0 gets printed. QtSpim also pops up an error window.

InstructionValid addressExample that fails
lw, swmultiple of 4 (ending in 0, 4, 8 or c in hexadecimal)lw $t0, 6($s0) with $s0 = 0x10010000
lh, lhu, shevenlh $t0, 9($s0)
lb, lbu, sbanythingnever fails because of alignment

Working out a field’s offset by counting bytes by hand and forgetting the padding SPIM puts before a .word. If an lw fails with Unaligned address, check in the Data tab where the value really ended up.

Storing: sw, sh and sb

Stores are the mirror image of loads: sw writes the register’s 4 bytes, sh the bottom 2 and sb only the bottom byte. Whatever is around it in memory is left alone. Our hero levels up: one more level, 15 more max HP (and a full heal), and 500 gold paid to the trainer.

# store.s: the hero levels up and the sheet changes in memory
        .data
sheet:  .word 2750                 # +0 gold
        .half 120                  # +4 max HP
        .half 85                   # +6 current HP
        .byte 7                    # +8 level
        .text
        .globl main
main:   la   $s0, sheet            # $s0 = base address
        lbu  $t0, 8($s0)           # level = 7
        addi $t0, $t0, 1           # level + 1
        sb   $t0, 8($s0)           # sb writes ONLY 1 byte
        lhu  $t1, 4($s0)           # max HP = 120
        addi $t1, $t1, 15          # each level gives 15 HP
        sh   $t1, 4($s0)           # sh writes 2 bytes
        sh   $t1, 6($s0)           # levelling up heals completely
        lw   $t2, 0($s0)           # gold = 2750
        addi $t2, $t2, -500        # the trainer charges 500 (there is no subi)
        sw   $t2, 0($s0)           # sw writes all 4 bytes
        li   $v0, 10
        syscall

This program prints nothing: the result is in memory. Before running it, the Data tab shows this (it is the before.s program, which only has the data):

[10010000]    00000abe  00550078  00000007  00000000    . . . . x . U . . . . . . . . .

And after running store.s:

[10010000]    000008ca  00870087  00000008  00000000    . . . . . . . . . . . . . . . .

Let’s check it word by word:

  • 0x000008ca = 2250: the gold, 2750 − 500. Written by sw.
  • 0x00870087: both halfwords are 0x0087 = 135 = 120 + 15. Written by the two sh.
  • 0x00000008: the level goes from 7 to 8. sb only wrote the byte at 0x10010008; the three next to it are still 0.

To read a value you are going to store with sb or sh, use the unsigned version (lbu, lhu) if the value is never negative. That way the register holds the real value while you work, and only the bottom bytes go back when you store.

Big constants: li, lui and ori

MIPS immediates (the number inside addi, ori or an offset) have 16 bits. What if you need 200000, which is 0x00030D40 in hexadecimal and does not fit? That is what lui (load upper immediate) is for: it puts 16 bits in the upper half of a register and clears the lower half. Then an ori fills in the lower half.

# constant.s: a number that does not fit in 16 bits
        .text
        .globl main
main:   li   $t0, 200000           # 0x00030D40: does not fit in 16 bits
        li   $t1, 1500             # this one fits
        li   $t2, -1500            # and so does this one
        lui  $t3, 0x0003           # what li does, by hand: the top half...
        ori  $t3, $t3, 0x0D40      # ...and the bottom half
        li   $v0, 1
        move $a0, $t3              # prints 200000
        syscall
        li   $v0, 10
        syscall
200000

li is a pseudoinstruction, and QtSpim’s Text tab shows what the assembler turns it into:

[00400024] 3c010003  lui $1, 3                      ; 4: li $t0, 200000 # 0x00030D40: does not fit in 16 bits
[00400028] 34280d40  ori $8, $1, 3392
[0040002c] 340905dc  ori $9, $0, 1500               ; 5: li $t1, 1500 # this one fits
[00400030] 3c01ffff  lui $1, -1                     ; 6: li $t2, -1500 # and so does this one
[00400034] 342afa24  ori $10, $1, -1500
[00400038] 3c0b0003  lui $11, 3                     ; 7: lui $t3, 0x0003 # what li does, by hand: the top half...
[0040003c] 356b0d40  ori $11, $11, 3392             ; 8: ori $t3, $t3, 0x0D40 # ...and the bottom half

Between the lines:

  • li $t0, 200000 becomes two instructions: lui $1, 3 (upper half 0x0003 in $at, register 1) and ori $8, $1, 3392 (lower half 0x0D40 = 3392). $8 is $t0.
  • li $t1, 1500 fits in 16 bits and stays as one: ori $9, $0, 1500.
  • li $t2, -1500 needs two again, because an ori cannot set the top ones of a negative number.
  • The two hand-written lines, lui + ori, give exactly the same as the li on the first line.

That is why $at (register 1) is “reserved for the assembler”: it uses it for pseudoinstructions. Don’t keep anything of yours in it.

la, li and move: what you write and what runs

A pseudoinstruction is an instruction the processor does not have: the assembler replaces it with one or two real ones. The three you will write in every program, and what shows up in the Text tab:

You writeWhat runsWhat it doesWhy
li $t1, 1500ori $9, $0, 1500$t1 = 0 OR 1500 = 1500It fits in 16 bits: an OR with 0 leaves the number as is
li $t0, 200000lui $1, 3 and ori $8, $1, 3392Upper half in $at, lower half with oriIt does not fit in 16 bits: it has to be built in two halves
la $a0, t_gold (from load.s)lui $1, 4097 and ori $4, $1, 12$a0 = 0x1001000CAn address is 32 bits: the same recipe as li, with 4097 = 0x1001 on top and 12 below, because t_gold starts right after the sheet’s 12 bytes
move $a0, $t0addu $4, $0, $8$a0 = 0 + $t0Adding 0 is copying; with addu, a copy can never raise an overflow warning

Here you can see the difference between la and lw from topic 1: la $s0, sheet leaves the house number in $s0 without reading memory; lw $t0, sheet goes to that house and brings back what is inside (2750). With sheet, whose lower half is 0 (0x10010000), the assembler can skip the ori and leave just the lui.

Count instructions, not lines. li $v0, 4, la $a0, t_gold and syscall are three lines, but four real instructions (ori, lui, ori and syscall): 16 bytes of .text.

Adding and subtracting: add, addi and sub

Arithmetic instructions have three operands: destination, source 1, source 2. add $t2, $t0, $t1 means $t2 = $t0 + $t1. If the second source is a constant, the instruction ends in i: addi $t2, $t2, 5. A fight with the sheet:

# add.s: a fight in four instructions
        .data
attack:  .word 48
defense: .word 19
hp:      .word 85                  # the enemy's HP
txt:     .asciiz "Enemy HP: "
        .text
        .globl main
main:   lw   $t0, attack
        lw   $t1, defense
        sub  $t2, $t0, $t1         # dmg = attack - defense
        addi $t2, $t2, 5           # +5 from the enchanted sword
        lw   $t3, hp
        sub  $t3, $t3, $t2         # hp - dmg
        addi $t3, $t3, -1          # bleeding takes 1 more
        move $s0, $t3              # copy of the result in $s0
        add  $t3, $zero, $zero     # and $t3 goes back to 0
        li   $v0, 4
        la   $a0, txt
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 10
        syscall
Enemy HP: 50

Let’s do the maths: damage = 48 − 19 = 29; with the sword, 29 + 5 = 34; HP = 85 − 34 = 51; with the bleeding, 51 − 1 = 50.

Three details in this program that come up in every exam:

  • There is no subi. To subtract a constant you add its negative: addi $t3, $t3, -1.
  • $zero is always 0 and cannot be changed. add $t3, $zero, $zero sets a register to 0, and add $t2, $s1, $zero copies one register into another.
  • move is a pseudoinstruction: QtSpim turns it into addu $16, $0, $11, that is, $s0 = 0 + $t3.
I want to…InstructionExample
Add two registersadd $rd, $rs, $rtadd $t2, $t0, $t1
Add a constantaddi $rt, $rs, immaddi $t2, $t2, 5
Subtract two registerssub $rd, $rs, $rtsub $t2, $t0, $t1
Subtract a constantaddi with the negative constantaddi $t3, $t3, -1
Copy a registermove $rd, $rs (pseudo)move $s0, $t3
Set a register to 0add $rd, $zero, $zero (or li $rd, 0)add $t3, $zero, $zero

Overflow: add versus addu

A register holds signed integers between −2,147,483,648 and 2,147,483,647. What happens if you add one coin to 2,147,483,647?

# overflow.s: the gold that wrapped around
        .data
gold:   .word 2147483647           # the largest signed 32-bit integer
txt1:   .asciiz "With addiu: "
txt2:   .asciiz "\nWith addi:  "
        .text
        .globl main
main:   lw    $t0, gold
        addiu $t1, $t0, 1          # add without watching for overflow
        li    $v0, 4
        la    $a0, txt1
        syscall
        li    $v0, 1
        move  $a0, $t1
        syscall
        li    $v0, 4
        la    $a0, txt2
        syscall
        addi  $t2, $t0, 1          # the same addition, watched
        li    $v0, 1
        move  $a0, $t2
        syscall
        li    $v0, 10
        syscall
With addiu: -2147483648
With addi:    Exception 12  [Arithmetic overflow]  occurred and ignored
0
Exception occurred at PC=0x0040005c
  Arithmetic overflow
  • addiu (and addu, the u is for unsigned) does not watch for overflow: the result wraps around from the largest positive to the smallest negative, −2,147,483,648. Not a word.
  • addi (and add and sub) do watch: if the result does not fit, they raise exception 12 (Arithmetic overflow) and do not write the register. That is why $t2 stays at 0.

The gold that wrapped around, bit by bit

To see why 2,147,483,647 + 1 gives −2,147,483,648 you have to look at bit 31, the leftmost one: in two’s complement it holds the sign (0 positive, 1 negative). The largest positive is a 0 followed by 31 ones. We add 1 as in school, from right to left:

StepBits (4 at a time)HexadecimalRead as signedWhy
The gold0111 1111 1111 1111 1111 1111 1111 11110x7FFFFFFF2,147,483,647Bit 31 is 0 and all the others are 1: the largest positive
What you add0000 0000 0000 0000 0000 0000 0000 00010x000000011The 1 in the addiu (or a register holding 1 with addu)
Bits 0 to 30each one: 1 + 1 = 0, carry 1The carry runs leftwards through the 31 ones
Bit 310 + 0 + the carried 1 = 1The carry ends up in the sign bit
Result1000 0000 0000 0000 0000 0000 0000 00000x80000000−2,147,483,648Bit 31 is 1: for two’s complement, it is now negative

The bit addition is the same in both instructions. addiu (and addu) keeps those 32 bits; addi (and add) also looks at the signs: two positives cannot give a negative, so it raises exception 12 and does not write $t2. The rule, in words: an addition only overflows when both operands have the same sign and the result comes out with the opposite one. If the signs are different, as when you pay 500 gold (2750 + (−500)), the result lies between the two and can never overflow.

Check you’ve got it: $t0 holds −2,147,483,648 and $t1 holds 1. What happens with sub $t2, $t0, $t1? And with subu?

Subtracting 1 is adding −1: two negatives, 0x80000000 + 0xFFFFFFFF. The 32-bit result is 0x7FFFFFFF, which starts with 0: positive. Two negatives cannot give a positive: there is overflow. sub raises Arithmetic overflow (exception 12) and leaves $t2 unwritten; subu keeps the 32 bits and $t2 becomes 2,147,483,647, the largest positive.

Which one should you use? In the labs, add, addi and sub: if something overflows, you want to know. C compilers use addu and addiu, because C does not check for overflow.

Thinking the u in addu changes how it adds. The addition is exactly the same, bit by bit; the only difference is whether overflow is reported. Even addiu sign-extends its immediate.

Multiplying and dividing: hi and lo

Multiplying two 32-bit numbers can give a 64-bit one. That is why mult does not write to a normal register: it leaves the result in two special registers, hi (the top 32 bits) and lo (the bottom 32). And div uses the same two registers to give you two results at once: the quotient in lo and the remainder in hi. To get them out you have mflo and mfhi (move from lo / hi).

# multdiv.s: critical hits and shared loot
        .data
hit:     .word 34                  # damage of a normal hit
crit:    .word 3                   # a critical hit does triple
big:     .word 100000
loot:    .word 2750                # gold in the chest
party:   .word 4                   # players in the party
t_crit:  .asciiz "Critical (lo):  "
t_hi1:   .asciiz "\nCritical (hi):  "
t_bhi:   .asciiz "\nBig (hi):       "
t_blo:   .asciiz "\nBig (lo):       "
t_mul:   .asciiz "\nBig (mul):      "
t_quo:   .asciiz "\nEach one (lo):  "
t_rem:   .asciiz "\nLeft over (hi): "
        .text
        .globl main
main:   lw   $t0, hit
        lw   $t1, crit
        mult $t0, $t1              # hi:lo = 34 * 3
        mflo $s0                   # low part: 102
        mfhi $s1                   # high part: 0
        lw   $t2, big
        mult $t2, $t2              # hi:lo = 100000 * 100000 (does not fit in 32 bits)
        mfhi $s2
        mflo $s3
        mul  $s4, $t2, $t2         # mul keeps only the bottom 32 bits
        lw   $t3, loot
        lw   $t4, party
        div  $t3, $t4              # lo = quotient, hi = remainder
        mflo $s5
        mfhi $s6
        li   $v0, 4
        la   $a0, t_crit
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 4
        la   $a0, t_hi1
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t_bhi
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t_blo
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t_mul
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 4
        la   $a0, t_quo
        syscall
        li   $v0, 1
        move $a0, $s5
        syscall
        li   $v0, 4
        la   $a0, t_rem
        syscall
        li   $v0, 1
        move $a0, $s6
        syscall
        li   $v0, 10
        syscall
Critical (lo):  102
Critical (hi):  0
Big (hi):       2
Big (lo):       1410065408
Big (mul):      1410065408
Each one (lo):  687
Left over (hi): 2
The hi and lo registersmult leaves the 64-bit product split: hi = 0x00000002 and lo = 0x540be400, which together are 10,000,000,000. div leaves the quotient in lo (687) and the remainder in hi (2).mult $t2, $t2 (100000 × 100000)hi0x00000002lo0x540be400hi:lo together = 64 bits = 2 × 2³² + 1410065408 = 10,000,000,000mflo / mul keep only lo: 1410065408div $t3, $t4 (2750 / 4)hi2 (remainder)lo687 (quotient)Check: 4 × 687 + 2 = 2750. You take them out with mfhi and mflo.
Multiply: hi is the top half. Divide: hi is the remainder. lo, in both cases, is what you usually want.

Between the lines:

  • A critical hit: 34 × 3 = 102 fits easily in 32 bits, so lo = 102 and hi = 0.
  • A huge product: 100,000 × 100,000 = 10,000,000,000, which needs 34 bits. hi = 2 and lo = 1410065408. Check: 2 × 4,294,967,296 + 1,410,065,408 = 10,000,000,000.
  • mul $s4, $t2, $t2 is the handy form from the cheat sheet: it leaves the product straight in a register, but only the bottom 32 bits (the same 1410065408) and without warning you that something got lost.
  • The loot: 2750 gold among 4 players. lo = 687 each and hi = 2 left over. Check: 4 × 687 + 2 = 2750.

The remainder is the piece you will use most in the practical exams: “is it a multiple of 5?” is “is the remainder of dividing by 5 equal to 0?”, and “the last digit of a number” is the remainder of dividing it by 10.

I want…InstructionsWhere it ends up
To multiply and keep everythingmult $rs, $rt + mfhi / mflotop in hi, bottom in lo
To multiply small numbersmul $rd, $rs, $rt$rd (bottom 32 bits only)
The quotient of a divisiondiv $rs, $rt + mflolo
The remainder of a divisiondiv $rs, $rt + mfhihi

Mixing up mfhi and mflo after a div. One way not to forget: the remainder is what is left over, what stays up top, in hi.

hi and lo are overwritten by every mult or div. If you do two divisions in a row, take the results of the first one out with mfhi / mflo before the second.

Logic operations: bit masks

Logic instructions work bit by bit: bit 0 of the result comes from bits 0 of the two sources, bit 1 from bits 1, and so on up to 31. They let you touch single bits of a word. Our hero’s awards are eight switches in a byte: 0x0B = 0000 1011, with awards 0, 1 and 3 unlocked. The number you operate with to choose which bits to touch is called a mask.

The four operations, in one table

First, what each operation does with a single bit (a, the data bit; b, the mask bit):

abandorxornor
000001
010110
100110
111100

In words: and gives 1 only if both are 1; or, if either is; xor, if they are different; and nor is or the other way round. Read from the mask, which is how you will use it, each operation has a bit that “touches” and another that “lets through”: a 0 in an and mask clears the bit and a 1 leaves it as it was; a 1 in an or mask sets it and a 0 leaves it; a 1 in an xor mask flips it and a 0 leaves it.

# bits.s: the hero's awards are eight switches
        .data
awards: .word 0x0B                 # 0000 1011: awards 0, 1 and 3 unlocked
t1:     .asciiz "Award 3 (andi 8):   "
t2:     .asciiz "\nAward 2 (andi 4):   "
t3:     .asciiz "\nUnlock 2 (ori):     "
t4:     .asciiz "\nToggle 0 (xori):    "
t5:     .asciiz "\nAll flipped (nor):  "
t6:     .asciiz "\nOdd (andi 1):       "
        .text
        .globl main
main:   lw   $t0, awards
        andi $s1, $t0, 0x08        # mask 0000 1000: is award 3 there?
        andi $s2, $t0, 0x04        # mask 0000 0100: is award 2 there?
        ori  $s3, $t0, 0x04        # sets award 2 to 1
        xori $s4, $t0, 0x01        # toggles award 0 (1 -> 0)
        nor  $s5, $t0, $zero       # NOT: flips all 32 bits
        andi $s6, $t0, 1           # bit 0 says whether the number is odd
        li   $v0, 4
        la   $a0, t1
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t2
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t3
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t4
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 4
        la   $a0, t5
        syscall
        li   $v0, 1
        move $a0, $s5
        syscall
        li   $v0, 4
        la   $a0, t6
        syscall
        li   $v0, 1
        move $a0, $s6
        syscall
        li   $v0, 10
        syscall
Award 3 (andi 8):   8
Award 2 (andi 4):   0
Unlock 2 (ori):     15
Toggle 0 (xori):    10
All flipped (nor):  -12
Odd (andi 1):       1
Bit masksawards is 0000 1011. andi with 0000 1000 keeps only bit 3 and gives 8; ori with 0000 0100 sets bit 2 and gives 15; xori with 0000 0001 flips bit 0 and gives 10.awards = 0x0B01234567000010110000 1011andi 0x080000100000001000= 0000 1000award 3? → 8 (yes)maskori 0x040000010000001111= 0000 1111unlock 2 → 15maskxori 0x010000000100001010= 0000 1010toggle 0 → 10mask
and clears what the mask has at 0, or sets what it has at 1 and xor flips what it has at 1.
I want to…OperationMaskExample with 0000 1011
Know whether a bit is 1and / andi1 in the bit you checkandi … 0x08 → 8 (yes); andi … 0x04 → 0 (no)
Set a bit to 1or / ori1 in the bit you setori … 0x04 → 0000 1111 = 15
Flip a bitxor / xori1 in the bit you flipxori … 0x01 → 0000 1010 = 10
Clear a bitand0 in that bit, 1 in all the otherswe will see it in the practice
Flip them all (NOT)nor $rd, $rs, $zero (or the not pseudo)—1111…1111 0100 = −12
Know whether a number is oddandi $rd, $rs, 1bit 01 = odd, 0 = even

Why does the NOT come out as −12? Because nor flips all 32 bits, not just the bottom 8: the 24 zeros on top become ones and the number is negative. 1111…1111 0100 in two’s complement is −12.

The masks in bits.s, column by column

Now the program, with the awards and each mask one on top of the other (the top 24 bits are zeros and stay that way):

InstructionAwardsMaskResultWhy
andi $s1, $t0, 0x080000 10110000 10000000 1000 = 8The mask only lets bit 3 through; since it was 1, the result is not 0: the award is there
andi $s2, $t0, 0x040000 10110000 01000000 0000 = 0Bit 2 was 0, and the mask clears all the others
ori $s3, $t0, 0x040000 10110000 01000000 1111 = 15The 1 sets bit 2; the rest stay as they were
xori $s4, $t0, 0x010000 10110000 00010000 1010 = 10The 1 flips bit 0 (from 1 to 0); the zeros touch nothing
andi $s6, $t0, 10000 10110000 00010000 0001 = 1Only bit 0 is left, which is 1 in odd numbers

“Is award 3 there?” does not answer 1 but 8: the bit stays where it is, and for the yes or no it is enough to check whether the result is 0 (you will do it with beq and bne in the branches topic). Why all the fuss? Because eight yes-or-no values fit in one byte this way, and the mask lets you ask about one, set it or flip it without touching the other seven.

Check you’ve got it: how do you know whether the hero has award 1? And how do you take it away with a single instruction if you know they have it?

To ask, a mask with a single 1 in bit 1: andi $t1, $t0, 0x02. 0000 1011 AND 0000 0010 = 0000 0010 = 2, not 0, so the hero has it. To take it away, since you know it is 1, flipping it is enough: xori $t1, $t0, 0x02 gives 0000 1001 = 9, with awards 0 and 3 untouched. If you did not know it was 1, the xori could set it instead; to clear it no matter what, you use an and with a 0 in that bit, the case in the practice.

Using andi, ori or xori with a mask that needs ones in the upper half. These three pad their immediate with zeros (unlike addi, which sign-extends), so andi $t1, $t0, 0xFFFD wipes the top 16 bits. We will see it happen in the practice.

Shifts: sll, srl and sra

Shifts move all the bits of a register left or right by a fixed number of positions:

  • sll (shift left logical): to the left, bringing in zeros on the right. Shifting i positions multiplies by 2^i.
  • srl (shift right logical): to the right, bringing in zeros on the left. It divides by 2^i, but only works properly with unsigned numbers.
  • sra (shift right arithmetic): to the right, bringing in copies of the sign bit. It divides negatives by 2^i too.
# shift.s: multiplying and dividing by moving bits
        .data
dmg:    .word 40
debt:   .word -40                  # a negative amount: the gold debt
t1:     .asciiz "40 sll 3:    "
t2:     .asciiz "\n40 srl 2:    "
t3:     .asciiz "\n-40 sra 2:   "
t4:     .asciiz "\n-40 srl 2:   "
t5:     .asciiz "\nIndex 5 * 4:  "
        .text
        .globl main
main:   lw   $t0, dmg
        sll  $s1, $t0, 3           # 40 * 2^3
        srl  $s2, $t0, 2           # 40 / 2^2
        lw   $t1, debt
        sra  $s3, $t1, 2           # -40 / 4, filling with the sign
        srl  $s4, $t1, 2           # -40 "divided" filling with zeros
        li   $t2, 5                # item 5 of a table of words
        sll  $s5, $t2, 2           # offset = 5 * 4 bytes
        li   $v0, 4
        la   $a0, t1
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t2
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t3
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t4
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 4
        la   $a0, t5
        syscall
        li   $v0, 1
        move $a0, $s5
        syscall
        li   $v0, 10
        syscall
40 sll 3:    320
40 srl 2:    10
-40 sra 2:   -10
-40 srl 2:   1073741814
Index 5 * 4:  20

40 × 2³ = 320 and 40 / 2² = 10, as expected. The interesting one is −40:

sra versus srl with a negative-40 is 32 bits 1111…1101 1000. Shifted two places right: sra brings in two ones on the left and gives 0xfffffff6 (-10); srl brings in two zeros and gives 0x3ffffff6 (1073741814).-40 in $t10xffffffd8 = -4011111111111111111111111111011000sra $s3, $t1, 20xfffffff6 = -1011111111111111111111111111110110srl $s4, $t1, 20x3ffffff6 = 107374181400111111111111111111111111110110sra fills with the sign bit (1) and the number stays negative; srl shifts in zeros and you get a huge positive.
Look at the two leftmost bits (in coral): they are the ones coming in.

sra brings in two ones on the left and the number stays negative: −40 / 4 = −10. srl brings in two zeros, the sign bit becomes 0 and you get 1,073,741,814, a huge positive. The number of positions goes in the instruction (5 bits, 0 to 31); if you need it to come from a register, there are sllv, srlv and srav.

Shifting, bit by bit (and what it is for)

Moving bits is multiplying or dividing because each position is worth twice the one to its right: if every bit moves up one position, the number is worth twice as much. With the data from shift.s (only the bottom 16 bits; the top ones are zeros):

InstructionBeforeAfterValueWhy
sll $s1, $t0, 30000 0000 0010 1000 (40)0000 0001 0100 0000320The bits move up 3 positions: × 2 × 2 × 2 = × 8; three zeros come in on the right
srl $s2, $t0, 20000 0000 0010 1000 (40)0000 0000 0000 101010They move down 2 positions: ÷ 4; the two zeros on the right fall off and are lost
sll $s5, $t2, 20000 0000 0000 0101 (5)0000 0000 0001 010020Index 5 × 4 bytes per word: the offset of item 5

Together with masks they have a second use: pulling a piece out of a word. The shift brings the piece all the way to the right and an andi clears what is left over. In the sheet, the bytes from +8 to +11 (level, luck, strength and awards) make up the word 0x0bc8fe07, the third one in the load.s dump.

Check you’ve got it: with lw $t0, 8($s0) you bring in 0x0bc8fe07 in one go. How do you get the strength (200) out with a shift and a mask?

In little endian the byte at the lowest address is the least significant one: level (+8) in bits 0 to 7, luck (+9) in 8 to 15, strength (+10) in 16 to 23 and awards (+11) in 24 to 31. So srl $t1, $t0, 16 leaves 0x00000bc8 (strength at the bottom, the awards still on top) and andi $t1, $t1, 0xFF keeps the bottom 8 bits: 0x000000c8 = 200. Unsigned, just like lbu $t1, 10($s0).

The last case in the program is the one you will write most: turning an index into an offset. Item 5 of a table of words is 5 × 4 = 20 bytes from the start, and multiplying by 4 is sll …, 2, no mult needed. We will use it a lot in the arrays topic.

I want to…InstructionWatch out for
Multiply by 2, 4, 8…sll $rd, $rt, iIt can overflow without warning
Divide an unsigned number by 2, 4, 8…srl $rd, $rt, iGarbage with negatives
Divide a signed number by 2, 4, 8…sra $rd, $rt, iNegative odd numbers round down (−5 / 2 = −3)
Turn an index into a word offsetsll $rd, $ri, 2For halfwords, sll …, 1
Bring a bit field down to position 0srl and then andiWe will see it in the practice

When SPIM complains

The errors in this topic almost never stop the assembly: they show up when you run the program, in the messages panel, and the program carries on with a register that was not written. These are the ones you will meet:

QtSpim messageWhat happenedHow to fix it
Unaligned address in inst/data fetch: 0x10010006An lw/sw at an address that is not a multiple of 4 (or an lh/sh at an odd one)Check the offset and look in Data for where the value is; use the label or the instruction of the right size
Arithmetic overflowAn add, addi or sub whose result does not fit in 32 signed bitsCheck the data; if the number can never be negative, maybe you need addu or mult with hi
No message, but a strange numberlb/lbu swapped, mfhi/mflo swapped or srl on a negativeRead the register’s value in hexadecimal in the registers panel

Try it in QtSpim (or right here)

This topic makes sense when you watch the registers while the instructions go by. Open QtSpim (or the environment below, which works the same way) and check what we have seen with the hero’s sheet:

Loading the MIPS environment… If it does not appear, copy load.s into your QtSpim.

  1. Load load.s (in QtSpim, Reinitialize and Load File; here, Load) and step through it with F10. When lb $t3, 10($s0) runs, look at $t3 in the registers panel: ffffffc8. One instruction later, $t4 is 000000c8.
  2. In the Data tab, find the [10010000] line and spot each field: 00000abe the gold, 00550078 the two HP values and 0bc8fe07 the four bytes.
  3. Change lh $t1, 6($s0) to lw $t1, 6($s0) and run it again: the messages panel will say Unaligned address.
  4. Change the luck’s .byte -2 to .byte 254 and run it: lb gives −2 again. For memory, −2 and 254 are the same byte, fe.
  5. Add li $t5, 2750 and li $t6, 4 at the end, then div $t5, $t6, and look at the HI and LO registers in the panel: 2 and 687 (in hexadecimal, 2 and 2af).

Summary

ConceptThe essentials
Load and storeYou only operate in registers: load, operate and store. Address = $base + offset
Sizeslw/sw 4 bytes, lh/lhu/sh 2, lb/lbu/sb 1
Signlb/lh copy the sign bit upwards; lbu/lhu fill with zeros
Alignmentlw/sw at multiples of 4, lh/sh at even addresses; otherwise Unaligned address
Constants16-bit immediates; li with big numbers = lui + ori
Add and subtractadd, addi, sub; there is no subi (addi with a negative); $zero is 0
Overflowadd/addi/sub raise Arithmetic overflow; addu/addiu wrap around silently
Multiply and dividemult → hi:lo (64 bits); div → quotient in lo and remainder in hi; taken out with mflo/mfhi
Logicand checks and clears, or sets, xor flips, nor with $zero is NOT; andi/ori/xori pad with zeros
Shiftssll × 2^i, srl ÷ 2^i unsigned, sra ÷ 2^i signed

Three ideas to take away

  1. Memory only stores bytes: the instruction you read with decides how much you read and whether it is signed. Choose lw, lh or lb by the size of the value, and the u by whether it can be negative.
  2. mult and div do not write to your registers: they leave their result in hi and lo, and you take it out with mfhi and mflo. In a division, the remainder is up top, in hi.
  3. With a mask and the right operation you can touch any bits you like: and to check or clear, or to set and xor to flip. With srl + andi you can pull any field out of a word.

In the load, arithmetic and logic practice we take the hero’s sheet into three complete programs: levelling up according to the experience, sharing out a loot that does not fit in 32 bits and pulling three values out of a single word.

Next step: practiceLoad, arithmetic and logic in MIPS — QtSpim practice: levelling up, a 64-bit loot and three values in one word (and the award that wiped my morale)

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