7

Recently, I am working on RV32I base instruction set, and I did not find any instruction looks like LD r1, imm. Thus, I am wondering how assembly programer load an immediate to a register in RV32I system? Thanks.

To do so, programmer could use ADDI r1, r0, imm. Since r0 is a constant 0, so this instruction move imm to register r1.

I have no idea if the designers of RV32I think this way, use ADDI to replace LD r1, imm?

Hope anyone could shed some lights on it. Thanks.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Betty
  • 161
  • 1
  • 2
  • 6

1 Answers1

8

There is a li (load immediate) alias or pseudo instruction that provides the functionality you are referring too.

The following example shows the li pseudo instruction which is used to load immediate values:

.equ  CONSTANT, 0xdeadbeef

li    a0, CONSTANT

Which, for RV32I, generates the following assembler output, as seen by objdump:

00000000 <.text>:
   0: deadc537            lui a0,0xdeadc
   4: eef50513            addi    a0,a0,-273 # deadbeef <CONSTANT+0x0>

This snippet is from this github markdown that is a good reference when programming in riscv assembly. https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md#load-immediate

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
FeelTheBurns
  • 1,065
  • 2
  • 8
  • 14
  • I reviewed the specification of RV32I, I found there are two instructions, so-called LUI and AUIPC. LUI and ADDI could be used together to load a 32-bit immediate number to some registers, while AUIPC and LB could be used together to get access to any data which stored at address (PC + 32-bit offset), and AUIPC and JALR could be used together to jump to any procedure which begins at address (PC + 32-bit offset). – Betty Jun 27 '19 at 02:21
  • @Betty I edited the answer to show more context as to what the pseudo instruction is doing. There is also an la (load address) pseudo instruction which may also be useful. https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md#load-address. But your comment looks correct. – FeelTheBurns Jun 27 '19 at 15:45
  • 2
    What kind of insane assembler emits four instructions to materialize a 32-bit constant on RV32? `clang -c -target riscv32 foo.s` assembles that to `37 c5 fe ca lui a0, 831468` (using all immediate 20 bits, not leaving most of them zero) and `addi a0, a0, -1346` same as the final instruction here. The manual you linked on github has since been fixed to show it assembling to 2 instructions, so I guess RV32I doesn't put any extra restriction on allowed immediates for LUI. I'll update your answer, I guess. – Peter Cordes Apr 26 '22 at 04:43