---
title: Pipelining and hazards
heading: Five instructions in flight, and what gets in their way
eyebrow: C8 · Lesson 40 · Pipelining and hazards
xp: 40
---

::: hook
A single-cycle processor leaves most of its hardware idle: while the data memory serves a load, the instruction memory, the register file and the ALU have nothing to do. Pipelining puts registers between the stages so that each stage works on a different instruction, like a laundry where the washer starts the next load while the dryer runs. Five instructions are in progress at once and the clock can run several times faster. The catch is that instructions depend on each other: one needs a result another hasn't finished, or a branch changes which instructions should have been started. Those **hazards** decide how close a real pipeline gets to its ideal.
:::

::: play
- A processor's 1000 ps of logic is split into k equal stages, each followed by a pipeline register that costs r ps. Each extra stage also adds stall cycles from hazards, at the rate h per instruction per stage.
- The curve is the time per instruction, the cycle time times the CPI. Drag k up from 1: it falls fast at first, then flattens, then rises as register overhead and stalls take over.
- Set h to 0: deeper is always better, though with diminishing returns. Raise h and the best depth moves down.
:::
:::

```sim plot
view: graph
x: k = 1..30
y: t = 0..1100 ps
slider: r = 10..100 step 5 = 50
slider: h = 0..0.3 step 0.01 = 0.15
plot: (1000/k + r)*(1 + h*(k - 1)) | label: time per instruction
readout: best depth = sqrt(1000*(1 - h)/(r*(h + 0.000001))) | digits: 3
readout: single-cycle time, ps = 1000 + r | digits: 4
readout: time at 5 stages, ps = (200 + r)*(1 + 4*h) | digits: 4
```

::: predict
## A five-stage pipeline with no stalls runs 1000 instructions. How many clock cycles does it take?

- [ ] 1000
- [x] 1004
- [ ] 1005
- [ ] 5000

::: reveal
1004. The first instruction takes 5 cycles to come out of the pipeline, and after that one finishes every cycle: 5 + 999. For long programs that's a CPI very close to 1, at a clock about five times faster than single-cycle.
:::
:::

::: nameit
## Five stages

**Fetch** (read the instruction), **Decode** (read registers, build the immediate), **Execute** (ALU), **Memory** (load or store), **Writeback** (write the register file). Each instruction moves one stage per cycle:

| Cycle | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| `lw t0, 0(a0)` | F | D | E | M | W | | |
| `add t1, t2, t3` | | F | D | E | M | W | |
| `sub t4, t5, t6` | | | F | D | E | M | W |

The clock period is set by the slowest stage plus the pipeline register's overhead, $T_c = \max(t_\text{stage}) + t_{pcq} + t_\text{setup}$. N instructions in a k-stage pipeline with no stalls take $k + N - 1$ cycles.

## Hazards

- **Data hazards.** `add t0, ...` followed by `sub t1, t0, ...`: the sub reads t0 in Decode before the add has written it. **Forwarding** sends the ALU result straight from the pipeline register back to the ALU's input, so no time is lost. A **load-use** hazard is worse: a loaded value isn't ready until the end of Memory, so an instruction that uses it immediately must **stall** one cycle even with forwarding. Compilers schedule an independent instruction into that slot when they can.
- **Control hazards.** A branch is decided in Execute, by which time two more instructions have been fetched. If the processor predicted "not taken" and the branch is taken, those two are **flushed**: a 2-cycle penalty.
- **Structural hazards.** Two stages needing one resource at once, such as fetching an instruction and loading data from a single memory. Separate instruction and data caches avoid it.

## CPI with stalls

$$\text{CPI} = 1 + F_\text{load-use} \cdot 1 + F_\text{branch} \cdot F_\text{mispredicted} \cdot 2$$

with each F the fraction of instructions (or of branches) involved.
:::

::: example
## A design's five stages take 200, 150, 120, 200 and 80 ps, and each pipeline register adds 40 ps. Compare it with the single-cycle version on a billion instructions at a CPI of 1.15.

::: solution
1. **Single-cycle.** 750 ps a cycle at a CPI of 1: 0.75 s.
2. **The pipelined clock.** The slowest stage plus a register:
   $$\begin{aligned} T_c &= 200 + 40 \\ &= 240\ \text{ps} \end{aligned}$$
