ISA & Assembly

In RISC-V, what is the usual way to put a 32-bit constant that does not fit in a 12-bit immediate (e.g. 0x12345678) into a register?

  1. AUse a single addi with the whole 32-bit immediate
  2. BSet the upper 20 bits with lui, then add the lower 12 bits with addi
  3. CConstants cannot be used, so the value must always be read from input
Show answer and explanation

Answer: B. Set the upper 20 bits with lui, then add the lower 12 bits with addi

lui (load upper immediate) places a 20-bit immediate in bits 31-12 of a register and clears the low 12 bits. Following it with addi to add the low 12 bits produces any 32-bit constant. However, the addi immediate is sign-extended, so when the top bit of the low 12 bits is 1, the lui value must be made one larger. Writing "li a0, 0x12345678" in assembly makes the assembler expand it into these two instructions as needed. In fixed-length ISAs, building large constants in pieces is the norm.

  • A. A 32-bit immediate cannot fit in a 32-bit instruction.
  • B. Correct. The li pseudo-instruction expands to this pair.
  • C. Two instructions build it, or it can be loaded from memory.