Load, 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)

In the lab I got a bit exercise: a character’s status word keeps the awards in the bottom byte, and you had to clear one without touching anything else. “Easy: an and with a mask that has a 0 in that bit and ones everywhere else.” I wrote andi $s5, $t0, 0xFFFD, ran it and the console showed this:

Clear 1 (andi):  1289

The status word was 0xFD00050B and I expected 0xFD000509: the same number with one bit less. What came out was 0x00000509. The award had been cleared, yes, but so had the character’s morale, the top eight bits. The reason is in a line of the theory I had skimmed: andi pads its 16-bit immediate with zeros on top. My “mask with ones everywhere else” was really 0x0000FFFD.

In this practice we use what we saw in the theory of load, arithmetic and logic in MIPS in three complete programs with the hero’s sheet, all intermediate level and with the results checked in QtSpim’s Data tab and registers panel. The first one levels up the character according to their experience and stores the sheet back field by field; the second shares out a loot so big it does not fit in 32 bits; and the third pulls out three values packed into a single word, which is how game settings or device registers are really stored. If you don’t have QtSpim yet, start with installing QtSpim and how to use QtSpim.

Before you start

You should be clear about:

  • You only operate with registers: load, operate and store, with offset($base) addresses.
  • Which load instruction goes with each size (lw, lh, lb) and when to add the u (lbu, lhu).
  • That div leaves the quotient in lo and the remainder in hi, and that mult splits its 64-bit product between the two.
  • What and, or, xor, sll, srl and sra do bit by bit.

If any of these sounds shaky, go over the theory before carrying on.

The three programs are best watched step by step. In QtSpim, load the file, press F10 to move one instruction at a time and keep the registers panel (Int Regs) and the Data tab in view. In the environment below, the same: Step and the Data tab.

Program 1: levelling up

The hero’s sheet now holds five fields: gold, experience, max HP, current HP and level. After a quest, the game recalculates the level from the accumulated experience (one level every 1000 points), says how much is left for the next one, raises the max HP according to the level (100 + 15 per level), fully heals the hero and charges 50 gold per level for the trainer. What makes it tricky: each field has a different size, and you have to read it and store it with the instruction of that size.

The idea

Everything is done from a single base address: la $s0, sheet and each field as offset($s0). First the maths, in registers; at the end, all the stores together. The maths is:

  1. Level and what is left: a single div gives both the level (quotient, in lo) and the points you already have towards the next level (remainder, in hi).
  2. Max HP = 100 + level × 15, without multiplying: 15 = 16 − 1, so level × 15 = level × 16 − level, and × 16 is sll …, 4.
  3. Gold − level × 50, here with mul, because 50 is not a power of 2.

Before programming, draw the sheet on paper with each field’s offset: +0 gold (word), +4 experience (word), +8 max HP (half), +10 current HP (half), +12 level (byte). With that drawing, every load and store writes itself.

The code

# levelup.s: experience decides the level, the HP and what the trainer charges
        .data
sheet:  .word 2750                 # +0  gold
        .word 8384                 # +4  accumulated experience
        .half 120                  # +8  max HP
        .half 85                   # +10 current HP
        .byte 7                    # +12 level
t_lvl:  .asciiz "Level: "
t_left: .asciiz "\nLeft for the next one: "
t_hp:   .asciiz "\nMax HP: "
t_gold: .asciiz "\nGold after paying the trainer: "
        .text
        .globl main
