blt

blt

RISC-V Assembly Reference

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

blt compares two values and branches when the first is smaller. beq and bne test equality instead. The name stands for branch if less than. The form below jumps to the labeled position when rs1 is less than rs2, and falls through to the next instruction otherwise.

blt rs1, rs2, label

The beq page explains branches, labels, and how a jump works.

The comparison treats both values as signed, so they can be negative. -1 is less than 0, and any negative number is less than any positive one. Unsigned comparisons use a separate instruction, bltu, and the two disagree on any value whose top bit is set.

Counting loops rely on blt. The line below repeats while the counter t0 stays below its limit t1.

blt t0, t1, loop

Once the counter reaches the limit, the branch is not taken and the loop ends. Bounds checks use the same instruction to keep a value under a maximum before the program uses it.

The RISC-V manual specifies that blt and bltu take the branch when rs1 is less than rs2, comparing signed and unsigned respectively. It also notes that bgt, bgtu, ble, and bleu can be synthesized by reversing the operands of blt, bltu, bge, and bgeu.

RISC-V provides no branch if greater. To test whether a is greater than b, reverse the comparison and test whether b is less than a. The assembler offers a bgt shorthand that swaps the operands for you.

Example

li t0, 2
li t1, 5
blt t0, t1, done   # 2 < 5, so jump to 'done'