# Phase 5.1 - Branch Instructions ## Context Branches compare two registers and conditionally update PC to a PC-relative target. They enable loops and conditionals. ## Goals - Implement `beq`, `bne`, `blt`, `bge`, `bltu`, and `bgeu`. - Learn signed and unsigned branch comparisons. - Verify target calculation and fall-through behavior. ## New Concepts - PC-relative addressing: target is computed from current PC plus immediate. - Branch comparator: dedicated comparison logic for branch conditions. - B-type immediate: split immediate format used by branch instructions. - Taken branch: branch condition true, PC becomes target. ## How To Think About It Separate three questions: what is the target, is the condition true, and which PC should be used next? Debugging is easier when those are visible independently. ## Learning Tasks - Decode a B-type immediate by hand. - Build test cases where signed and unsigned comparisons differ. - Trace a loop from initialization through exit. ## Pitfalls - Forgetting branch offsets are multiples of 2 bytes in the encoding. - Comparing signed values with unsigned operators. - Counting loop iterations incorrectly because PC update timing is unclear. ## Tooling And Testing - Use assembler-generated branch encodings. - In waveforms, inspect PC, immediate, comparator result, and next PC. - Include backward and forward branch targets. ## References - RISC-V unprivileged ISA, branch instructions: https://riscv.org/technical/specifications/ - RISC-V assembly manual: https://github.com/riscv-non-isa/riscv-asm-manual - RISC-V opcode data: https://github.com/riscv/riscv-opcodes