main:   la   $s0, sheet            # $s0 = base: everything is read as offset($s0)
        # 1) level = experience / 1000 and progress to the next = experience % 1000
        lw   $t0, 4($s0)           # experience = 8384
        li   $t1, 1000
        div  $t0, $t1              # lo = 8, hi = 384
        mflo $s1                   # new level
        mfhi $t2                   # points within the level
        sub  $s2, $t1, $t2         # falta = 1000 - 384
        # 2) max HP = 100 + level * 15, with 15 = 16 - 1
        sll  $t3, $s1, 4           # level * 16
        sub  $t3, $t3, $s1         # level * 16 - level = level * 15
        addi $s3, $t3, 100         # + 100
        # 3) the trainer charges 50 gold per level
        li   $t4, 50
        mul  $t5, $s1, $t4         # 8 * 50 = 400
        lw   $t6, 0($s0)           # gold = 2750
        sub  $s4, $t6, $t5         # gold - 400
        # 4) store into the sheet with the size of each field
        sw   $s4, 0($s0)           # gold: 4 bytes
        sh   $s3, 8($s0)           # max HP: 2 bytes
        sh   $s3, 10($s0)          # levelling up heals you completely
        sb   $s1, 12($s0)          # level: 1 byte
        # 5) the summary on the console
        li   $v0, 4
        la   $a0, t_lvl
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t_left
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t_hp
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t_gold
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 10
        syscall

The heart of the program is the six lines of the level and the max HP:

lw   $t0, 4($s0)           # experience = 8384
li   $t1, 1000
div  $t0, $t1              # lo = 8, hi = 384
mflo $s1                   # new level
mfhi $t2                   # points within the level
sub  $s2, $t1, $t2         # falta = 1000 - 384
# 2) max HP = 100 + level * 15, with 15 = 16 - 1
sll  $t3, $s1, 4           # level * 16
sub  $t3, $t3, $s1         # level * 16 - level = level * 15
addi $s3, $t3, 100         # + 100
InstructionRegister that changesValue afterwards
lw $t0, 4($s0)$t08384
li $t1, 1000$t11000
div $t0, $t1lo, hilo = 8, hi = 384
mflo $s1$s18 (new level)
mfhi $t2$t2384
sub $s2, $t1, $t2$s2616
sll $t3, $s1, 4$t3128 (8 × 16)
sub $t3, $t3, $s1$t3120 (8 × 15)
addi $s3, $t3, 100$s3220

Output

Level: 8
Left for the next one: 616
Max HP: 220
Gold after paying the trainer: 2350

Checking it by hand: 8384 / 1000 = 8 remainder 384, and 1000 − 384 = 616. The max HP: 100 + 8 × 15 = 100 + 120 = 220. The gold: 2750 − 8 × 50 = 2750 − 400 = 2350. It all adds up.

But the console is only half the result: the program has also changed the sheet in memory. This is the Data tab before (with before.s, which has the same data) and after levelup.s:

[10010000]    00000abe  000020c0  00550078  00000007    . . . . .   . . x . U . . . . .
[10010000]    0000092e  000020c0  00dc00dc  76654c08    . . . . .   . . . . . . . L e v
The sheet before and after levelling upThirteen bytes from 0x10010000. Before: gold be 0a, experience c0 20, max HP 78 00, HP 55 00 and level 07. After: gold 2e 09, the experience unchanged, both HP dc 00 and level 08.Before (before.s)+0+1+2+30x10010000be0a00000x10010004c02000000x10010008780055000x1001000c07After levelup.s+0+1+2+30x100100002e0900000x10010004c02000000x10010008dc00dc000x1001000c08gold: 0abe (2750) → 092e (2350)exp: untouched (8384)max and current HP: 0078/0055 → 00dc/00dc (220)level: 07 → 08 (sb, one byte)
sw, sh and sb only write their 4, 2 or 1 bytes: the experience is not touched.

0x0000092e is 2350; the two halfwords at 0x10010008 are 0x00dc = 220; and the byte at 0x1001000c went from 07 to 08. The bytes after the level, in the same word, are the beginning of the "Level: " string: sb has not touched them. Had we stored the level with sw, they would have become zeros.

What has changed in the Data tab, word by word. QtSpim shows each word in little endian: the byte at the lowest address is the one on the right.

