add

add

RISC-V Assembly Reference

lyszt.net covers add and other RISC-V instructions in more detail.

Encoding format

R
31–25funct7
24–20rs2
19–15rs1
14–12funct3
11–7rd
6–0opcode
I
31–20imm[11:0]
19–15rs1
14–12funct3
11–7rd
6–0opcode
S
31–25imm[11:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:0]
6–0opcode
B
31–25imm[12,10:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:1,11]
6–0opcode
U
31–12imm[31:12]
11–7rd
6–0opcode
J
31–12imm[20,10:1,11,19:12]
11–7rd
6–0opcode

Description

add sums the values in two registers and stores the result in a third. A register is a small slot inside the processor that holds a single 32-bit number. RISC-V provides 32 registers. A bit is one 0 or 1, and 32 bits cover whole numbers from 0 up to roughly four billion. Arithmetic takes place between registers and never touches memory directly.

add has the form below, and the result is rd = rs1 + rs2. rd is the destination register, where the answer goes. rs1 and rs2 are the source registers, and their values stay the same.

add rd, rs1, rs2

The destination can serve as a source too. The line below adds t1 to t0 and puts the result back in t0. Running totals in loops use this form.

add t0, t0, t1

A register holds at most 32 bits. When a sum exceeds the largest value a register can hold, the result wraps around to a small number, the way a 24-hour clock goes from 23:59 back to 00:00. This is overflow, and RISC-V gives no warning when it occurs.

The RISC-V manual states that no integer computational instruction raises an arithmetic exception, and that the base instruction set carries no overflow checks because branches handle the job at low cost. For unsigned addition, one branch after the add suffices. In the two lines below, the branch jumps to the label overflow when the sum is less than an operand, which happens only if the sum wrapped around.

add t0, t1, t2
bltu t0, t1, overflow

In the example, the first two lines use li (load immediate) to place the constants 3 and 4 in t0 and t1. The add line then leaves 7 in t2.

Example

li t0, 3
li t1, 4
add t2, t0, t1   # t2 = 7