MIPS program structure and data — theory with a video game inventory, directives, little endian and la versus lw (and the points that came out as 268500996)

First lab session of IC1 (Computer Fundamentals I). The task looked like a joke: store a video game character’s data and show their points on screen. I defined the lives, the level, the coins and the points, looked up the “print an integer” service on my cheat sheet and wrote this:

# hook.s: I wanted to print my game points...
        .data
lives:   .byte 3
level:   .byte 12
coins:   .half 1250
points:  .word 48000
        .text
        .globl main
main:   li   $v0, 1                 # service 1: print an integer
        la   $a0, points            # ...and I pass it the points (are you sure?)
        syscall
        li   $v0, 10
        syscall

I loaded it into QtSpim, pressed F5 and the console showed:

268500996

“268 million points? I wish.” No error, no warning: just a huge number and me staring at it. The bug was a single letter. la does not load the datum: it loads the address where the datum is stored. 268500996 is, in decimal, the address 0x10010004, the spot in memory where my 48000 points lived. To read what is inside that address I needed lw.

Today we look at how a MIPS program is built inside: what each line is (instructions, pseudo-instructions, directives, labels and comments), where SPIM puts your instructions and your data, how data are written with .byte, .half, .word, .ascii, .asciiz and .space, why padding bytes sometimes appear, why the bytes of a word are stored “backwards” and when to use la and when lw. Our running example is a video game inventory: lives, level, coins, points, items and a weapon. If you don’t have QtSpim yet, start with install QtSpim and how to use QtSpim; when you finish, the MIPS program structure and data practice is waiting with three complete programs.

Before you start. You need three things. First, QtSpim installed and knowing where its windows are, as in install QtSpim and how to use QtSpim: the text segment, the Data tab and the console. Second, reading hexadecimal: that 0x24 is 36, that each digit is 4 bits and that two digits are one byte. Third, the idea that memory is a very long row of one-byte boxes, each with its own number (its address). That’s all. The topic goes in this order: first, what kinds of line a program has, with a minimal program read line by line; then, the two areas of memory (instructions and data) and the registers you’ll see in QtSpim; next, the directives that write the data and how they are placed, box by box, with the video game inventory; and finally, the order of the bytes, strings, the difference between la and lw and the syscalls for printing. If at any point you get lost, go back to the same question: is this an address (where it is) or a value (what’s inside)?

The five kinds of line in a MIPS program

This is the smallest MIPS program that does something visible: it prints a message and ends.

# anatomy.s: the skeleton of any MIPS program
        .data                         # the data go from here on
greeting: .asciiz "Game loaded\n" # a string ending in a 0 byte
        .text                         # the instructions go from here on
        .globl main                   # main has to be visible from the start-up code
main:   li   $v0, 4                   # service 4: print a string
        la   $a0, greeting            # $a0 = address of the string
        syscall                       # QtSpim prints on the console
        li   $v0, 10                  # service 10: end the program
        syscall
Game loaded

It’s only ten lines, but everything is here. Each line of an assembly program can have a label at the start, an instruction, a pseudo-instruction or a directive in the middle and a comment at the end:

KindHow to spot itWhat it doesIn anatomy.s
DirectiveStarts with a dotGives orders to the assembler: where the data start, how much each one takes… It is not executed.data, .asciiz, .text, .globl
LabelA name followed by a colonNames a memory address (that of a datum or of an instruction)greeting:, main:
InstructionAn operation the processor can doBecomes one 32-bit word of machine codesyscall
Pseudo-instructionAn operation the processor does not haveThe assembler replaces it with one or more real instructionsli, la
CommentFrom # to the end of the lineNothing: it’s for you (and for whoever marks your lab work)# service 4: …

Between the lines:

  • .data and .text split the program into two areas: whatever follows .data is data and whatever follows .text is instructions. You can switch between them as often as you like, but one of each is the norm.
  • .globl main makes the label main visible from outside your file. Who looks for it? The start-up code that QtSpim loads before your program and that ends with a jal main. If you forget it, SPIM makes it global on its own, but always write it: it’s the custom in the lab.
  • li $v0, 4 + la $a0, greeting + syscall is the recipe for printing a string: the service number in $v0, the datum in $a0 and the call. The last pair, li $v0, 10 + syscall, ends the program.

