目录 ← 首页
CS61C

J-Type

Learning Outcomes

  • Translate between J-Type assembly instructions and machine instructions.
  • Identify use cases for different unconditional jump instructions and pseudoinstructions: j, jr, jal, jalr, ret.
  • Use J-Type instructions for conditional branches.

Jump Instructions

The remainder of this page covers in-scope content that was not covered in lecture.

Conditionally Branching Far Away

Conditional Branches are typically used for if-else statements, for/while loops. In general, because these control structure are usually pretty small (<50 lines of C code), we can use B-Type instructions. However, as we saw earlier, B-Type instructions have limited range: ±210\pm 2^{10} instructions from the current instruction (PC).

To jump even further, we can use J-Type unconditional jumps in combination with B-Type instructions.

Admittedly, J-Type instructions also have a limited range: ±218\pm 2^{18} instructions from the currrent insturction (PC).

If we wanted to jump to any address, RISC-V opts for jumping with absolute addressing and jalr. As discussed in a previous section, jalr is an I-Type instruction that sets PC to PC = R[rs1] + imm, where imm specifies a 12-bit immediate imm.

  • To call functions with absolute addressing, instead of jal ra Label1:
    lui  ra <hi20bits*>
    jalr ra ra <lo12bits>
  • To break out of loops using absolute addressing, instead of j Label (e.g., jal x0 Label):
    auipc ra <hi20bits*>
    jalr  x0 ra <lo12bits>

See the discussion of U-Type instructions lui and auipc. Just like with resolving li pseudoinstructions, jalr sign-extends immediates. So if lo12bits has sign bit set, increment hi20bits by 1.

Footnotes

  1. The jalr instruction will save the jump address to the PC and save the current PC + 4 to the ra in the same cycle (effectively, “simultaneously”)