Understanding RISC-V 5-Stage Pipeline Hazards and Forwarding
Instruction pipelining is the fundamental technique used in modern microprocessors to execute multiple instructions concurrently. In this post, we explore the classic 5-stage RISC-V pipeline: Instruction Fetch (IF), Instruction Decode (ID), Execute (EX), Memory Access (MEM), and Write Back (WB).
The 5-Stage In-Order Pipeline
- IF (Instruction Fetch): Fetches the 32-bit instruction from memory at the current PC.
- ID (Instruction Decode / Register Read): Decodes opcode, reads source registers (rs1, rs2).
- EX (Execute / ALU): Computes arithmetic results or branch target address.
- MEM (Memory Access): Reads from or writes to data cache for load/store instructions.
- WB (Write Back): Writes the result back to destination register (rd).
The Data Hazard Problem
Consider this sequence of instructions:
Without hazard mitigation, the sub instruction would read the stale value of x1 because add has only completed its EX stage when sub needs the value in ID.
Solution: Operand Forwarding (Bypassing)
Instead of stalling the pipeline for two full cycles, we can route the calculated ALU result directly from the output of the EX/MEM pipeline register back to the ALU input multiplexer in the EX stage:
Load-Use Hazard
When a load instruction is immediately followed by an instruction that depends on the loaded value:
Here, forwarding alone is not enough because the data is only ready at the end of the MEM stage. The pipeline must insert one stall cycle (bubble), after which forwarding can supply the value from MEM/WB into the EX stage.
Conclusion
Understanding hazard detection and forwarding mechanics provides the foundation for designing custom RISC-V cores and building hardware-aware compilers that schedule instructions to avoid load-use bubbles.