add
lyszt.net covers add and other RISC-V instructions in more detail.
Encoding format
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
References
- [1]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4, Integer Computational Instructions, page 27.
- [2]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4.2, Integer Register-Register Instructions, page 29.