In SPIM, commas between operands are optional: lw $t0 lives works just like lw $t0, lives. That’s why you’ll see lines without commas in QtSpim’s comment column, which copies your line as it is. Still, write them: they read better and it’s what the marker expects.

Naming a label b, or j, or la. Those are instruction names and SPIM replies with a syntax error on that line. Use names that don’t clash: x1, data1, loop…

anatomy.s line by line

The table of the five kinds says what each line is; what’s missing is why each one is there. Read anatomy.s the way SPIM reads it, from top to bottom (line 1 is the title comment):

LineWhat it doesWhy
2: .dataAnnounces that what follows is dataThe assembler has to know which area of memory to put the next lines in: here, from 0x10010000 on
3: greeting: .asciiz "Game loaded\n"Writes 13 bytes (11 characters, the \n and the 0 byte) and names the address of the first one greeting, 0x10010000It’s what we’re going to print; the label saves us from having to remember the number 0x10010000
4: .textAnnounces that what follows is instructionsThey go in another area, from 0x00400024 on (after the start-up code)
5: .globl mainMakes main visible outside the fileThe start-up code ends with jal main and has to find it
6: main: li $v0, 4main now stands for 0x00400024; $v0 = 4The syscall looks at $v0 to know which service you want: 4 is print a string
7: la $a0, greeting$a0 = 0x10010000Service 4 doesn’t want the letters, it wants where they start
8: syscallPrints from 0x10010000 up to the first 0 byteThat’s why .asciiz was needed: the 0 byte is the signal to stop
9: li $v0, 10$v0 = 10Service 10 is end the program
10: syscallEnds the programWithout this pair, the processor would keep reading the next address

Notice that only lines 6 to 10 end up in the text segment as instructions. Lines 2 to 5 are directives and the label on line 6 is a name: none of them takes up room among the instructions.

Check you’ve got it: what happens if on line 7 you write lw $a0, greeting instead of la?

The program loads without complaint, but the syscall fails. lw doesn’t bring the address of greeting, but the 4 bytes inside it: the letters G, a, m and e (0x47, 0x61, 0x6d and 0x65). Read as a word in little endian (you’ll see it further down), they are 0x656d6147. Syscall 4 takes that number as if it were an address and goes looking for letters there, but there is no memory of your program at that address: SPIM stops with an address-out-of-memory error (in the console spim, Memory address out of bounds). It’s the bug from the beginning the other way round: there, I passed an address where a value was needed; here, a value where an address was needed.

Where everything lives: the memory map

Before the map with its addresses, the idea in words. A program has two kinds of things: what the processor does (the instructions) and what it does it with (the data). A segment is an area of memory reserved for one of the two. In the video game, the text segment would be the rules of the game and the data segment, the character’s sheet: the rules don’t change while you play, the sheet does.

SegmentWhat it holdsWho fills itIn anatomy.sWhy they are kept apart
Text (.text)Instructions, each one a 4-byte wordThe assembler, when it translates your linesli, la, syscall…The processor fetches the next instruction from here, 4 bytes at a time
Data (.data)Numbers and strings the program reads or changesThe data directivesgreetingThat way a datum is never mistaken for an instruction

The .data and .text directives take up no memory: they are like switching folders for the assembler. Everything you write after .data goes into the data folder, in order, and everything you write after .text, into the instructions folder.

When you press Reinitialize and Load File, SPIM always lays your program out in memory the same way. This is the map, from low addresses (bottom) to high ones (top):

Memory map of a MIPS programBottom to top: reserved, text segment from 0x00400000 (start-up code, then main at 0x00400024), static data from 0x10000000 with .data at 0x10010000, dynamic data, and the stack growing down from 0x7ffffffc.Stack ↓0x7ffffffcHeap (dynamic data) ↑Static data: your .data0x10010000Text: your instructions (.text)0x00400000Reserved0x000000000x7fffffff0x00400000start-up code(9 instructions, jal main)0x00400024main:0x10010000first .data labelMemory of aprogram in QtSpim
Your program lives in two areas: instructions in the text segment and data at 0x10010000.

