CPU Pipelining (COA Core #3)
A pipeline overlaps instructions so that five stages work on five instructions at once. The throughput becomes one instruction per cycle instead of one per five, but only if the next instruction does not need a result that is still being computed. Hazards are everything that breaks that overlap.
Pipeline stages
The classic five-stage RISC pipeline:
| Stage | What it does |
|---|---|
| IF | fetch the instruction at PC |
| ID | decode, read registers |
| EX | ALU operation or address calculation |
| MEM | load or store data |
| WB | write the result back to a register |
Pipeline registers between stages (IF/ID, ID/EX, EX/MEM, MEM/WB) hold the intermediate results for each instruction in flight.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=1.0cm, minimum height=0.45cm, font=\tiny\bfseries}]
\foreach \i/\j/\st in {
0/0/IF, 0/1/ID, 0/2/EX, 0/3/MEM, 0/4/WB,
1/1/IF, 1/2/ID, 1/3/EX, 1/4/MEM, 1/5/WB,
2/2/IF, 2/3/ID, 2/4/EX, 2/5/MEM, 2/6/WB,
3/3/IF, 3/4/ID, 3/5/EX, 3/6/MEM, 3/7/WB,
4/4/IF, 4/5/ID, 4/6/EX, 4/7/MEM, 4/8/WB}
\node[c, fill=blue!12] at (\j*1.05,-\i*0.55) {\st};
\node[font=\scriptsize, anchor=east] at (-0.65,0) {I1};
\node[font=\scriptsize, anchor=east] at (-0.65,-0.55) {I2};
\node[font=\scriptsize, anchor=east] at (-0.65,-1.1) {I3};
\node[font=\scriptsize, anchor=east] at (-0.65,-1.65) {I4};
\node[font=\scriptsize, anchor=east] at (-0.65,-2.2) {I5};
\node[font=\scriptsize, anchor=north] at (3.6,-2.85) {one instruction completes per cycle after the pipeline fills};
\end{tikzpicture}
Five instructions take 9 cycles instead of 25. The first four cycles are the fill, and the last four are the drain; steady state is one per cycle.
ASolution
No. Deeper pipelines raise the clock but also increase the misprediction and hazard penalties, because more in-flight work must be flushed. Pentium 4’s deep pipeline lost to shorter, wider designs.
Latency, throughput, and ideal speedup
- Latency: time from starting one instruction to finishing it. Pipelining does not reduce it; each instruction still takes \(k\) cycles.
- Throughput: instructions completed per cycle. This is what improves.
For \(n\) instructions and \(k\) stages with one cycle per stage:
\[ T_{\text{pipelined}} = (k + n - 1)\,T_{\text{cycle}} \]
Against an unpipelined machine that takes \(k\) cycles per instruction:
\[ \text{speedup} = \frac{n k T}{(k + n - 1)T} = \frac{nk}{k+n-1} \;\xrightarrow[n \to \infty]{}\; k \]
Example: \(k = 5\), \(n = 100\) → 104 cycles versus 500, speedup 4.81. The ideal 5× is approached only for long instruction streams.
ASolution
The fill and drain cycles do no useful work. Their fraction is \((k-1)/(k+n-1)\), which shrinks as \(n\) grows.
Structural hazards
A structural hazard is a resource conflict: two instructions need the same hardware in the same cycle.
- A single memory used for both instruction fetch and data access (IF and MEM collide).
- A register file with one write port when two instructions want to write.
- One ALU when both an integer operation and an address calculation need it.
The classic fix is to duplicate the resource: separate L1 instruction and data caches, multi-ported register files, more ALUs. When duplication is too expensive, the pipeline stalls one instruction for a cycle.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.9cm, minimum height=0.45cm, font=\tiny\bfseries}]
\node[c, fill=blue!15] at (0,0) {IF};
\node[c, fill=blue!15] at (1.0,0) {ID};
\node[c, fill=blue!15] at (2.0,0) {EX};
\node[c, fill=red!25] at (3.0,0) {MEM};
\node[c, fill=gray!15] at (4.0,0) {WB};
\node[c, fill=blue!15] at (1.0,-0.55) {IF};
\node[c, fill=gray!25] at (2.0,-0.55) {stall};
\node[c, fill=gray!25] at (3.0,-0.55) {stall};
\node[font=\scriptsize, anchor=west] at (4.6,-0.28) {memory port conflict};
\end{tikzpicture}
ASolution
To remove the structural hazard between fetch and memory access. A unified L1 would force one of them to stall every cycle a load/store executes.
Data hazards
A data hazard exists when an instruction needs a value that another instruction has not finished producing. The three dependency types:
| Type | Name | Example | Real dependency? |
|---|---|---|---|
| RAW | read after write (true) | add r1,... ; sub ...,r1 |
yes |
| WAR | write after read (anti) | sub ...,r1 ; add r1,... |
no, only with out-of-order |
| WAW | write after write (output) | add r1,... ; sub r1,... |
no, only with out-of-order |
RAW is the one that matters in an in-order pipeline: the consumer must wait for the producer’s value. WAR and WAW are false dependencies; in-order pipelines write in program order, so they cannot occur. Out-of-order cores use register renaming to remove them.
add r1, r2, r3 ; produces r1 in EX
sub r4, r1, r5 ; needs r1 in EX one cycle later
and r6, r1, r7 ; needs r1 one cycle after that
Without help, sub would read the old r1. With forwarding, it reads the value
directly from the pipeline register.
ASolution
They exist only because the same register name is reused. Different physical registers would remove them entirely, which is what renaming does.
Forwarding and bypassing
Forwarding sends a result from where it is produced to where it is needed, without waiting for the writeback.
Paths in the five-stage pipeline:
- EX/MEM → EX: ALU result forwarded to the next instruction’s ALU input.
- MEM/WB → EX: memory result forwarded one cycle later.
- MEM/WB → ID: for a value read in the same cycle it is written (write-first register file also handles this).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=1.35cm, minimum height=0.6cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=blue!12] (ex1) at (0,0.8) {EX: add};
\node[b, fill=blue!12] (mem1) at (2.0,0.8) {MEM};
\node[b, fill=orange!18] (ex2) at (2.0,-0.3) {EX: sub};
\draw[a, red!65] (ex1.east) -- (mem1.west);
\draw[a, red!65, dashed] (1.0,0.5) -- (1.0,-0.55) -- (ex2.north);
\node[font=\scriptsize, anchor=west, text=red!65] at (2.6,0.35) {forward result};
\end{tikzpicture}
Forwarding removes most stalls but not all. The load-use hazard is the exception:
lw r1, 0(r2) ; data available only after MEM
add r3, r1, r4 ; needs r1 at the start of EX
The load’s data arrives at the end of MEM, while the consumer needs it at the start of EX — the same cycle. Forwarding cannot go backwards in time, so one stall cycle is required. Without forwarding, the same pair needs two stalls.
| Producer → consumer | Stalls with forwarding | Stalls without |
|---|---|---|
| ALU → ALU | 0 | 2 |
| ALU → store data | 0 | 1 |
| load → ALU | 1 | 2 |
| load → store data | 1 | 2 |
cannot?
ASolution
The ALU result exists at the end of EX, in time for the next instruction’s EX. A load’s result exists only after MEM, which is one cycle too late for a consumer that needs it in EX.
Control hazards
A branch changes the PC, but the pipeline fetches ahead before the branch is resolved. If the branch is taken, the incorrectly fetched instructions must be flushed.
The penalty is the number of cycles between fetching the branch and knowing the next PC:
- Branch resolved in ID: 1 cycle of wrong-path fetch.
- Resolved in EX: 2 cycles.
- Deep out-of-order cores: 10–20 cycles, because many instructions are in flight.
Fixes:
- Resolve early: move branch comparison into ID.
- Delay slots: execute the instruction after the branch regardless (MIPS); the compiler fills the slot.
- Predict: guess the direction and keep fetching; flush only on a miss.
ASolution
Fewer wrong-path instructions have been fetched by the time the correct PC is known, so less work is flushed.
Branch prediction
Prediction guesses the next PC so fetch continues:
- Static: always not taken, always taken, or backward-taken/forward-not-taken (loops are taken, if-branches usually not). No hardware state.
- 1-bit dynamic: remember the last outcome.
- 2-bit saturating counter: needs two consecutive surprises to change its mind, which handles loop exits better.
- BTB (branch target buffer): caches the target address, so a taken branch has no gap.
- Correlated / TAGE: uses global history of recent branches; modern predictors reach 95–99% accuracy on typical code.
A 2-bit counter has four states: strongly taken, weakly taken, weakly not taken, strongly not taken. Taken increments (saturating at strongly taken), not-taken decrements.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, circle, minimum size=0.95cm, font=\tiny, align=center},
a/.style={->, thick}]
\node[b, fill=green!25] (st) at (0,0) {strong\\taken};
\node[b, fill=green!12] (wt) at (2.2,0) {weak\\taken};
\node[b, fill=red!10] (wn) at (4.4,0) {weak\\not};
\node[b, fill=red!25] (sn) at (6.6,0) {strong\\not};
\draw[a] (st) to[bend left=20] node[above, font=\tiny] {T} (wt);
\draw[a] (wt) to[bend left=20] node[above, font=\tiny] {N} (st);
\draw[a] (wt) -- node[above, font=\tiny] {T} (wn);
\draw[a] (wn) -- node[above, font=\tiny] {N} (sn);
\draw[a] (sn) to[bend left=20] node[below, font=\tiny] {N} (wn);
\draw[a] (wn) to[bend left=20] node[below, font=\tiny] {T} (wt);
\end{tikzpicture}
ASolution
A loop branch is taken many times and then not taken once at exit. A 1-bit predictor mispredicts both the exit and the first iteration of the next run; the 2-bit version needs two unusual outcomes to flip.
Pipeline performance calculations
Define:
- \(k\) = number of stages,
- \(s\) = average stall cycles per instruction,
- \(b\) = fraction of instructions that are branches,
- \(m\) = misprediction rate,
- \(p\) = misprediction penalty in cycles.
\[ \text{CPI} = 1 + s + b \cdot m \cdot p, \qquad \text{speedup} \approx \frac{k}{\text{CPI}} \]
Worked example, five stages:
- 20% of instructions are loads; 50% of those are used immediately → one stall each: \(s = 0.10\).
- 15% are branches; 10% mispredict; penalty 2 cycles: \(bmp = 0.15 \times 0.10 \times 2 = 0.03\).
- CPI = \(1 + 0.10 + 0.03 = 1.13\).
- Speedup over an unpipelined 5-cycle machine: \(5 / 1.13 = 4.42\).
Another core with 20% branches, 99% prediction accuracy, and a 15-cycle penalty:
\[ \text{CPI} = 1 + 0.20 \times 0.01 \times 15 = 1.03 \]
The penalty term is why predictors matter more as pipelines deepen. A 15-cycle misprediction on a 5% miss rate costs 0.15 CPI on its own, which can erase the gain from a higher clock.
// branches are the enemy: this compiles to a branch per element
int count_positive(const int* a, int n) {
int c = 0;
for (int i = 0; i < n; ++i)
if (a[i] > 0) ++c;
return c;
}
On random data, the if is unpredictable and costs a misprediction almost every
other element. A branchless version (c += (a[i] > 0);) compiles to a compare and
an add, with no branch at all.
with a 10-cycle penalty. What is the CPI from branches alone?
ASolution
\(0.10 \times 0.10 \times 10 = 0.10\), so CPI = 1.10 from that term.
Superscalar and out-of-order execution
A superscalar core issues more than one instruction per cycle (width 2–8). Ideal IPC equals the width, but dependencies and resource limits reduce it.
Out-of-order execution lets independent instructions bypass stalled ones. The core keeps a window of instructions, renames registers to remove WAR/WAW, and executes anything whose operands are ready. Results are committed in program order so that exceptions and memory state stay correct.
This is why IPC can exceed 1 (typically 2–4 on modern cores) and why measured performance is so hard to predict from instruction counts alone.
ASolution
To keep precise exceptions and a consistent memory view. If an older instruction faults, the younger ones must not have changed architectural state.
Bugs and edge cases
- Counting stages as latency. Five stages means five cycles latency, not five times faster.
- Ignoring fill and drain. Small loops and short programs see much less than the ideal speedup.
- Assuming forwarding removes all stalls. The load-use case always needs one.
- Forgetting branch penalty assumptions. State whether resolution is in ID or EX; the arithmetic changes.
- Mixing CPI and IPC. IPC = 1/CPI only when CPI is the total cycles per instruction.
- Assuming stalls are free. A stall wastes an issue slot for every instruction in flight behind it.
- Ignoring the compiler. Scheduling instructions to separate load and use is often easier than adding hardware.
failure?
ASolution
No. CPI 2 means 0.5 IPC, well below the width of 4. Dependencies, cache misses, and branch misses commonly keep real workloads far below peak issue width.
Next: Memory Hierarchy (COA Core #4) — cache geometry, AMAT, and the arithmetic of hits and misses.