Search code examples
assemblymipsinstruction-setimmediate-operand

How does LUI/ORI on MIPS work to create a 32-bit constant value?


I have this risc v code :

lui S0, 0x1234
ori S1, S0, 0x5678
add S2, S1, S1

and the question asks me, "What does the register S2 hold?" The question explains that lui and I quote:

"Load the lower half word of the immediate imm into the upper halfword of register rt. The lower bits of the register are set to 0"

I don't know how to 'compile this program' and what does 0x1234 mean?


Note: This question was originally titled/tagged , but the code can only assemble for MIPS, and the accepted answer is also only correct for MIPS. So lets just make it a MIPS question.

MIPS uses 16-bit immediates for lui and all other immediate instructions, and zero-extends bitwise boolean immediates (ori/andi/xori). Other MIPS instructions do sign-extend their immediate, like RISC-V does for everything.

RISC-V lui takes a 20-bit immediate, while other instructions only take a 12-bit sign-extended immediate, so lui and/or addi can still materialize any 32-bit constant in 1 or 2 RISC-V instructions, like MIPS and all(?) other 32-bit RISC ISAs.


Solution

  • Take the instructions one at a time. First the load-upper-immediate, take the immediate (0x1234) and "load" it into the upper half of the S0 register and zero out the lower half:

    lui S0, 0x1234 
    
    S0 = 0x12340000
    

    Next the or-immediate, we OR the value in S0 with the value 0x5678:

    ori S1, S0, 0x5678
    
       0x12340000
    OR 0x00005678
       ----------
       0x12345678 = S1
    

    Finally the add, we are adding the value in S1 to itself or, equivalently, multiplying the value in S1 by 2:

    add S2, S1, S1
    
      0x12345678
    + 0x12345678
      ----------
      0x2468ACF0 = S2
    

    So the value in S2 register is 0x2468ACF0. Note, I am assuming 32-bit words. An immediate is like a constant, so lui is an instruction that places a constant into the upper half of a register. In combination with ori, you can load an entire word-immediate into a register.