Look at the two areas that are yours:

  • The text segment starts at 0x00400000, but your main isn’t there. The first nine instructions, from 0x00400000 to 0x00400020, are the start-up code that QtSpim loads with Load Exception Handler: it prepares the arguments, jumps to your program with jal main and, if your program ever returned, ends it with syscall 10. Your first instruction lands at 0x00400024.
  • The data start at 0x10010000. SPIM’s data segment begins at 0x10000000, but the .data directive with no address puts your data 64 KiB higher, at 0x10010000. That’s why QtSpim’s Data tab first shows a line [10000000]..[1000ffff] 00000000: everything below, all zeros.

You can check it in the text segment of anatomy.s, as QtSpim shows it (I’m not repeating the nine start-up lines):

[00400024] 34020004  ori $2, $0, 4                  ; 6: li $v0, 4 # service 4: print a string
[00400028] 3c041001  lui $4, 4097 [greeting]        ; 7: la $a0, greeting # $a0 = address of the string
[0040002c] 0000000c  syscall                        ; 8: syscall # QtSpim prints on the console
[00400030] 3402000a  ori $2, $0, 10                 ; 9: li $v0, 10 # service 10: end the program
[00400034] 0000000c  syscall                        ; 10: syscall

Each line is one instruction: its address, its machine code in hexadecimal, the instruction once translated and, after the semicolon, the line number and the text from your file. The addresses go up in steps of 4 because each instruction takes 4 bytes. And look at the second line: your la $a0, greeting has become lui $4, 4097. We’ll come back to that in the la and lw section.

The guide how to use QtSpim explains panel by panel how to read this window. If your QtSpim doesn’t show the start-up code, turn on Simulator → Settings → Load Exception Handler, as in the lab.

Registers: number and name

In the text segment you’ve seen ori $2, $0, 4 where you wrote li $v0, 4, and $4 where you wrote $a0. They are the same registers under another name. MIPS has 32 registers of 32 bits, numbered 0 to 31; the processor only knows the number, and the name is an agreement between programmers (the convention) that says what each one is used for. QtSpim shows the number in the translated instruction and your line, with names, after the semicolon.

NameNumberWhat it’s used forWhy it matters today
$zero0Always 0li $v0, 4 is translated as ori $2, $0, 4: 0 OR 4 = 4
$at1Used by the assembler for pseudo-instructionslw $t1, points overwrites it; don’t use it yourself
$v0, $v12, 3Results; in syscalls, the service numberli $v0, 1, li $v0, 4, li $v0, 10
$a0 to $a34 to 7ArgumentsThe datum or the address you pass to the syscall
$t0 to $t78 to 15Temporaries, for intermediate calculationsla $t0, points comes out as lui $8, 4097
$s0 to $s716 to 23Values that must lastYou’ll see them with subroutines
$t8, $t924, 25More temporaries
$k0, $k126, 27Reserved for the systemDon’t touch them
$gp, $sp, $fp28, 29, 30Pointers to areas of memory (global, stack, frame)$sp is the stack on the memory map
$ra31Return addressjal main stores here where to go back to

To go from number to name, just remember where each group starts: 2 $v, 4 $a, 8 $t, 16 $s, 24 $t8. So $9 is the second of the $t registers ($t1) and $5 the second of the $a registers ($a1).

Check you’ve got it: in la_lw.s, further down, you’ll see lw $9, 0($1). Which registers are they, by name?

$9 is in the group that starts at 8, the $t registers, and it’s the second one: $t1, the destination you wrote in lw $t1, points. $1 is $at, the assembler’s register: it doesn’t appear in your line because the assembler put it there to hold the upper part of the address of points. That’s why, if you used $at for something of your own, a line like this would overwrite it without warning.

Data directives

Data directives tell the assembler what kind of datum you store, how much space it takes and which value it starts with. There are seven:

DirectiveTakesWhat forInventory example
.byte b1, b2, …1 byte eachSmall numbers (−128 to 127, or 0 to 255)lives: .byte 3
.half h1, h2, …2 bytes each16-bit numberscoins: .half 1250
.word w1, w2, …4 bytes each32-bit numbers and arraysitems: .word 5, 2, 0, 1
.ascii "text"1 byte per characterStrings without a 0 byte at the endtitle: .ascii "GAME"
.asciiz "text"1 byte per character + 1Strings with a 0 byte at the end (the ones syscall 4 prints)weapon: .asciiz "Dagger"
.space nn bytesReserving zeroed space (for results, buffers…)gap: .space 3
.align nwhatever is neededMaking the next datum start at a multiple of 2ⁿ.align 2 (multiple of 4)

