div

div

RISC-V Assembly Reference

lyszt.net covers div 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

Divides the value of one register by another and drops the fractional part. In div rd, rs1, rs2, rs1 is divided by rs2 and the quotient goes to rd. Dividing 17 by 5 yields 3, and rem on the same operands returns the leftover 2. Division rounds toward zero, and -7 divided by 2 yields -3. Dividing by zero yields -1 without any warning, and code that treats a zero divisor as an error must test the divisor first.

Official definition

RISC-V Instruction Set Manual

DIV and DIVU perform an XLEN bits by XLEN bits signed and unsigned integer division of rs1 by rs2, rounding towards zero. REM and REMU provide the remainder of the corresponding division operation. For REM, the sign of a nonzero result equals the sign of the dividend.

If both the quotient and remainder are required from the same division, the recommended code sequence is: DIV[U] rdq, rs1, rs2; REM[U] rdr, rs1, rs2 (rdq cannot be the same as rs1 or rs2). Microarchitectures can then fuse these into a single divide operation instead of performing two separate divides.

Semantics for division by zero and division overflow. L is the width of the operation in bits: XLEN for DIV[U] and REM[U], or 32 for DIV[U]W and REM[U]W.

ConditionDividendDivisorDIVU[W]REMU[W]DIV[W]REM[W]
Division by zero Overflow (signed only)x -2^L-10 −12^L-1 -x -−1 -2^L-1x 0