RISC-V 5-Stage Pipeline and Hazards Visualizer
Enter a few instructions, turn forwarding on or off, and see where the pipeline stalls and why.
Data hazards only: branches are treated as not taken. The register file writes in the first half of a cycle and reads in the second.
| Instruction | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
lw x1, 0(x2) | IF | ID | EX | MEM | WB | |||||
sub x4, x1, x5 | IF | stall | ID | EX | MEM | WB | ||||
and x6, x1, x7 | stall | IF | ID | EX | MEM | WB | ||||
or x8, x1, x9 | IF | ID | EX | MEM | WB | |||||
add x10, x4, x6 | IF | ID | EX | MEM | WB |
sub x4, x1, x5reads x1, written bylw x1, 0(x2): a load-use hazard, 1 stall even with forwarding.add x10, x4, x6reads x6, written byand x6, x1, x7: a read-after-write hazard, resolved by forwarding with no stall.
The formulas
N instructions in a 5-stage pipeline: the first takes 5 cycles, each later one adds 1, and every stall adds 1.
Cycles per instruction once the pipeline is full.
Worked example: a load followed by its uses
- lw x1, 0(x2); sub x4, x1, x5; and x6, x1, x7; or x8, x1, x9; add x10, x4, x6.
- With forwarding: sub needs x1 in EX, but the load only has it at the end of MEM, so sub waits 1 cycle (a load-use hazard). Everything else is forwarded. 5 + 4 + 1 = 10 cycles.
- Without forwarding: sub must wait until lw writes back, 2 stalls. and and or are far enough behind to read x1 from the register file. add needs x6 from and, two instructions earlier: 1 more stall. 5 + 4 + 3 = 12 cycles.
- Only data hazards are modeled. Branches are treated as not taken, so control hazards don't appear.
- Reordering independent instructions into the slot after a load removes the load-use stall; compilers do exactly this.