---
title: "Pipelining the core: hazards and forwarding"
heading: The five-stage RISC-V pipeline, data and control hazards, forwarding and stalls
eyebrow: S3 · Lesson 42 · Pipelining the core
xp: 50
---

::: hook
Cut the single-cycle core into five stages (fetch, decode, execute, memory, write-back) with registers between them, and five instructions are in flight at once. The clock period drops to the slowest stage, and ideally one instruction finishes every cycle. Instructions depend on each other, though: an add that needs the result of the instruction just ahead would read a stale register, and a branch isn't decided until fetch has already moved on. Forwarding paths, a hazard unit that stalls when it must, and flushing on mispredicted branches keep the pipeline correct, and the cycles they cost decide how close the CPI gets to 1.
:::

::: play
- CPI of a five-stage pipeline against the branch misprediction rate. Solid: with forwarding, the only data stalls are loads followed at once by a use. Dashed: without forwarding, an instruction that uses the result of the one just before stalls 2 cycles, and of the one two before, 1 cycle.
- L is the fraction of instructions that are loads, u the fraction of loads used by the next instruction, B the fraction that are branches and P the misprediction penalty. d1 and d2 are the fractions of instructions that depend on the instruction one or two ahead.
- Forwarding removes most of the data stalls. Branches remain: a deeper pipeline raises P, which is why prediction matters more as pipelines get longer.
:::
:::

```sim plot
view: graph
x: m = 0..0.6
y: C = 1..3
slider: L = 0.1..0.35 = 0.25
slider: u = 0..1 = 0.4
slider: B = 0.05..0.3 = 0.15
slider: P = 1..10 step 1 = 2
slider: d1 = 0..0.5 = 0.3
slider: d2 = 0..0.3 = 0.15
plot: 1 + L*u + B*m*P | label: CPI with forwarding
plot: 1 + 2*d1 + d2 + B*m*P | dashed | color: ch2 | label: CPI without forwarding
readout: load-use stalls per instruction = L*u
readout: data stalls per instruction without forwarding = 2*d1 + d2
```

::: predict
## In a five-stage pipeline with full forwarding, `lw t1, 0(t0)` is followed immediately by `add t2, t1, t3`. How many cycles does the add stall?

- [ ] 0: forwarding handles it
- [x] 1
- [ ] 2
- [ ] 3

::: reveal
One. The load's data comes out of the memory stage at the end of its fourth cycle, but the add needs it at the start of its own execute stage, which would be that same cycle. Forwarding can send the value from the MEM/WB register into execute one cycle later, so the hazard unit holds the add in decode for one cycle (a bubble). Compilers schedule an independent instruction into that slot when they can.
:::
:::

::: nameit
## The five stages

| Stage | Work | Pipeline register after it |
|---|---|---|
| IF | fetch from instruction memory, PC + 4 | IF/ID |
| ID | decode, read registers, generate immediate | ID/EX |
| EX | ALU, branch compare and target | EX/MEM |
| MEM | data memory | MEM/WB |
| WB | write the register file | |

With no stalls, N instructions take $k + N - 1$ cycles in a k-stage pipeline. The register file writes in the first half of a cycle and reads in the second, so WB and ID in the same cycle don't conflict.

## Data hazards

A read-after-write (RAW) hazard: an instruction reads a register an earlier instruction hasn't written yet.

