Understanding how `lw` and `sw` actually work in a MIPS program

十年热恋 提交于 2020-01-06 07:54:36

问题


I'm having bit of a difficulty understanding what sw and lw do in a MIPS program. My understanding of the topic is that we use lw to transfer data from the memory into the register and vice-versa for sw. 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 the Offset, 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 to Offset + Reg.Source - so if we say that Offset = 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 does sw work?

PS: It would be great if the answers could also contain just a one liner example such as sw $t0, 32($s3).


回答1:


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.



来源:https://stackoverflow.com/questions/54136371/understanding-how-lw-and-sw-actually-work-in-a-mips-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!