A comma puts several data in a row: .word 5, 2, 0, 1 is four words, 16 bytes, and the label items points to the first. That’s how you write an array in MIPS. Numbers are decimal unless they start with 0x, and inside strings you can use \n (newline), \t (tab) and \" (quotes).

This is our character’s complete inventory:

# inventory.s: a video game inventory in the data segment
        .data
lives:   .byte 3                    # 1 byte
level:   .byte 12                   # 1 byte, right after
coins:   .half 1250                 # 2 bytes: SPIM places it at an even address
points:  .word 48000                # 4 bytes: at an address that is a multiple of 4
items:   .word 5, 2, 0, 1           # potions, keys, maps and shields
weapon:  .asciiz "Dagger"           # 6 letters + the 0 byte = 7 bytes
gap:     .space 3                   # 3 reserved bytes, set to zero
record:  .word 99999                # another word: it gets aligned again
        .text
        .globl main
main:   li   $v0, 10                # it does nothing else: we only want to see the memory
        syscall

The program prints nothing: we only want to see how memory ends up. And here comes the exam question: at which address does each label land?

How data are placed in memory

SPIM places the data one after another, starting at 0x10010000, with just one extra rule: each .half starts at an even address and each .word at a multiple of 4. If the next free spot doesn’t follow the rule, SPIM skips as many bytes as needed. Those skipped bytes are called padding and stay at zero.

This is QtSpim’s Data tab with inventory.s loaded:

User data segment [10000000]..[10040000]
[10000000]..[1000ffff]  00000000
[10010000]    04e20c03  0000bb80  00000005  00000002    . . . . . . . . . . . . . . . .
[10010010]    00000000  00000001  67676144  00007265    . . . . . . . . D a g g e r . .
[10010020]    00000000  0001869f  00000000  00000000    . . . . . . . . . . . . . . . .
[10010030]..[1003ffff]  00000000

Each line shows 16 bytes as four hexadecimal words and, on the right, the same 16 bytes as characters (a dot if it isn’t a printable character). It’s hard to read at a glance, so let’s go datum by datum with this drawing, taken from that same memory:

The inventory in memoryEach row is a 4-byte word from 0x10010000. lives and level take one byte each, coins two bytes at 0x10010002, points the word at 0x10010004, items four words, weapon seven bytes from 0x10010018 with its 0 byte, gap three zero bytes and record the word at 0x10010024, after one padding byte.+0+1+2+30x10010000030ce2040x1001000480bb00000x10010008050000000x1001000c020000000x10010010000000000x10010014010000000x1001001844D61a67g67g0x1001001c65e72r00\0000x1001002000000x100100249f860100lives:.byte 3level:.byte 12coins:.half 1250points:.word 48000items:.word 5, 2, 0, 1weapon:.asciiz "Dagger"gap:.space 3record:.word 99999alignment paddingData segment byte by byte (row = one word)
Values in hex as they sit in memory. The hatched cell is padding SPIM adds to align record.

And now the calculation by hand, which is what the exam asks for. “Free” is the first unused address before placing each datum:

DatumFreeAlign?AddressTakesNext free
lives: .byte 30x10010000No (a byte fits anywhere)0x1001000010x10010001
level: .byte 120x10010001No0x1001000110x10010002
coins: .half 12500x10010002Even: 2 is even, not needed0x1001000220x10010004
points: .word 480000x10010004Multiple of 4: 4 is0x1001000440x10010008
items: .word 5, 2, 0, 10x10010008Multiple of 4: 8 is0x10010008160x10010018
weapon: .asciiz "Dagger"0x10010018No (strings: byte by byte)0x1001001870x1001001F
gap: .space 30x1001001FNo (.space doesn’t align)0x1001001F30x10010022
record: .word 999990x10010022Multiple of 4: 0x22 = 34 is not → jumps to 0x240x1001002440x10010028

