Sub topic 2
Pipeline Hazards: Resource Conflicts, Data Dependences, and Forwarding
This chapter assumes you know the five pipeline stages (IF, ID, EX, MEM, WB), what a pipeline register does, and how to read simple assembly instructions such as add, sub, and lw.
A hazard is a situation where the next instruction cannot run in its planned cycle. The processor then either stalls, meaning it waits, or does extra work to stay correct.
Structural hazards: resource conflicts
A structural hazard occurs when two instructions in the pipeline need the same hardware unit in the same cycle. A classic case is a single memory unit used for both instruction fetch (IF) and data access (MEM). If one instruction is in MEM while a later one is in IF, the pipeline must stall one of them. Designs avoid this by using separate instruction and data caches.
Data hazards: RAW, WAR, and WAW
A data hazard occurs when instructions depend on each other's operands. The three kinds are named by the order of reads and writes:
- RAW (read after write): a later instruction reads a register before an earlier one writes it. In an in-order five-stage pipeline, this is the only kind that occurs.
- WAR (write after read): a later instruction writes a register before an earlier one reads it.
- WAW (write after write): a later instruction writes a register before an earlier one writes it.
Reads happen in ID and writes happen in WB, so in-order pipelines never reorder them. WAR and WAW matter mainly in out-of-order designs.
Stalls and bubbles: resolving hazards by waiting
The simplest fix is to stall. The pipeline holds the dependent instruction in ID and inserts a bubble, a no-op, into EX. The bubble pushes every later instruction back by one cycle.
add r1, r2, r3 # writes r1 in WB
sub r4, r1, r5 # reads r1 in ID: RAW hazardWithout forwarding, sub must stall two cycles, because add writes r1 in WB, two cycles after sub reaches ID.
Operand forwarding: removing most data stalls
Forwarding, also called bypassing, adds wires that copy a result from a pipeline register straight to the EX input of the next instruction. The add result exists at the end of EX, so it can feed the sub in its EX stage. With forwarding, no stall is needed.
add r1, r2, r3 # result ready at end of EX
sub r4, r1, r5 # forwarded from EX/MEM into EX: no stallThe load-use hazard: the stall forwarding cannot remove
A load gets its value only at the end of MEM, not EX. An instruction that uses the loaded value right away must wait at least one cycle, even with forwarding.
lw r1, 0(r2) # value ready after MEM
add r3, r1, r4 # needs r1 at start of EX: 1 stall cycleExercise
In a five-stage pipeline with forwarding, how many stall cycles does a load followed immediately by a dependent add need?
Show answer
One stall cycle. The loaded value exists only at the end of MEM, so the add's EX stage must wait one cycle before it can take the forwarded value.