Hands on Risc-V (RV32IMAC) assembler : Part 4

Making decisions

Up until now, the microprocessors I have dealt with made decisions using the following pattern:

compare A to B

branch if higher/lower/same etc to somewhere else

The compare instruction is similar to a subtraction however the result is not used but changes to the ALU flags are used to by the subsequent conditional branch instruction to determine whether the branch (jump) is taken or not. Comparison operands typically can be registers or (sometimes) an immediate values.

The RV32IMAC architecture executes the compare and conditional jump operation as a single instruction. Some examples are:

	beq t0,zero,jump2
	bne t0,zero,jump1
	
	blt t0,t1,jump1
	bltu t0,t1,jump2
	ble t0,t1,jump2
	bleu t0,t0,jump1
	
	bgt t0,t1,jump2
	bgtu t0,t0,jump1
	bge t0,t1,jump2
	bgeu t0,t0,jump1
	

Note that conditional branches work with registers only. The destination is a 12 bit signed relative offset expressed in two byte steps. In other words if this is 5 then the actualy offset is 10 bytes away. The first two comparisons above use the zero register in the CPU core as one of the operands. The u suffix on the conditional branch instructions indicates that an unsigned comparison is to be made.