Notes
All notes

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.

QQuestionDoes a deeper pipeline always improve performance?
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

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.

QQuestionWhy is the speedup less than \(k\) for finite \(n\)?
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.

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}
QQuestionWhy do modern CPUs have separate L1 instruction and data caches?
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.

QQuestionWhy are WAR and WAW called false dependencies?
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:

\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
QQuestionWhy can an ALU result be forwarded without a stall but a load result

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:

Fixes:

QQuestionWhy is a branch that is resolved early cheaper?
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:

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}
QQuestionWhy is a 2-bit counter better than 1-bit for loops?
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:

\[ \text{CPI} = 1 + s + b \cdot m \cdot p, \qquad \text{speedup} \approx \frac{k}{\text{CPI}} \]

Worked example, five stages:

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.

QQuestionA loop has 10% branch instructions and the predictor is 90% accurate

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.

QQuestionWhy must an out-of-order core still commit in order?
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

QQuestionA program has CPI 2 on a 4-wide superscalar core. Is that a 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.