Let’s check a couple of things in the real memory:

  • The first word, 04e20c03, holds four data at once. Its bytes, from the lowest address to the highest, are 03 (lives = 3), 0c (level = 12) and e2 04, which read as a half word give 0x04E2 = 4 × 256 + 226 = 1250 coins. Why do they come out in that order? We’ll see in the next section.
  • 0000bb80 is 0xBB80 = 11 × 4096 + 11 × 256 + 8 × 16 = 48000 points.
  • Dagger is 6 letters: with the final 0 byte, 7 bytes, from 0x10010018 to 0x1001001E. The character column reads D a g g e r .: the dot is that 0 byte.
  • Bytes 0x10010022 and 0x10010023 are the padding: nobody asked for them, but without them record wouldn’t be at a multiple of 4. That’s why record lands at 0x10010024 and holds 0001869f = 99999.

To tell whether an address is a multiple of 4, look only at its last hexadecimal digit: it must be 0, 4, 8 or C. For a .half, it must be even: 0, 2, 4, 6, 8, A, C or E.

With .align n the next datum starts at a multiple of 2ⁿ even if it’s a byte or a string: .align 2 goes to a multiple of 4 and .align 3 to one of 8. And .align 0 does the opposite: it turns off automatic alignment, so a .word can end up at an odd address (until the next .data). In the course exercises you’ll see .align used to make you think about padding.

Memory box by box

The drawing above shows memory by words. In the exam, though, they ask you about a specific address, so it’s worth knowing how to read it byte by byte. These are the boxes of inventory.s in the two areas where there’s something to think about: the beginning, where four data share a word, and the end, where the padding appears.

AddressByteWhich datumWhy
0x1001000003lives3 fits in one byte
0x100100010clevel12 = 0x0c; a .byte goes at any address
0x10010002e2coins, least significant byte1250 = 0x04e2; the address is even, so there’s no padding
0x1001000304coins, most significant byteThe least significant byte goes first (you’ll see it in little endian)
0x10010004 – 0x1001000780 bb 00 00points48000 = 0x0000bb80, starting with the least significant byte
0x10010008 – 0x1001001716 bytesitemsFour words: 5, 2, 0 and 1
0x1001001844weapon: DStrings aren’t aligned: it starts wherever is free
0x1001001961weapon: aOne character per byte, in order
0x1001001A67weapon: g
0x1001001B67weapon: g
0x1001001C65weapon: e
0x1001001D72weapon: r
0x1001001E00weapon: endThe 0 byte that .asciiz adds
0x1001001F00gap, 1st.space doesn’t align: it follows right after
0x1001002000gap, 2nd
0x1001002100gap, 3rdLast reserved byte
0x1001002200paddingrecord is a .word: 0x22 is not a multiple of 4
0x1001002300paddingNor is 0x23
0x100100249frecord, least significant byte0x24 = 36 is a multiple of 4; 99999 = 0x0001869f
0x1001002586record
0x1001002601record
0x1001002700record, most significant byteNext free: 0x10010028

The two zeros at 0x10010022 and 0x10010023 look the same as the ones in gap, but they belong to nobody: the “Which datum” column is the only thing that tells them apart. That’s why in the exam it isn’t enough to look at memory; you have to keep track of “Free”.

Check you’ve got it: if you write .align 3 right before record, where does record land and how many padding bytes are there?

It lands at 0x10010028 and there are 6 padding bytes. The free address after gap is still 0x10010022. .align 3 asks for a multiple of 2 to the power of 3, that is, of 8; in hexadecimal, the last digit has to be 0 or 8. From 0x22, the first one is 0x28 (40 = 5 × 8), so from 0x10010022 to 0x10010027 there are 6 zero bytes that nobody asked for. Checked in SPIM: la $a0, record with syscall 1 prints 268501032, which is 0x10010028.

A label is an address

With the table in front of you, you can see what happened in the hook. Each label in the data segment is a name for the number of the first box of its datum. The value is inside those boxes, and to read it you have to go and fetch it:

LabelIs the addressIn decimalWhat’s insideWhy it matters
lives0x100100002685009923The first label always stands for the start of the data
points0x1001000426850099648000It’s the number I printed with la instead of lw
record0x1001002426850102899999Its address depends on the padding before it
main0x004000244194340The word 0x3402000a (li $v0, 10)Instructions have labels and addresses too

