rem
lyszt.net covers rem and other RISC-V instructions in more detail.
Encoding format
Description
rem gives the remainder of a division, which is the amount left over. Dividing 17 by 5 goes in 3 times with 2 left over. div returns the 3 and rem returns the 2. The name is short for remainder. The form is shown below and means rd = the remainder of rs1 divided by rs2.
rem rd, rs1, rs2
It belongs to the same optional M math extension as div.
The two instructions work on the same pair of numbers and together give the quotient and what is left. rem is the assembly form of the % (modulo) operator in higher-level languages.
With negative numbers the remainder takes the sign of the number being divided. 7 remainder 2 is 1, and -7 remainder 2 is -1. A test for odd numbers that checks whether the remainder by 2 equals 1 gives the wrong answer for negative numbers. Checking whether the remainder is zero decides even or odd for every sign.
The RISC-V manual says rem provides the remainder of the corresponding division and that a nonzero result has the sign of the dividend. Every division that does not overflow satisfies dividend = divisor times quotient plus remainder. A remainder by zero equals the dividend, and the signed overflow case, the most negative number divided by -1, gives a remainder of zero. To get the quotient and the remainder of the same division, the manual recommends div and then rem on the same operands, which a processor can fuse into a single division.
Remainders are used to wrap a counter back to the start of a buffer, to take digits off a number and to spread items across slots. A remainder by zero returns the original number. The example computes 17 remainder 5 and leaves 2 in t2.
Example
li t0, 17 li t1, 5 rem t2, t0, t1 # t2 = 2
