B-Type Instruction

The B-type (branch) format is designed for the conditional branch instructions that require two registers and a label. It follows the format:

3130-2524-2019-1514-1211-876-0
imm[12]imm[10:5]rs2rs1funct3imm[4:1]imm[11]opcode

where the instruction’s label is stored as a 13-bit immediate offset multiple of 4 whose 0th bit is constant and is not stored since it is known (imm[12:1]). This way, we do not need additional infrastructure since we resemble the S-type and R-type’s layout; more specifically, imm[10:1] is stored in the same manner as it is in the S-type. Finally, imm[12] holds the integer’s sign and is most efficiently accessed at the beginning of the instruction.

Intuition

Since the computer cannot recognize labels, we have to somehow convert them into offset immediates to store them. This is done by calculating the distance where a label has been called from the label itself. Consider the following code:

		beq x0 x0 target  #+2 instructions = 8 bytes, so offset=8

		addi x0 x0 100

target: addi x0 x0 100. # callee

		j target #-1 instruction = -4 bytes, so offset=-4

		li t0 0x5F3759DF #The li here is actually 2 instructions

		beq t0 t0 target #-4 instructions, so offset=-16**

Here, the offset at beq x0 x0 target is 8 bytes, since each instruction is 4 bytes and the line is 2 instructions away from the target label. Similarly, the offset at beq t0 t0 target is -16 bytes since the caller line is -4 lines “above” the target label.

Since evidently all label offsets are a multiple of 4, we must omit the last two (rightmost) bits. We can first verify this using a quick check: , . However, some 16-bit RISC-V operations use the 2nd bit, and as such, we only omit the rightmost bit.