A label takes up no memory and doesn’t change while the program runs: it’s a constant that the assembler replaces with its number. What can change is what’s inside the address.

Little endian: the bytes backwards

A word is 4 bytes, but in which order are they stored? Write a word in hexadecimal and see what QtSpim does:

# endian.s: four bytes that read the other way round from how you write them
        .data
number:  .word 0x12345678           # the word we write in hexadecimal
secret:  .word 0x4546494C           # which letters are in these four bytes?
         .byte 0                    # the 0 byte that ends the string
        .text
        .globl main
main:   li   $v0, 4                 # we print the secret word as if it were text
        la   $a0, secret
        syscall
        li   $v0, 10
        syscall
LIFE

“LIFE”? There’s no string in the program… This is the memory, as the Data tab shows it:

[10010000]    12345678  4546494c  00000000  00000000    x V 4 . L I F E . . . . . . . .

The word shows as 12345678, just as we wrote it. But the character column on the right goes byte by byte, in address order, and there it starts with x V 4: byte 0x78 is the letter x, 0x56 is V and 0x34 is 4. In other words, address 0x10010000 holds byte 78, the least significant one. This drawing makes it clear:

Little endian in QtSpimThe word 0x12345678 is stored with its bytes reversed: 78 at 0x10010000, then 56, 34 and 12 at 0x10010003. The word 0x4546494C stores 4c 49 46 45, the letters L I F E in address order.You write.word 0x1234567812345678most significant byte on the leftIn memory (QtSpim, little endian)0x0000780x0001560x0002340x000312the least significant byte at the lowest address.word 0x4546494Clooks like a number…0x00044c'L'0x000549'I'0x000646'F'0x000745'E'…but syscall 4 reads the bytes in address order:→ LIFE
Real data from endian.s loaded in SPIM: the same memory, two different readings.

QtSpim stores words in little endian: the least significant byte goes at the lowest address. And syscall 4, which prints byte by byte from the address you give it up to the first 0, reads the bytes of secret in address order: 0x4C, 0x49, 0x46, 0x45, which in ASCII are L, I, F, E.

Trusting what the word “looks like” in the Data window. QtSpim shows each word as a number (with the most significant byte on the left), but in memory the bytes are the other way round. If you’re asked which byte is at a given address, count from the end of the word: the last pair of digits is the one at the lowest address.

In the course notes you’ll read that MIPS is big endian (the most significant byte at the lowest address), and it’s true: the original MIPS processor was. But QtSpim uses the byte order of the computer it runs on, and PCs are little endian. In the lab and in the exam, QtSpim rules: little endian.

Check you’ve got it: in inventory.s, which byte is at address 0x10010026?

0x01. record starts at 0x10010024 and holds 99999 = 0x0001869f. In little endian, the least significant byte goes at the lowest address: 0x9f at 0x10010024, 0x86 at 0x10010025, 0x01 at 0x10010026 and 0x00 at 0x10010027. If you had read it left to right in the Data window, the way the word is written, you would have said 0x86, which is the typical mistake from a few lines above. Checked in SPIM with lbu $a0, 0x10010026 and syscall 1: it prints 1.

Strings: .ascii versus .asciiz

A string is its characters, one per byte, in order. The difference between the two directives is at the end:

# ascii.s: .ascii does not add the 0 byte at the end
        .data
title:  .ascii  "GAME"              # 4 bytes, NO 0 byte
ending: .asciiz " OVER\n"           # 6 bytes + the 0 byte
        .text
        .globl main
main:   li   $v0, 4
        la   $a0, title             # we ask to print only the title...
        syscall
        li   $v0, 10
        syscall
GAME OVER

We asked it to print only title, which is "GAME", and out came GAME OVER. Syscall 4 doesn’t know where your string ends: it prints bytes until it finds a 0 byte. .ascii doesn’t add one, so it carried on with the bytes of ending, which start right after. .asciiz (“ascii zero-terminated”) does add it, and that’s where it stopped.

I want…DirectiveBytes of “Dagger”
A string to print with syscall 4.asciiz7 (6 letters + the 0)
Pieces printed together, as a single stringSeveral .ascii and one .asciiz at the end6 in each .ascii
A buffer to read a string from the keyboard.space nas many as you reserve