AddressBeforeAfterWhy
0x1001000000000abe0000092eThe gold: 0xabe = 2750 becomes 0x92e = 2350, with sw (all 4 bytes)
0x10010004000020c0000020c0The experience (0x20c0 = 8384): no store points at +4
0x100100080055007800dc00dcTwo halfwords: the one at +8 is the right half (0078 = 120) and the one at +10, the left half (0055 = 85). The two sh leave both at 00dc = 220
0x1001000c0000000776654c08Only the right-hand byte belongs to the level (07 → 08); the other three are not its own

The row that fools you most is the third one: read from left to right, it looks as if the current HP came first, and it is the other way round. The halfword at the lowest address, +8, is the one on the right.

Questions you might ask

Why a single div and not two? Because a MIPS division always gives both things at once: the quotient in lo and the remainder in hi. Another div for the remainder would repeat the same work.

Why sll and sub instead of mul for the × 15? Both give 120. With sll and sub you see how to multiply by a constant using shifts, which is what compilers do with constants close to a power of 2. For the × 50 we do use mul: 50 = 32 + 16 + 2 would take five instructions.

Why all the stores at the end? So the maths is done with the original data. If you store the new level before working out something that needs the old one, you lose it.

Why do I store the max HP twice? Because levelling up fully heals: the current HP (+10) becomes equal to the max (+8). They are two different halfwords, so two sh with the same register.

What if the experience were 7999? div gives 7 remainder 999: level 7 and 1 point left for level 8. Integer division always rounds down, which is what the game wants.

Writing sw $s1, 12($s0) for the level. 12 is a multiple of 4, so it does not fail, but sw writes four bytes: the level and the first three characters of the string that follows. The program carries on, and the “Level: ” text disappears from the console.

What if you stored the max HP with a single sw $s3, 8($s0)?

The healing would backfire. 8 is a multiple of 4, so there is no alignment error, but $s3 is 220 = 0x000000dc and sw writes all four of its bytes: the word at 0x10010008 becomes 000000dc. The halfword at +8 (the right half) is 0x00dc = 220, so the max HP is right; the one at +10 (the left half) becomes 0x0000. The current HP drops to 0: the hero levels up and dies in the same instant.

And the console does not show it. It prints $s3, which is still 220, and the four lines come out exactly as before. You only see it in the Data tab, or by reading the current HP afterwards with lhu …, 10($s0), which gives 0.

Try it yourself

  • Change the experience to 12500 and predict, before running it, the level (12), what is left (500), the max HP (280) and the gold (2150). Check it on the console and in Data.
  • Make the max HP 100 + level × 12 using only shifts and additions (12 = 8 + 4).

Program 2: the guild’s loot

The final boss drops 98765 gold each game and the guild has played 50000 games. How much gold has come out in total? And each time a loot drops, how much does each of the seven players get and how much is left for the guild? What makes it tricky: the total does not fit in 32 bits.

The idea

For the total, mult and the two registers: the top 32 bits in hi and the bottom ones in lo. Next to it we put a mul, which does the same multiplication but keeps only lo, to see what gets lost. For the sharing, a div by 7: the quotient is each player’s share and the remainder, what is left over.

Before programming, estimate: 98765 × 50000 is about 5,000 million, and the largest unsigned 32-bit integer is 4,294,967,295. It does not fit, so hi cannot be 0.

The code

# loot.s: the guild's treasure, too big for 32 bits
        .data
loot:    .word 98765               # gold the boss drops in each game
games:   .word 50000               # games played by the guild
party:   .word 7                   # players in the party
t_hi:    .asciiz "Treasure (hi): "
t_lo:    .asciiz "\nTreasure (lo): "
t_mul:   .asciiz "\nWith mul:       "
t_each:  .asciiz "\nEach player: "
t_guild: .asciiz "\nFor the guild: "
        .text
        .globl main
