Skip to content
Tactiverge

Textbooks/Computer Architecture/Chapter 3Lite (plain text) version

3Pipelining and hazards

Version 1 · Technically checked (automated checks only) · 3 source lessons · 8 practice items

Text
All chapters and search
  1. 1. Instruction-set design
  2. 2. The performance equation
  3. 3. Pipelining and hazards
  4. 4. Caches and the memory hierarchy
  5. 5. Input, output and the hardware–software boundary
  6. 6. Parallelism and acceleration
  7. 7. Energy and reduced precision
  8. 8. Measuring performance honestly

Introduction

A pipeline overlaps instructions like an assembly line, so in the ideal case one finishes every cycle. Reality interrupts. An instruction needs a value that is not ready yet (a data hazard), the next instruction depends on a branch not yet decided (a control hazard), or two stages want the same hardware (a structural hazard). This chapter counts the cost of each, shows how forwarding and prediction recover most of it, and explains measured speed-ups from first principles.

12345678lw r1IFIDEXMEMWBadd r2,r1IFID··EXMEMWBsub r3IF··IDEXMEMWB·· = stall: loaded value ready only after MEMCPI = 1 + 0.25 loads × 0.4 used next × 1 = 1.1(3 instructions: 7 cycles ideal, 8 with the stall)
Figure 3.1. A load-use stall. Three instructions in a five-stage pipeline. A load is followed by an add that uses the loaded register; even with forwarding the add waits one bubble for MEM to finish, so 3 instructions take 8 cycles instead of 7. With 0.25 loads per instruction, 0.4 of them used next, CPI becomes 1.1.

Explanation

This chapter is built from 3 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

3.1 Pipelining: an assembly line for instructions

A laundry takes 30 minutes to wash, 40 to dry and 20 to fold. How long do four loads take if you never wait for one to finish before starting the next?

Throughput versus latency

Pipelining does not make one instruction faster: it still passes through every stage, and register overhead makes it slightly slower. What improves is throughput: once full, the pipeline completes one instruction every cycle. Ideal CPI approaches 1 for long runs.

The classic five stages

IF fetches the instruction, ID decodes it and reads registers, EX uses the ALU, MEM accesses data memory, WB writes the result back. Registers between stages hold each instruction's state so the stages can work on different instructions at once.

Balance and overhead

The clock must suit the slowest stage, and every stage boundary adds a register's setup and clock-to-output delay. Deeper pipelines get diminishing returns and, as you will see, pay more for every hazard. Modern designs settle on roughly 10–20 stages as a compromise.

Derivation: How much faster can a pipeline be?
  1. Unpipelined: each instruction takes T, so n instructions take n·T.

  2. Split into k stages. If perfectly balanced, each stage is T/k, but each needs a pipeline register adding overhead o. Cycle = T/k + o.

  3. Pipelined time for n instructions = (k + n − 1)(T/k + o).

  4. Speed-up S = n·T / ((k + n − 1)(T/k + o)). As n → ∞, S → T/(T/k + o) = k / (1 + k·o/T).

  5. With no overhead the limit is k. With o = 0.1 T, a 5-stage pipe tops out at 5/1.5 ≈ 3.3×; a 20-stage pipe at 20/3 ≈ 6.7×, not 20×.

  6. Unbalanced stages are worse: the cycle is set by the slowest stage, so S ≤ T / max(stage delay).

Common mix-ups

  • A k-stage pipeline makes the processor k times faster.
    ✓ Only with perfect balance, no overhead, no hazards and infinitely long programs. Real gains are smaller.
  • Pipelining makes each instruction finish sooner.
    ✓ It makes instructions finish more often. Each one still takes all k stages.

Open the full lesson: Pipelining: an assembly line for instructions →

3.2 Hazards, forwarding and branch prediction

An instruction needs a number the previous one hasn't finished computing. Does the whole assembly line stop?

Data hazards

A read-after-write hazard occurs when an instruction needs a register that an earlier, still-in-flight instruction will write. Without help, the reader stalls in ID until the writer reaches WB: 2 bubbles for adjacent instructions in the classic 5-stage pipe. Forwarding (bypassing) wires the ALU output straight back to the ALU input, removing the stall for ALU results.

