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

前端 未结 1 389
生来不讨喜
生来不讨喜 2020-12-20 07:48

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

相关标签:
1条回答
  • 2020-12-20 08:15

    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.

    0 讨论(0)
提交回复
热议问题