- **Forwarding (bypassing):** multiplexers at the ALU inputs take the value from EX/MEM (the instruction one ahead) or MEM/WB (two ahead) when its destination matches the source register (and isn't x0).
- **Load-use stall:** a load's value exists only after MEM, so an immediately following use stalls one cycle. The hazard unit freezes PC and IF/ID and inserts a bubble into ID/EX.
- Without forwarding, a dependence at distance 1 costs 2 stalls and at distance 2 costs 1.

## Control hazards

A branch resolved in EX has fetched two more instructions by then. Predicting not taken and flushing them when wrong costs 2 cycles per misprediction; resolving in ID costs 1. In general the penalty is the number of stages fetched past before the branch resolves.

$$\text{CPI} = 1 + f_\text{load}u + f_\text{branch}mP$$

Speedup over the single-cycle core is $\frac{T_\text{single}}{\text{CPI} \cdot T_\text{pipe}}$.
:::

::: example
## A program has 25% loads (40% of them used at once by the next instruction) and 15% branches (30% mispredicted, 2-cycle penalty). What's the CPI, and how much faster is the pipeline at 320 ps than the 945 ps single-cycle core?

::: solution
1. **CPI.**
   $$\begin{aligned} \text{CPI} &= 1 + 0.25 \times 0.4 \\ &\quad + 0.15 \times 0.3 \times 2 \\ &= 1.19 \end{aligned}$$
2. **Time per instruction.**
   $$1.19 \times 320 = 381\ \text{ps}$$
   against 945 ps, 2.48 times faster.
3. **Without forwarding.** If 30% of instructions depend on the one before and 15% on the one two before:
   $$\begin{aligned} \text{CPI} &= 1 + 0.6 + 0.15 + 0.09 \\ &= 1.84 \end{aligned}$$
   and the speedup is only 1.6.

**Answer:** a CPI of 1.19, which makes the pipeline 2.48 times faster than the single-cycle core.
:::
:::

::: example
## How many cycles does this sequence take on the five-stage pipeline with forwarding, branch predicted not taken and resolved in EX: `lw t1, 0(t0)`, `add t2, t1, t1`, `beq t2, zero, L` (taken), then the target instruction, which is the last?

::: solution
1. **No hazards.** Four instructions would take
   $$5 + 4 - 1 = 8\ \text{cycles}$$
2. **Load-use stall.** The add stalls 1 cycle after the load.
3. **The branch's operand.** The add's result is forwarded to the branch with no stall.
4. **The taken branch.** It flushes the 2 instructions fetched after it.
5. **Total.**
   $$8 + 1 + 2 = 11\ \text{cycles}$$

**Answer:** 11 cycles.
:::
:::

::: example
## A six-instruction loop runs 1000 times on the five-stage pipeline. Each iteration has one load-use stall and ends in a taken branch, predicted not taken and resolved in EX. How many cycles does it take, and what's the CPI?

::: solution
1. **One iteration.** 6 cycles plus 1 stall plus a 2-cycle flush:
   $$6 + 1 + 2 = 9\ \text{cycles}$$
2. **The whole loop.** Over 1000 iterations that's 9000, plus 4 to fill the pipeline at the start:
   $$9000 + 4 = 9004\ \text{cycles}$$
3. **CPI.**
   $$\frac{9004}{6000} = 1.50$$
4. **Improving it.** Moving an independent instruction between the load and its use, and predicting the backward branch taken, would bring it near 1.0.

**Answer:** 9004 cycles, a CPI of 1.50.
:::
:::

::: check
given: k = 5 | 7 | 12; N = 10 | 100 | 1000
answer: k + N - 1
tolerance: 0

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

::: right
Right. $k + N - 1$ = {answer}: k to fill, then one per cycle.
:::

::: misses
- [k*N] The instructions overlap.
- [N] The first one still takes k cycles.
- [any] Not yet. Fill the pipeline, then one finishes per cycle.
:::
:::

::: check
given: L = 0.2 | 0.3; u = 0.3 | 0.5; B = 0.1 | 0.2; m = 0.05 | 0.2; P = 2 | 3
answer: 1 + L*u + B*m*P
tolerance: 0.5%

## A pipeline with forwarding runs code with {L} loads ({u} of them used at once), {B} branches, a {m} misprediction rate and a {P}-cycle penalty. What's the CPI?

::: right
Right. $1 + f_Lu + f_BmP$ = {answer}.
:::

::: misses
- [1 + L*u + B*P] Only mispredicted branches pay the penalty.
- [1 + L + B*m*P] Only loads followed at once by a use stall.
- [any] Not yet. Add the stall cycles per instruction to 1.
:::
:::

::: check
given: d = 0.2 | 0.35; e = 0.1 | 0.2
answer: 1 + 2*d + e
tolerance: 0.5%

## Without forwarding, {d} of instructions depend on the one just before and {e} on the one two before. Ignoring branches, what's the CPI?

::: right
Right. 2 stalls at distance 1, 1 at distance 2: {answer}.
:::

::: misses
- [1 + d + e] A distance-1 dependence waits until the value is written back: 2 stalls.
- [any] Not yet. Count the stalls each dependence costs.
:::
:::

::: check
given: S = 800 | 1000; T = 250 | 300; C = 1.15 | 1.4
answer: S/(C*T)
tolerance: 0.5%

## A single-cycle core runs at {S} ps per instruction; its pipelined version has a {T} ps clock and a CPI of {C}. What's the speedup?

::: right
Right. $\frac{T_\text{single}}{\text{CPI} \cdot T_\text{pipe}}$ = {answer}.
:::

::: misses
- [S/T] Include the stalls.
- [any] Not yet. Compare time per instruction.
:::
:::

::: check
given: N = 20 | 50; n = 2 | 5; b = 1 | 3; P = 2 | 3
answer: 5 + N - 1 + n + P*b
tolerance: 0

## A five-stage pipeline runs {N} instructions with {n} load-use stalls and {b} mispredicted branches at a {P}-cycle penalty. How many cycles in all?

::: right
Right. $(5 + N - 1) + n + Pb$ = {answer}.
:::

::: misses
- [N + n + P*b] Count the cycles to fill the pipeline.
- [any] Not yet. The ideal count plus every stall.
:::
:::

::: check
given: s = 2 | 3 | 4 | 7
answer: s - 1
tolerance: 0

## A pipeline predicts branches not taken and resolves them in stage {s} (fetch is stage 1). How many cycles does a misprediction cost?

::: right
Right. {answer}: the instructions fetched after the branch before it resolved are flushed.
:::

::: misses
- [s] Fetch of the branch itself isn't wasted.
- [any] Not yet. Count the stages behind it.
:::
:::

::: check
kind: parts
given: l = 0.2 | 0.3; u = 0.3 | 0.5; b = 0.1 | 0.2; m = 0.1 | 0.3; P = 1 | 2 | 3; S = 900 | 1000; p = 250 | 300

## A program has {l} loads ({u} of them used by the next instruction) and {b} branches ({m} of them mispredicted, {P} cycles each). The pipeline runs at {p} ps; the single-cycle core it replaces ran at {S} ps.

::: part
answer: 1 + l*u + b*m*P
tolerance: 0.5%

### What is the pipeline's CPI?

::: misses
- [any] $1 + f_\text{load}u + f_\text{branch}mP$.
:::
:::

::: part
answer: S/((1 + l*u + b*m*P)*p)
tolerance: 0.5%

### How much faster is it than the single-cycle core?

::: misses
- [S/p] Include the CPI.
- [any] $T_\text{single}/(\text{CPI}\cdot T_\text{pipe})$.
:::
:::
:::

::: check
kind: derivation
vars: k = 2..20, N = 1..1e6

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

::: step
answer: k + N - 1

### How many cycles does it take?
:::

::: step
answer: N*k/(k + N - 1)

### How much faster is it than an unpipelined core whose cycle is k stages long?
:::

::: right
Right. For long programs the speedup approaches k; filling the pipeline only matters for short ones.
:::
:::

::: explain
## Why can forwarding remove the stall between an add and an instruction that uses its result, but not between a load and an instruction that uses its value?

::: model
An add's result is computed at the end of its execute stage, and the next instruction needs it at the start of its own execute stage, one cycle later. The value already exists by then, sitting in the EX/MEM pipeline register, so a forwarding multiplexer can route it straight into the ALU input without waiting for write-back. A load's value isn't known until the end of its memory stage, which is the same cycle the following instruction would be executing. No wire can deliver a value before it exists, so the hazard unit has to delay the dependent instruction by one cycle, after which the loaded value can be forwarded from MEM/WB.
:::
:::

::: practice

::: check
given: k = 4 | 9; N = 30 | 500
answer: k + N - 1
tolerance: 0

## Cycles for {N} instructions on {k} stages, no stalls?

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

::: check
given: L = 0.15 | 0.35; u = 0.2 | 0.6; B = 0.12 | 0.25; m = 0.1 | 0.3; P = 2 | 4
answer: 1 + L*u + B*m*P
tolerance: 0.5%

## CPI: {L} loads, {u} used at once, {B} branches, {m} mispredicted, {P}-cycle penalty?

::: misses
- [any] $1 + f_Lu + f_BmP$.
:::
:::

::: check
given: S = 900 | 1200; T = 220 | 280; C = 1.1 | 1.6
answer: S/(C*T)
tolerance: 0.5%

## Speedup: {S} ps single cycle, {T} ps pipeline, CPI {C}?

::: misses
- [any] $T_s/(\text{CPI}\,T_p)$.
:::
:::
:::
