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?
- AUse a single addi with the whole 32-bit immediate
- BSet the upper 20 bits with lui, then add the lower 12 bits with addi
- 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. 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.