How to use MIPS load word

Viewed 3337

Maybe this question sound stupid :) but I am abit confused, can someone explain why does the code use lw to load word from memory to register while 0x1b430010 is already in register $t1 by using lui and ori?

lui $t1,0x1b43 
ori $t1,$t1,0x0010 
lui $t2,0xabbb 
ori $t2,$t2,0x8050

lw $t0,0($t1) 
srl $t0,$t0,6 
andi $t0,$t0,0x3

lw $t3,0($t2) 
andi $t3,$t3,0xff9f 
sll $t0,$t0,5 
or $t3,$t3,$t0 
sw $t3,0($t2)
1 Answers

0x1b430010 is in t1 as number (32 bit unsigned integer), representing memory address. The lui + ori build this constant in t1 from partial immediate values encoded directly in lui/ori instruction opcodes (each MIPS instruction is encoded as 32 bit word, so part of those bits form a pattern known to CPU as lui instruction, or ori instruction, and the remaining, 16 bits IIRC, form the immediate value to be used by the instruction).

The lw $t0,0($t1) is quite different, it will first use the value in t1 (modified by constant "displacement" +0 - that's that "0" ahead of parentheses) as memory address, i.e. the CPU will set address bus wires to value 0x1b430010, and then it will signal the memory chip it should use those address wires and do the memory load from that address, setting up the read value on bus data-wires. Once the memory chip will signal the CPU, that data were read and data-wires are in correct state, CPU will store that state as new value of t0.

In short, it will load word from computer memory at address 0x1b430010 into register t0 - but what is the actual value stored in memory there, that's not possible to tell from your short snippet.

JFYI: the memory on MIPS is addressable by bytes (address bus is 28 or 30 bits wide? or full 32? Depends probably on particular target HW = the width of address bus defines the maximum area you can address, i.e. it limits maximum possible memory available in the CPU address space). So by setting up particular address, you can read/modify any byte of memory (as long as you have enough privileges to do it, and it's not read-only memory, or void space unmapped by any memory chip).

There's a minor catch, that load/store word instructions require (to keep HW design of memory management unit simpler) the memory address to be "word aligned", i.e. divisible by 4 (equals "bottom two bits are zero"). Similarly to read half-word, the memory address must be half-word aligned (divisible by 2 = bottom address bit zero). If you are working with unaligned data buffers, you have to load it per single bytes (and compose word value out of four byte reads), to avoid crashing on unaligned memory access by using lw on wrong address.

The value 0x1b430010 is divisible by 4 (bottom four bits are zero, while two would be enough, this is actually divisible by 16), and that memory address is probably pointing into .data area, so doing lw from there should work without problem.

Related