5.3.11 · D3Advanced Microarchitecture

Worked examples — Speculative execution

3,801 words17 min readBack to topic

This is the hands-on companion to Speculative execution. The parent note told you what speculation is and why CPUs gamble on branches. Here we drill the arithmetic: for every kind of branch a program can throw at a CPU, we compute the exact cycle cost, decide whether speculation wins or loses, and prove it.

Before we touch numbers, four quantities do all the work. Let's earn each symbol.

The scenario matrix

Branches don't come in infinite varieties — they come in a handful of behaviour classes. This table is the full list. Every cell gets a worked example below.

Cell Case class What makes it special Example
A Correct guess () best case, penalty never paid Ex 1
B Single wrong guess in a long run one miss amortised over many hits Ex 2 (loop)
C 50/50 unpredictable () worst realistic case, gamble may lose Ex 3
D Degenerate: limiting value, penalty term vanishes Ex 4
E Degenerate: (always wrong) pathological, penalty every time Ex 4
F Break-even point the exact accuracy where gamble = stall Ex 5
G Real-world word problem mixed branch mix in real code Ex 6
H Exam twist: deeper pipeline grows, changes the verdict Ex 7
I Security cell (correctness, not speed) Spectre leak count, not cycles Ex 8

Now we work every cell.










Recall Quick self-test

Average penalty formula ::: , where is accuracy and is the misprediction penalty. Precise vs headline penalty ::: Precise ; headline is the worst case where the branch resolves at the last stage (). What sets the stall cost ::: The resolve stage where the branch condition is computed; . Early-resolving branches are cheap to stall on, late ones expensive. Why a 2-bit counter misses only once at loop exit ::: Its hysteresis means one surprise nudges but does not flip the prediction, so a single anomaly costs one miss, not the two a 1-bit predictor would. Speculate-vs-stall rule ::: Speculate only when . Break-even accuracy for , ::: . Why a deeper pipeline is riskier for speculation ::: It increases the worst-case while (set by the resolve stage) stays fixed, so the same miss rate costs more cycles and the margin over stalling shrinks. Which cell is about correctness not speed ::: Cell I — Spectre-style cache side channels; a squashed speculative load still leaves a cache footprint.

See also: Speculative execution · Out-of-order execution · Instruction-level parallelism (ILP) · Superscalar architecture · Pipeline hazards