The load-use stall

A load's data appears only at the end of MEM. Even with forwarding, an instruction that uses it immediately must wait one cycle. Compilers hide this by scheduling an independent instruction between the load and its use, which is why the 'Load then use' program in the pipeline diagram has an unrelated sub in the middle.

Control and structural hazards

A branch is not resolved until EX, so the pipeline has already fetched 2 instructions that may be wrong. Stalling on every branch wastes those cycles always; predict not taken wastes them only when the branch is taken; dynamic predictors learn each branch's habit and are right well over 90% of the time on typical code. A structural hazard arises when two stages need one resource, like a single memory port for fetch and data: hence separate instruction and data caches.

Hazards in the Iron Law

Every stall adds to CPI: CPI = 1 + (data stalls per instruction) + (branch fraction × mispredict rate × penalty) + (memory stalls). Deeper pipelines raise the branch penalty, so a faster clock can lose to a shorter pipe with a better predictor.

Common mix-ups

  • Forwarding removes all data hazards.
    ✓ It cannot help a load followed immediately by its use: the data does not exist yet.
  • Branch prediction is a guess, so it cannot be relied on.
    ✓ Wrong guesses are detected and flushed; prediction only affects speed, never correctness.

Open the full lesson: Hazards, forwarding and branch prediction →

3.3 Explaining results from first principles

Your 8-bit version runs 2.6× faster than float, but the arithmetic is only 2× cheaper. Where did the rest come from?

Explain the numbers

For each metric, give the mechanism and check the size: operation counts for compute, bytes and AMAT for memory, quantisation step for accuracy, P = αCV²f and duty cycle for energy. A mechanism that predicts the right size of effect is far stronger than one that only predicts its direction.

Results that resist explanation

If the model leaves a gap, report it as an open question rather than stretching the explanation. 'The model predicts 2.75× but we measured 3.4×; we suspect hardware prefetching, which our model omits' is honest and useful.

The final report

Question and prediction; method (as pre-registered, with any deviations); results with uncertainty; first-principles explanation; recommendation from the pre-stated rule; limitations: simulation versus hardware, one workload, one compiler, toy data. No claim beyond the evidence.

Derivation: Decomposing a speed-up
  1. T = IC × CPI × t_clk, with CPI = CPI_base + (memory accesses per instruction) × miss rate × miss penalty.

  2. Speed-up S = T_A/T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (t_A/t_B). Taking logs, ln S = ln(IC ratio) + ln(CPI ratio) + ln(clock ratio): each factor's share adds.

  3. Example: SIMD packing halves IC (ratio 2). Smaller data cuts the miss rate from 6% to 3% with 0.4 accesses per instruction and a 50-cycle penalty: CPI 1 + 1.2 = 2.2 → 1 + 0.6 = 1.6 (ratio 1.375). Clock unchanged.

  4. Predicted S = 2 × 1.375 = 2.75×. If you measured 2.6× ± 0.1, the model explains it within uncertainty; the shares are ln 2 / ln 2.75 ≈ 68% from IC and 32% from CPI.

  5. If the model and measurement disagree beyond uncertainty, something unmodelled matters (branch behaviour, prefetching, frequency scaling): say so and investigate.

Common mix-ups

  • A good result needs no explanation.
    ✓ Without a mechanism, you cannot predict whether it will hold on the next workload or chip.
  • If the model doesn't match, the experiment failed.
    ✓ A mismatch is information: it points to an effect your model left out.

Open the full lesson: Explaining results from first principles →

Worked examples

Pipelining: an assembly line for instructions: example 1

Stages of 200, 150, 250, 300 and 100 ps, register overhead 20 ps. Find the cycle time and the speed-up for many instructions versus the 1000 ps unpipelined design.

Solution

Cycle = slowest stage + overhead = 300 + 20 = 320 ps. Limit speed-up = 1000/320 ≈ 3.1×, well below 5× because the stages are unbalanced.

