Understanding how `lw` and `sw` actually work in a MIPS program
lw (load word) loads a word from memory to a register.
lw $2, 4($4) # $2 <- mem($4+4)
$2 is the destination register and $4 the address register. And the source of information is the memory.
4 is an offset that is added (not multiplied) to the address register. This kind of memory access is called based addressing and is it quite useful in many situations. For instance, if $4 hold the address of a struct, the offset allows to pick the different fields of the struct. Or the next or previous element in a array, etc. offset does not have to be a multiple of 4, but (address register + offset) must and most of the time both are.
Sw is similar, but stores a register into memory.
sw $5, 8($7) # mem[$7+8] <- $5
Again $7 is the register holding the memory address, 8 an offset and $5 is the source of the information that will be written in memory.
Note that contrary to others MIPS instructions, the first operand is the source, not the destination. Probably this is to enforce the fact that the address register plays a similar role in both instruction, while in lw it is used to compute the memory address of the source of data and in sw the memory destination address.
Ski Mask
I ask a lot of questions. Excuse me for the bad terminology.
Updated on March 06, 2020Comments
-
Ski Mask about 4 years
I'm having bit of a difficulty understanding what
sw
andlw
do in a MIPS program. My understanding of the topic is that we uselw
to transfer data from the memory into the register and vice-versa forsw
. But how is this exactly accomplished?Let's say we have the following line of code:
lw Reg.Dest, Offset(Reg.Source) sw Reg.Source, Offset(Reg.Dest)
If we concentrate on
lw
it's essentially storing the data from the memory,Reg.Source
and multiplying the address of that data with theOffset
, always a multiple of $4$ because the registers deal with $32$ bits and the memory uses $8$ bits, into a specific address in the register which is equal toOffset + Reg.Source
- so if we say thatOffset = 16, Reg.Source = $s1 = 12
then the register will store the data from the memory into the address $28$ in the register.Assuming that my understanding of
lw
is correct, my question is then how doessw
work?PS: It would be great if the answers could also contain just a one liner example such as
sw $t0, 32($s3)
.