3. **The pipelined time.**
   $$\begin{aligned} t &= 10^9 \times 1.15 \times 240\ \text{ps} \\ &= 0.276\ \text{s} \end{aligned}$$
   2.7 times faster.
4. **Why less than 5.** The stages aren't equal, the registers cost time, and stalls raise the CPI.

**Answer:** 0.276 s pipelined against 0.75 s single-cycle, 2.7 times faster.
:::
:::

::: example
## 25% of instructions are loads, and 40% of loads are followed at once by an instruction that uses the value. 15% are branches, half of them taken, predicted not taken with a 2-cycle penalty. What is the CPI?

::: solution
1. **Load-use stalls.**
   $$0.25 \times 0.4 \times 1 = 0.10$$
2. **Branch penalties.**
   $$0.15 \times 0.5 \times 2 = 0.15$$
3. **Add them to the base CPI.**
   $$\begin{aligned} \text{CPI} &= 1 + 0.10 + 0.15 \\ &= 1.25 \end{aligned}$$

**Answer:** a CPI of 1.25.
:::
:::

::: example
## Without forwarding, an instruction that uses the result of the one just before it waits 2 cycles, and 30% of instructions do. With forwarding, only loads stall, 1 cycle, and 25% of instructions are loads of which 40% are used at once. Compare the CPIs.

::: solution
1. **Without forwarding.**
   $$\begin{aligned} \text{CPI} &= 1 + 0.3 \times 2 \\ &= 1.6 \end{aligned}$$
2. **With forwarding.**
   $$\begin{aligned} \text{CPI} &= 1 + 0.25 \times 0.4 \times 1 \\ &= 1.1 \end{aligned}$$
3. **Compare.** A handful of multiplexers and wires make the processor 45% faster.
4. **The stall that remains.** A load's data comes out of the memory stage, too late for the next instruction's execute stage; compilers hide it by scheduling an independent instruction into the gap.

**Answer:** a CPI of 1.6 without forwarding and 1.1 with it, 45% faster.
:::
:::

::: check
kind: parts
given: k = 4 | 5 | 8; N = 100 | 1000 | 20

## A {k}-stage pipeline with no stalls runs {N} instructions.

::: part
answer: k + N - 1
unit: cycles
tolerance: 0

### How many cycles does it take?

::: misses
- [N] The first instruction needs {k} cycles to get through.
- [k*N] The instructions overlap.
- [any] Not yet. k + N − 1.
:::
:::

::: part
answer: N/(k + N - 1)
tolerance: 0.5%

### How many instructions finish per cycle, on average?

::: misses
- [any] Instructions over cycles.
:::
:::
:::

::: check
kind: parts
given: a = 150 | 220; b = 180 | 250; c = 120 | 200; o = 30 | 50

## A pipeline's slowest three stages take {a}, {b} and {c} ps (the others less), and each pipeline register adds {o} ps.

::: part
answer: (a + b + abs(a - b))/2 + (c - (a + b + abs(a - b))/2 + abs(c - (a + b + abs(a - b))/2))/2 + o
unit: ps
tolerance: 0.5%

### What is the clock period?

::: misses
- [a + b + c + o] Each stage gets the whole cycle; the period is set by the slowest one, not the sum.
- [any] Not yet. The slowest stage plus the register overhead.
:::
:::

::: part
answer: 1e6/((a + b + abs(a - b))/2 + (c - (a + b + abs(a - b))/2 + abs(c - (a + b + abs(a - b))/2))/2 + o)
unit: MHz
tolerance: 0.5%

### What is the clock frequency?

::: misses
- [any] One over the period.
:::
:::
:::

::: check
kind: parts
given: L = 0.2 | 0.3; u = 0.3 | 0.5; B = 0.1 | 0.2; m = 0.3 | 0.6; p = 2 | 3

## {L} of a program's instructions are loads, {u} of which are used immediately; {B} are branches, {m} of which are mispredicted at a {p}-cycle penalty.

::: part
answer: 1 + L*u + B*m*p
tolerance: 0.5%

### What is the CPI?

::: misses
- [1 + L + B*p] Only loads used at once stall, and only mispredicted branches pay.
- [any] Not yet. 1 + load-use stalls + misprediction cycles.
:::
:::

::: part
answer: B*m*p/(1 + L*u + B*m*p)*100
unit: %
tolerance: 0.5%

### What percentage of the cycles are lost to mispredictions?

::: misses
- [any] Misprediction cycles over all cycles.
:::
:::
:::