Hazards, forwarding and branch prediction: example 1

lw r1, 0(r2) then add r3, r1, r4, with forwarding. Stalls?

Solution

  1. The loaded value exists only after MEM; add's EX must come the cycle after lw's MEM, one cycle later than it would without the dependency.
Hazards, forwarding and branch prediction: example 2

Branches are 15% of instructions; a predictor is wrong 8% of the time; the penalty is 3 cycles. Extra CPI?

Solution

0.15 × 0.08 × 3 = 0.036. With base CPI 1, effective CPI 1.036.

Explaining results from first principles: example 1

Float: IC 10⁹, CPI 1.8, 1 GHz. Int8: IC 0.3×10⁹, CPI 2.1, 1 GHz. Speed-up and its sources?

Solution

T_f = 1.8 s, T_i = 0.63 s: S ≈ 2.86×. IC ratio 3.33 (ln 1.20) and CPI ratio 0.857 (ln −0.15): ln S = 1.05. Packing fewer, wider operations gained a lot; CPI got slightly worse (perhaps extra rescaling instructions or stalls) and gave some back.

Interactive figures

Figure 3.2 from Pipelining: an assembly line for instructionsChoose 'Independent ALU ops', turn forwarding on and choose 'Perfect predictor'. Read the diagonal staircase and check the cycle count against k + n − 1. Then pick the other programs to see the ideal break: that is next lesson's topic.
Can't use the interactive? Read a description instead

The pipeline table has one row per instruction and one column per clock cycle; each instruction's IF, ID, EX, MEM and WB cells shift one column to the right of the previous instruction's, forming a staircase. For 5 independent instructions it ends at cycle 9.

Interactive figure (online). Description: The pipeline table has one row per instruction and one column per clock cycle; each instruction's IF, ID, EX, MEM and WB cells shift one column to the right of the previous instruction's, forming a staircase. For 5 independent instructions it ends at cycle 9.

Figure 3.3 from Hazards, forwarding and branch predictionEvery stall cycle adds to CPI, and this calculator shows how much. Set branches to 20%, mispredict to 10% and penalty to 2: read the CPI. Raise the penalty to 15 (a deep pipeline) and watch the branch slice grow. Pin a design, then trade a faster clock for a bigger penalty and read the speed-up.
Can't use the interactive? Read a description instead

The Iron Law calculator shows CPI as base + branch stalls + memory stalls. With 20% branches, 10% mispredicted at 2 cycles, and 30% memory instructions missing 5% at 40 cycles, CPI = 1 + 0.04 + 0.6 = 1.64, and T = IC × CPI ÷ f.

Interactive figure (online). Description: The Iron Law calculator shows CPI as base + branch stalls + memory stalls. With 20% branches, 10% mispredicted at 2 cycles, and 30% memory instructions missing 5% at 40 cycles, CPI = 1 + 0.04 + 0.6 = 1.64, and T = IC × CPI ÷ f.

Laboratory

Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.

Guided practice

Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.

Practice 1

Compared with the unpipelined design, the latency of a single instruction in a pipeline is…

Practice 2

A 1,200 ps datapath is split into 6 perfectly balanced stages with 50 ps register overhead each. What is the speed-up limit for very long programs?

×

Practice 3

lw r5, 4(r2) / add r6, r5, r1. Which hazard and, with forwarding, how many stall cycles?

Practice 4

Design B doubles the pipeline depth of A, raising the clock 1.6× and the branch penalty from 2 to 5 cycles. Branch fraction 20%, mispredict 10%, base CPI 1 for both, memory ignored. Which is faster?

Practice 5

On the classic 5-stage pipeline with no forwarding, a chain of 4 ALU instructions each uses the previous one's result. How many total cycles? (Ideal is 8.)

cycles

Practice 6

Why do most processors have separate L1 instruction and data caches?

Practice 7

Version B executes 0.5× the instructions of A, and its CPI falls from 2.0 to 1.5. Same clock. What speed-up does the Iron Law predict?

×

Practice 8