main:   lw   $t0, loot
        lw   $t1, games
        mult $t0, $t1              # hi:lo = 98765 * 50000 = 4938250000
        mfhi $s0                   # the top 32 bits
        mflo $s1                   # the bottom 32 bits
        mul  $s2, $t0, $t1         # mul: only the bottom ones
        lw   $t2, party
        div  $t0, $t2              # sharing out ONE game: lo = quotient, hi = remainder
        mflo $s3                   # gold for each player
        mfhi $s4                   # what cannot be shared goes to the guild
        li   $v0, 4
        la   $a0, t_hi
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 4
        la   $a0, t_lo
        syscall
        li   $v0, 1                # fits in 31 bits: reads fine as signed
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t_mul
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t_each
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t_guild
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 10
        syscall

Output

Treasure (hi): 1
Treasure (lo): 643282704
With mul:       643282704
Each player: 14109
For the guild: 2

Checking it by hand: the exact total is 98765 × 50000 = 4,938,250,000. With hi = 1, that is 1 × 2³² + lo = 4,294,967,296 + 643,282,704 = 4,938,250,000. It adds up. mul gives 643,282,704, without warning that a whole 2³² is missing. And the sharing: 7 × 14109 = 98763, plus a remainder of 2, 98765.

The same number, split across two registers:

StepValueWhy
Exact product4,938,250,00098765 × 50000, done in 64 bits by mult
In hexadecimal0x1 2657B710It has 9 hexadecimal digits and a register holds 8
hi0x00000001 = 1The digit left over on the left: the top 32 bits
lo0x2657B710 = 643,282,704The 8 digits on the right: the bottom 32 bits
mul643,282,704It keeps lo and throws hi away without warning

In hexadecimal, splitting into hi and lo is no calculation at all: it is cutting off the 8 digits on the right. The 4,294,967,296 in the check is just what a 1 is worth in the ninth digit.

In QtSpim’s registers panel, at the end, HI is 2 and LO is 371d (14109 in hexadecimal): the div has overwritten the mult values. It does not matter because we had already taken them out with mfhi and mflo.

Questions you might ask

What do I do with a number that takes two registers? In 32-bit MIPS, treat it as two halves. Printing it whole would need a 64-bit division the instruction set does not have. In the exam the usual thing is to be asked to detect that it does not fit: if hi is not 0 (for positive numbers), the product has gone beyond 32 bits.

Why does lo print fine with syscall 1, which is for signed integers? Because 643,282,704 is less than 2³¹ and its bit 31 is 0. If lo started with a 1, syscall 1 would show it as negative.

Does the div share out the total or one loot? One loot, a single game’s (98765). Sharing out the 64-bit total would mean dividing a number that does not fit in a register.

What if the guild has 0 players? Dividing by 0 in MIPS does not make the div instruction fail: hi and lo are left with a meaningless value. That is why the three-operand pseudoinstruction div $rd, $rs, $rt adds a check beforehand that raises an exception if the divisor is 0.

Doing the sharing div before taking hi and lo out of the mult. Both use the same registers, and the mult is lost without any warning.

What if the guild played 70000 games?

The total would be 98765 × 70000 = 6,913,550,000. It does not fit either and hi comes out as 1 again, but now lo = 0x9C1466B0, which starts with 9 = 1001: its bit 31 is 1. Syscall 1 reads it as signed and the console says:

Treasure (hi): 1
Treasure (lo): -1676384592
With mul:       -1676384592
Each player: 14109
For the guild: 2

A negative treasure from a positive loot. This is what the syscall 1 question warned about: −1,676,384,592 = 2,618,582,704 − 4,294,967,296, the same bit pattern read as signed. With 70000 games, at least the flipped sign gives the problem away; with 50000 the mul gave a positive, believable number, and there was no clue at all. The sharing does not change, because it depends on one loot, not on the total.

