Reading — step 1 of 5
Read
~2 min readInstruction Decoding
Branches & Jumps
Control flow instructions:
Branches (B-type, conditional, PC-relative):
- BEQ rs1, rs2, offset: branch if equal.
- BNE rs1, rs2, offset: branch if not equal.
- BLT rs1, rs2, offset: branch if less (signed).
- BGE rs1, rs2, offset: branch if greater-or-equal (signed).
- BLTU / BGEU: unsigned variants.
python
If condition true: pc = pc + sign_extend(offset). Else: pc += 4 (next instruction).
Branch offsets are 13-bit signed (range ±4 KiB), multiples of 2.
JAL (J-type, jump and link):
- jal rd, offset
- rd = pc + 4 (return address).
- pc += sign_extend(offset).
Used for function calls: jal ra, function.
JALR (I-type, jump and link register):
- jalr rd, offset(rs1)
- rd = pc + 4.
- pc = (rs1 + sign_extend(offset)) & ~1.
Used for indirect calls and returns: jalr x0, 0(ra) (= ret).
Implementation:
python
After every instruction, advance pc. Branches may override.
Pseudoinstructions:
j label→jal x0, label(no return address saved).jr rs→jalr x0, 0(rs).ret→jalr x0, 0(ra).call label→auipc + jalr(for far calls).bgt rs1, rs2, lbl→blt rs2, rs1, lbl(operands swapped).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…