Your model predicts 2.0× and you measured 2.9× ± 0.2. What should the report say?

  1. Compared with the unpipelined design, the latency of a single instruction in a pipeline is…
    • k times shorter
    • About the same or slightly longer
    • Always exactly one cycle
    • Zero once the pipeline is full
  2. A 1,200 ps datapath is split into 6 perfectly balanced stages with 50 ps register overhead each. What is the speed-up limit for very long programs? (×)
  3. lw r5, 4(r2) / add r6, r5, r1. Which hazard and, with forwarding, how many stall cycles?
    • Structural, 0
    • Data (load-use), 1
    • Control, 2
    • Data, 0 thanks to forwarding
  4. Design B doubles the pipeline depth of A, raising the clock 1.6× and the branch penalty from 2 to 5 cycles. Branch fraction 20%, mispredict 10%, base CPI 1 for both, memory ignored. Which is faster?
    • A
    • B
    • Equal
    • Cannot tell without IC
  5. On the classic 5-stage pipeline with no forwarding, a chain of 4 ALU instructions each uses the previous one's result. How many total cycles? (Ideal is 8.) (cycles)
  6. Why do most processors have separate L1 instruction and data caches?
    • To store more data
    • To remove the structural hazard of fetch and load/store needing memory in the same cycle
    • Because instructions are larger than data
    • To make branch prediction possible
  7. Version B executes 0.5× the instructions of A, and its CPI falls from 2.0 to 1.5. Same clock. What speed-up does the Iron Law predict? (×)
  8. Your model predicts 2.0× and you measured 2.9× ± 0.2. What should the report say?
    • Adjust the model until it gives 2.9×
    • The model explains part of the gain; the remaining gap is unexplained, with candidate causes and a test to check them
    • Drop the measurement
    • Claim the model is confirmed

Engineering applications

  • Instruction scheduling

    Compilers move independent instructions into the slot after a load so the pipeline has useful work while the value arrives. The program means the same but runs in fewer cycles.

  • Branch-heavy code

    Parsing and decision code branches unpredictably, so deeper pipelines lose more per mispredict. Predictable loops are why signal-processing code pipelines so well.

Watch

Optional verified videos. Nothing loads from YouTube until you press play.

Explains instruction pipelining and why hazards force the CPU to wait.

21 min 48 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

Covers caches, pipelining, branch prediction and multiple cores: the tricks that make processors fast, in one sitting.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • CPU Pipeline - Computerphile (Computerphile)
  • Advanced CPU Designs: Crash Course Computer Science #9 (CrashCourse)

Chapter summary

  • Ideal pipelining divides the cycle time by the number of stages; latency per instruction does not improve.
  • Hazards add stall cycles: CPI = 1 + Σ (frequency × penalty) over every hazard type.
  • Forwarding removes most data stalls; a load followed immediately by its use still costs a bubble.
  • Deeper pipelines raise the clock but also the branch penalty; the Iron Law decides the net effect.

Glossary

Pipelining
Pipelining splits instruction execution into stages and overlaps them, so that while one instruction executes the next is being decoded and the one after is being fetched.
Pipeline hazards and forwarding
A hazard is a situation where the next instruction cannot proceed on schedule. Data hazards happen when an instruction needs a result an earlier one has not finished producing.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.

Definitions from the Field Guide.

Project: Explain a speed-up

Using the pipeline simulation, measure CPI for a program mix with and without forwarding. Predict the speed-up from a stall model before running, then compare. Where they disagree by more than 10 %, find the cause.

Deliverables

  • The stall model with its assumptions
  • Predicted and measured CPI with a comparison
  • An explanation of any mismatch

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • John L. Hennessy and David A. Patterson (2017). Computer Architecture: A Quantitative Approach, 6th edition. Morgan Kaufmann.
  • David A. Patterson and John L. Hennessy (2017). Computer Organization and Design RISC-V Edition: The Hardware Software Interface. Morgan Kaufmann.

Publication record

Version
1
Status
Technically checked (automated checks only)
Technical review
Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
Written by
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
Licence
All rights reserved by the founders unless a licence is approved.
Corrections
None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.