Miscounting how much a string takes and getting the address of whatever follows wrong. "Dagger" with .asciiz is 7 bytes, not 6; and a \n inside the string is one single byte (10), even though you write it with two characters.

la versus lw: the map and the treasure

Back to the opening bug with a program that does both things at once:

# la_lw.s: the address of a datum versus the datum
        .data
points: .word 48000
newline: .asciiz "\n"
        .text
        .globl main
main:   la   $t0, points            # $t0 = WHERE the points are (the map)
        lw   $t1, points            # $t1 = HOW MANY points there are (the treasure)
        li   $v0, 1                 # service 1: print the integer in $a0
        move $a0, $t0
        syscall
        li   $v0, 4
        la   $a0, newline
        syscall
        li   $v0, 1
        move $a0, $t1
        syscall
        li   $v0, 10
        syscall
268500992
48000

The first line is the same trap as in the lab: 268500992 = 0x10010000, the address of points. Here points is the first datum and sits right at the start; in the hook it came after 4 bytes, which is why it printed 268500996. The second one, the value: 48000.

la versus lwla $t0, points leaves the address 0x10010000 in $t0; lw $t1, points leaves the value 48000 in $t1. When loading, la becomes lui $8, 4097 and lw becomes lui $1, 4097 plus lw $9, 0($1).points: .word 48000at address 0x10010000la $t0, points$t0 = WHERE it is$t0 = 268500992 (0x10010000)lw $t1, points$t1 = WHAT is inside$t1 = 48000in the text segment:lui $8, 4097in the text segment:lui $1, 4097lw $9, 0($1)
la gives you the map; lw, the treasure. Below, what the assembler turns them into (real data from la_lw.s).

la (load address) leaves in the register where the datum is: it’s the map. lw (load word) goes to that address and fetches the 4 bytes inside: it’s the treasure. Neither gives an error if you swap them; you just get a number you didn’t expect. So it pays to know which one each place needs:

I want…UseExample
To print a string (syscall 4)la: the syscall wants the addressla $a0, msg
To print a number stored in memory (syscall 1)lw: the syscall wants the valuelw $a0, points
To go through an arrayla for the start, lw for each elementla $t0, items
To put a fixed number in a registerli: no memory involvedli $t1, 4

And what does the assembler do with them? Look at the text segment of la_lw.s:

[00400024] 3c081001  lui $8, 4097 [points]          ; 7: la $t0, points # $t0 = WHERE the points are (the map)
[00400028] 3c011001  lui $1, 4097                   ; 8: lw $t1, points # $t1 = HOW MANY points there are (the treasure)
[0040002c] 8c290000  lw $9, 0($1)

Neither of them exists as such in the processor:

  • la $t0, points becomes lui $8, 4097. lui (load upper immediate) puts a number in the upper 16 bits of the register and clears the lower ones. 4097 is 0x1001, so $t0 ends up as 0x10010000, the address of points. If the label weren’t right at the start of a 64 KiB block, a second instruction, ori, would be needed for the lower 16 bits: that happens with la $a0, newline, which a few lines further down in the same program becomes lui $1, 4097 and ori $4, $1, 4.
  • lw $t1, points becomes two: lui $1, 4097 leaves the upper part of the address in $1 (the $at register, reserved for the assembler) and lw $9, 0($1) loads the word. That’s why you should never use $at in your programs: the assembler overwrites it whenever it needs to.

This is how the address of newline is built, step by step, in the two instructions that la $a0, newline turns into:

StepInstructionRegister afterwardsWhy
1lui $1, 4097$at = 0x100100004097 = 0x1001 goes into the upper 16 bits; the lower ones are left at zero
2ori $4, $1, 4$a0 = 0x10010004newline is 4 bytes after points, so 4 has to be added to the lower bits

0x10010004 is 268500996 in decimal: the same number as in the hook. It’s no coincidence: in hook.s, points came after a .byte, another .byte and a .half (1 + 1 + 2 = 4 bytes), just as here newline comes after a 4-byte .word.

If a syscall prints a nine-digit number starting with 2685…, you’ve almost certainly passed it an address instead of a value. 268500992 is 0x10010000, the start of your data.

Printing: today’s three syscalls

With three services you can already show results. The recipe is always the same: the datum in $a0, the service number in $v0 and syscall.