Try it yourself

  • Change the number of games to 40000 and predict whether hi comes out as 0 (98765 × 40000 = 3,950,600,000, which does fit in 32 unsigned bits). See what syscall 1 prints with that lo.
  • Share the loot among 5 players and check that the remainder is 0: 98765 is a multiple of 5.

Program 3: three values in a single word

The hero’s status word, 0xFD00050B, holds three values: bits 7-0 are the awards (eight switches), bits 11-8 the rank (0 to 15) and bits 31-24 the morale, a signed number from −128 to 127. You have to pull out all three, clear award 1 without touching the rest and, while you are at it, capitalise the initial of the hero’s name, stored in lower case.

The idea

To pull out a bit field, two steps: bring it down to position 0 with srl and trim it with an andi that has as many ones as the field has bits. If the field is the topmost one there is no need to trim, but you do need to choose the shift carefully: sra if it is signed, srl if not. To clear a bit, and with a 32-bit mask that has that bit at 0 and all the others at 1, loaded with li. And for the capital, an ASCII trick: a lower-case letter and its capital differ only in bit 5 (0x20).

Three fields in one word0xFD00050B in binary: bits 31-24 are the morale (FD, -3 signed), 23-12 are unused, 11-8 the rank (5) and 7-0 the awards (0B, 11). Below, how each field is extracted and why andi with 0xFFFD also wipes the top half.status = 0xFD00050B11111101000000000000010100001011morale (signed)unusedrankawardsandi $s0, $t0, 0xFF→ 11srl 8 + andi 0x0F→ 5sra $s2, $t0, 24→ -3srl $s3, $t0, 24→ 253The andi trap:andi …, 0xFFFD uses 0x0000FFFD→ 0x00000509 = 1289 (morale wiped)li $t2, 0xFFFFFFFD + and→ 0xFD000509 (only bit 1 goes)
To extract a field: srl down to position 0 and andi with as many ones as it has bits.

Before programming, write 0xFD00050B in binary in groups of 4 (1111 1101 0000 0000 0000 0101 0000 1011) and mark where each field starts and ends. The drawing above is exactly that.

The code

# status.s: three values packed into one word, and a name that wants a capital
        .data
status: .word 0xFD00050B           # morale | 00 | rank | awards
name:   .asciiz "kaelen\n"
t_awd:  .asciiz "Awards:        "
t_rank: .asciiz "\nRank:          "
t_mor:  .asciiz "\nMorale (sra):  "
t_mou:  .asciiz "\nMorale (srl):  "
t_clr:  .asciiz "\nClear 1 (right): "
t_bad:  .asciiz "\nClear 1 (andi):  "
t_name: .asciiz "\nName: "
        .text
        .globl main
main:   lw   $t0, status
        # 1) awards: the bottom 8 bits
        andi $s0, $t0, 0xFF        # 0x0B = 11
        # 2) rank: bits 8 to 11
        srl  $t1, $t0, 8           # bring the field down to position 0
        andi $s1, $t1, 0x0F        # and keep 4 bits
        # 3) morale: the top 8 bits, signed
        sra  $s2, $t0, 24          # fills with the sign: -3
        srl  $s3, $t0, 24          # fills with zeros: 253
        # 4) clear award 1 without touching the rest
        li   $t2, 0xFFFFFFFD       # all ones except bit 1
        and  $s4, $t0, $t2         # right: 0xFD000509
        andi $s5, $t0, 0xFFFD      # wrong: andi pads the immediate with zeros
        # 5) the name's initial in capitals: 'k' (0x6B) -> 'K' (0x4B)
        la   $t3, name
        lbu  $t4, 0($t3)           # first character
        andi $t4, $t4, 0xDF        # clear bit 5 (0x20)
        sb   $t4, 0($t3)           # and put it back into the string
        li   $v0, 4
        la   $a0, t_awd
        syscall
        li   $v0, 1
        move $a0, $s0
        syscall
        li   $v0, 4
        la   $a0, t_rank
        syscall
        li   $v0, 1
        move $a0, $s1
        syscall
        li   $v0, 4
        la   $a0, t_mor
        syscall
        li   $v0, 1
        move $a0, $s2
        syscall
        li   $v0, 4
        la   $a0, t_mou
        syscall
        li   $v0, 1
        move $a0, $s3
        syscall
        li   $v0, 4
        la   $a0, t_clr
        syscall
        li   $v0, 1
        move $a0, $s4
        syscall
        li   $v0, 4
        la   $a0, t_bad
        syscall
        li   $v0, 1
        move $a0, $s5
        syscall
        li   $v0, 4
        la   $a0, t_name
        syscall
        li   $v0, 4
        la   $a0, name
        syscall
        li   $v0, 10
        syscall

