# Phase 5 - Branches And Jumps ## Context This phase adds control flow. The CPU stops being a straight-line executor and gains loops, conditionals, function calls, and returns. ## Goals - Implement conditional branches. - Implement `jal` and `jalr`. - Learn PC selection and control-transfer testing. ## New Concepts - Branch target: destination address for a taken branch. - Fall-through: next sequential PC, usually PC + 4. - Link register: register receiving return address for calls. - Control hazard: later pipeline issue where fetched instructions may be wrong. ## How To Think About It Control flow is just PC update logic plus optional register writeback. Keep the comparison, target calculation, and PC selection clearly separated. ## Learning Tasks - Hand-compute branch and jump targets from instruction immediates. - Trace a simple loop and count taken versus not-taken branches. - Understand why `jalr` clears bit 0 of the target address. ## Pitfalls - Off-by-four errors between current PC and next PC. - Using unsigned comparison for signed branches. - Forgetting that `jal`/`jalr` write PC + 4 to `rd`. ## Tooling And Testing - Test both taken and not-taken paths for every branch type. - Use short loops with known iteration counts. - Probe PC source selection in simulation and ILA. ## References - RISC-V branch and jump semantics: https://riscv.org/technical/specifications/ - RISC-V assembly examples: https://github.com/riscv-non-isa/riscv-asm-manual - Computer architecture control flow overview: https://www.nand2tetris.org/