Service$v0Before it, put in $a0Example
Print an integer1The valuelw $a0, points
Print a string4The address of an .asciiz stringla $a0, msg
End the program10Nothingli $v0, 10

Forgetting the final li $v0, 10 + syscall. The processor doesn’t know your program has finished: it carries on reading the next address, finds no instruction and QtSpim complains with Attempt to execute non-instruction. You’ll see it live in the exercises of this topic.

When SPIM complains

There are two moments when SPIM can protest. The first, when loading: if a line can’t be understood, a syntax error appears in the messages window and the program isn’t loaded.

# syntax.s: a misspelt instruction
        .data
lives:  .word 3
        .text
        .globl main
main:   lww  $t0, lives             # lww does not exist: it was lw
        li   $v0, 10
        syscall
spim: (parser) syntax error on line 6 of file syntax.s
	  main:   lww  $t0, lives             # lww does not exist: it was lw
           ^

The message gives the line and the exact spot: the ^ points at lww, an instruction that doesn’t exist. Watch out for a SPIM quirk: when the error is at the end of the line, the number it gives is sometimes the next line’s, because it only notices when it reads the line break. Always look at the text it copies underneath too.

The second moment is when running. A misspelt label isn’t caught when loading, but when execution reaches it:

# label.s: a label that does not exist
        .data
lives:  .word 3
        .text
        .globl main
main:   lw   $t0, live              # written without the s
        li   $v0, 10
        syscall
Instruction references undefined symbol at 0x00400024
  [0x00400024]	0x3c010000  lui $1, 0 [live]                ; 6: lw   $t0, live              # written without the s

The program loaded without complaint and failed on the first instruction: live doesn’t exist (it was lives), so the address was left as lui $1, 0 and SPIM refuses to go on. If a program loads fine but does nothing, look at the messages window.

Try it in QtSpim (or right here)

This topic is understood by looking at memory, so open QtSpim (or the playground below, which works the same) and check it:

Loading the MIPS playground… If it doesn’t appear, copy inventory.s into your QtSpim.

  1. Load inventory.s (in QtSpim, Reinitialize and Load File; here, Load) and open the Data tab. Find the line [10010000] and check that the first word is 04e20c03: lives, level and coins in a single word.
  2. Count the padding: on the line [10010020], the first word is 00000000 and the second 0001869f. Nobody asked for the bytes at 0x10010022 and 0x10010023: they’re the jump that makes record land at 0x10010024.
  3. Switch the base to decimal (Data Segment → Decimal in QtSpim, Dec here) and look for 48000 and 99999: now they read at a glance.
  4. Break the alignment: remove gap: .space 3, load again and see where record lands now. Hint: weapon ends at 0x1001001E.
  5. Look at the text segment (Text tab): your main starts at 0x00400024, after the nine instructions of the start-up code.

Summary

ConceptThe essentials
Parts of a program.data for data, .text for instructions, .globl main and main: where it starts
Kinds of lineDirectives (with a dot), labels (with a colon), instructions, pseudo-instructions and comments (#)
Where everything livesStart-up code at 0x00400000, your main at 0x00400024, your data at 0x10010000
Sizes.byte 1, .half 2, .word 4, .asciiz characters + 1, .space n n bytes
Alignment.half at an even address, .word at a multiple of 4; the gaps left are padding
Little endianIn QtSpim, the least significant byte of each word goes at the lowest address
la and lwla gives the address (the map), lw the value (the treasure); both are pseudo-instructions with labels
Syscalls1 prints an integer (value), 4 a string (address), 10 ends

Three ideas to take away

  1. A label is an address, not a value: la gives you that address and lw what’s inside.
  2. Memory fills up in order, with padding before every .half and .word that doesn’t land aligned. Being able to work out those addresses by hand is half of the data exercises.
  3. QtSpim is little endian: the bytes of a word are the other way round from how you write it, and the character column of the Data window shows you.

In the MIPS program structure and data practice we’ll build three programs with the inventory: one that prints the memory map with the distances between data, a game over banner made of .ascii pieces and a detective that reads the same memory as text and as a number.

Next step: practiceMIPS program structure and data — practice with the inventory map, a game over banner and the same memory read two ways (and the banner I printed with four syscalls)

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