user84037
user84037

Reputation: 83

MIPS32: ld pseudo instruction translation

I am trying to understand how the pseudo instruction in MIPS32 "ld" works. I use the MARS Simulator to test the code. When MARS assembles the following Code

    .data
LEN:
    .word 12
.text
ld $6, LEN

it says in basic code

lui $1, 0x00001001
lw $6, 0x00000000($1)
lui $1, 0x00001001
lw $7, 0x00000004($1)

The lw instructions seem to do everything needed: It loads 32 bits at the specific address 0x00000000 into Register $6 and the following 32 Bit into the following Register.

The lui instruction seem useless to me. It even does the same thing twice, why? It is used as Offset for the lw instruction, but it must have twice the same value, otherwise we dont get the 64 bit at the memory address, but two "random" 32 bits?

Can anyone help me where my mistake in thinking is? It is probably completely different than I think...

Upvotes: 2

Views: 947

Answers (1)

Ped7g
Ped7g

Reputation: 16586

The LEN is inside .data segment at offset +0, which is address 0x0000100100000000 (start of .data segment).

So the lw instructions are fetching the data from address 0x0000100100000000+0 and 0x0000100100000000+4, that's calculated from $1 + 0 and $1 + 4.

The lui sets that value into $1.

Twice, because MARS assembler is sort of "dumb", producing native MIPS instructions in fixed way, not optimizing special cases where the value is already in $1 register. Some of the pseudo instructions can be even implemented in more effective way, if you would check all of them, it's not like MARS is producing most optimal variant.

You can theoretically remove the second lui in this particular case without affecting the result, but removing the first lui would make the lw to access completely different memory area (as the $1 register would contain different value).


EDIT: btw, you did reserve only single .word for LEN, so the second lw is fetching value beyond that word, usually in more complex source that would be bug/oversight.

And if you would reserve LEN after some other .data memory already used, the lui would be followed by ori to put into $1 complete address including lower 16 bits. It's one of rare MARS optimizations, to remove the ori of "load address" when the low 16 bits are all zeroes.

I guess the ld would then look like lui, ori, lw, lui, ori, lw, i.e. there would be even more redundancy.

Upvotes: 1

Related Questions