The three extractions, one by one:

# 1) awards: the bottom 8 bits
andi $s0, $t0, 0xFF        # 0x0B = 11
# 2) rank: bits 8 to 11
srl  $t1, $t0, 8           # bring the field down to position 0
andi $s1, $t1, 0x0F        # and keep 4 bits
# 3) morale: the top 8 bits, signed
sra  $s2, $t0, 24          # fills with the sign: -3
srl  $s3, $t0, 24          # fills with zeros: 253

What each instruction leaves, in hexadecimal, starting with the word just loaded:

InstructionResultWhy
lw $t0, statusfd00050bThe whole word: morale, 00, rank and awards
andi $s0, $t0, 0xFF0000000bThe mask, padded with zeros, is 0x000000FF: only the bottom 8 bits get through
srl $t1, $t0, 800fd00058 bits are two hexadecimal digits: the 0b drops off on the right and two zeros come in on the left
andi $s1, $t1, 0x0F00000005The rank is now the last digit; 0x0F throws away everything else, including the morale, which has ended up in the middle
sra $s2, $t0, 24fffffffdSix digits drop off; ones come in because bit 31 is 1 (F = 1111)
srl $s3, $t0, 24000000fdThe same six digits drop off, but zeros come in

Since all three shifts are multiples of 4 bits, everything is done by moving whole hexadecimal digits, without going through binary.

Output

Awards:        11
Rank:          5
Morale (sra):  -3
Morale (srl):  253
Clear 1 (right): -50330359
Clear 1 (andi):  1289
Name:   Kaelen

The two “Clear 1” lines come out in decimal, which does not say much here. QtSpim’s registers panel shows them in hexadecimal:

RegisterHexadecimalWhat it is
$s00000000bThe awards: 0000 1011
$s100000005The rank
$s2fffffffdThe morale with sra: −3
$s3000000fdThe morale with srl: 253
$s4fd000509Right: only bit 1 has gone (b → 9)
$s500000509Wrong: with andi the morale has gone too

Checking it by hand: 0x0B = 11; 0x5 = 5; 0xFD = 253 unsigned, which signed is 253 − 256 = −3. And the name: 'k' is 0x6B = 0110 1011; clearing bit 5 leaves 0100 1011 = 0x4B, which is 'K'.

Why does andi with 0xDF work here, when it is what wiped my morale? Because lbu leaves the character with 24 zeros on top: $t4 = 0x0000006B. andi setting the top half to 0 clears nothing that was not already 0, and 0xDF = 1101 1111 has ones in the character’s 8 bits except bit 5. Besides, sb only puts the bottom byte back into the string. In the status word, the top half held the morale.

Questions you might ask

Why srl + andi for the rank and not a single andi 0xF00? andi $t1, $t0, 0xF00 leaves the rank where it is and would give 0x500 = 1280, not 5. To get the rank as a number you have to bring it down to position 0, and that is srl.

Why doesn’t the morale need a mask? Because after shifting 24 positions to the right there is nothing left above it: the bits coming in are copies of the sign (sra) or zeros (srl). That is the difference between −3 and 253.