::: check
kind: parts
given: T = 800 | 1200; r = 30 | 60; k = 4 | 6 | 10

## A processor's {T} ps of logic is split into {k} equal stages, each with a {r} ps register, and there are no stalls.

::: part
answer: T/k + r
unit: ps
tolerance: 0.5%

### What is the cycle time?

::: misses
- [T/k] Add the register overhead.
- [any] Not yet. T/k + r.
:::
:::

::: part
answer: (T + r)/(T/k + r)
tolerance: 0.5%

### How many times the single-cycle throughput (with one register) is that?

::: misses
- [k] The register overhead keeps it below k.
- [any] Not yet. (T + r)/(T/k + r).
:::
:::
:::

::: check
kind: choice

## Which pair stalls a five-stage pipeline for a cycle even with full forwarding?

- [ ] `add t0, t1, t2` then `sub t3, t0, t4`
- [x] `lw t0, 0(a0)` then `add t3, t0, t4`
- [ ] `lw t0, 0(a0)` then `add t3, t1, t4`
- [ ] `sw t0, 0(a0)` then `add t3, t0, t4`

::: misses
- [1] The add's result can be forwarded straight to the sub's Execute stage.
- [3] The add doesn't use t0.
- [4] A store writes memory, not t0; t0 was already available.
:::
:::

::: check
kind: order

## Put the five pipeline stages in order.

1. Fetch the instruction
2. Decode it and read registers
3. Execute in the ALU
4. Access data memory
5. Write the result back to the register file

::: right
Right. Each takes one cycle, and each holds a different instruction.
:::
:::

::: check
kind: parts
given: d = 20 | 30 | 40; l = 20 | 25; u = 30 | 50

## Without forwarding, {d}% of instructions wait 2 cycles for the one before. With forwarding only load-use pairs stall 1 cycle: {l}% loads, {u}% of them used at once.

::: part
answer: 1 + 2*d/100
tolerance: 0.5%

### What's the CPI without forwarding?

::: misses
- [any] $1 + 2d$.
:::
:::

::: part
answer: 1 + l/100*u/100
tolerance: 0.5%

### And with it?

::: misses
- [any] $1 + lu$.
:::
:::
:::

::: check
kind: derivation
vars: k = 2..20, T = 100..2000, o = 5..100

## A single-cycle design's T picoseconds of logic is split evenly into k stages, each with o of register overhead.

::: step
answer: T/k + o

### What's the pipelined clock period?
:::

::: step
answer: T/(T/k + o)

### What's the speedup at a CPI of 1, against a single-cycle clock of T?
:::

::: step
answer: T/o

### What does the speedup approach for very many stages?
:::

::: right
Right. Register overhead caps the gain from deeper pipelines.
:::
:::

::: explain
## Why does a load followed immediately by an instruction using its result cost a stall, even with forwarding?

::: model
Forwarding can only pass along a value that already exists. An ALU result exists at the end of the Execute stage, just in time for the next instruction's Execute in the following cycle. A load's value doesn't exist until the end of the Memory stage, one stage later, but the next instruction wants it at the start of its Execute stage, which is the same cycle as the load's Memory stage. There's no way to forward backward in time, so the dependent instruction has to wait one cycle, and a bubble goes down the pipeline in its place. If the compiler can put an independent instruction between them, the bubble disappears.
:::
:::

::: practice

::: check
given: k = 5 | 7; N = 10 | 500
answer: k + N - 1
unit: cycles
tolerance: 0

## How many cycles do {N} instructions take in a {k}-stage pipeline with no stalls?

::: misses
- [any] k + N − 1.
:::
:::

::: check
given: s = 180 | 260; o = 25 | 45
answer: s + o
unit: ps
tolerance: 0.5%

## The slowest stage takes {s} ps and the pipeline register adds {o} ps. What is the cycle time?

::: misses
- [any] Slowest stage plus overhead.
:::
:::

::: check
given: L = 0.15 | 0.25; u = 0.4 | 0.6; B = 0.12 | 0.2; m = 0.5 | 1
answer: 1 + L*u + B*m*2
tolerance: 0.5%

## Loads {L} (used at once {u} of the time), branches {B} (taken {m} of the time, predicted not taken, 2-cycle penalty): what is the CPI?

::: misses
- [any] 1 + L·u + B·m·2.
:::
:::
:::