Why li + and to clear the bit? Because the mask needs ones in all 32 bits but one, and that does not fit in a 16-bit immediate. li $t2, 0xFFFFFFFD builds it whole (the assembler turns it into lui + ori). Using andi with the mask is only fine if you don’t care about the upper half.

Why lbu for the character and not lb? ASCII characters go from 0 to 127 and both would give the same, but a character is never negative and with lbu you are safe if one day there is a byte above 127 (an accented letter in Latin-1, for example).

What if the name already starts with a capital? Nothing: clearing a bit that is already 0 leaves it as it is. To go to lower case, ori …, 0x20; to switch between the two, xori …, 0x20.

andi $rt, $rs, 0xFFFD to clear a bit of a whole word. andi, ori and xori pad their immediate with zeros: andi wipes the top 16 bits, and ori or xori can never touch them. That is what wiped my morale.

Try it yourself

  • Change the morale to +5 (the word becomes 0x0500050B) and check that sra and srl give the same.
  • Add the code to unlock award 2 (ori with 0x04) and to toggle award 7 (xori with 0x80), and look at the register in hexadecimal.

Common mistakes in this practice

  • Storing with the wrong size. sw where sb belonged overwrites the neighbouring bytes; sb where sw belonged only stores the bottom byte and the rest of the value stays as it was.
  • Reading hi and lo too late. Every mult or div overwrites both: take out what you need with mfhi / mflo before the next one.
  • Mixing up quotient and remainder. The remainder (what is left over) is in hi; the quotient, in lo.
  • Trimming a field without bringing it down. andi with the field’s mask leaves the number shifted (1280 instead of 5): srl first.
  • srl on a signed field. The −3 morale comes out as 253. If the field can be negative, sra.
  • 16-bit masks for a 32-bit word. andi, ori and xori do not touch (or they wipe) the upper half. With ones on top, li + and/or/xor.

Try it in QtSpim (or right here)

The first program is the one you enjoy most step by step, because you see the registers and memory change at the same time. Load it in QtSpim or right here:

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

  1. Step with F10 until you are past the div and look at the HI and LO registers: 180 and 8 in hexadecimal (384 and 8).
  2. Carry on to addi $s3, $t3, 100 and check the two steps of the × 15 in $t3: 80 (128) and 78 (120).
  3. Before the four stores, open the Data tab: the sheet is still as it started. Step through them one by one and see which bytes each one changes.
  4. Change sb $s1, 12($s0) to sw $s1, 12($s0), run it again and read the console: the “Level: ” text is missing.
  5. In the Text tab, find li $t1, 1000: the assembler has turned it into ori $9, $0, 1000, because 1000 fits in 16 bits.

Summary

  • A structure in memory is handled with a base address in a register and each field at its offset: lw 4($s0), sh 8($s0), sb 12($s0).
  • Each field is read and stored with the instruction of its size. The surroundings are left alone only if the size is right.
  • A single div gives the quotient and the remainder; a mult gives a 64-bit product in hi:lo, and if hi is not 0 the number does not fit in 32 bits.
  • Multiplying by a constant close to a power of 2 can be done with sll and an addition or subtraction.
  • To pull out a bit field: srl to bring it down and andi to trim it; if it is the top one and signed, sra.
  • andi, ori and xori use a 16-bit immediate padded with zeros: for a mask with ones on top, li + the register version.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Can you say, without looking, which register holds the remainder of a div?
  • Have you seen in the Data tab which bytes each sw, sh and sb in levelup.s changes?
  • Do you know why the morale is −3 with sra and 253 with srl?
  • Can you write the mask to clear bit 4 of a word without touching the others?
  • Have you tried the “Try it yourself” ideas without looking at the theory?

If you answered yes to almost everything, you are ready for the load, arithmetic and logic exercises in MIPS, where I no longer give you the code. See you there!

Next step: exercisesLoad, arithmetic and logic in MIPS — exercises with a potion, the play time and a save code (and the clock that showed 123 minutes)

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