---
title: Branch prediction
heading: Two-bit counters, correlating and gshare predictors, tournaments, target buffers and return stacks
eyebrow: S4 · Lesson 7 · Branch prediction
xp: 50
---

::: hook
A modern core fetches several instructions per cycle into a pipeline 15 or more stages deep, so at any moment it holds dozens of instructions past the last branch it has actually resolved. If it guessed a branch wrong, all of that work is thrown away. With branches every five or six instructions, prediction accuracy is one of the strongest levers on performance: going from 90% to 97% correct can speed a wide core up by a third. Predictors went from one bit per branch to two-bit counters, then to tables indexed by the history of recent branches, and today to perceptron and TAGE designs that are right well over 95% of the time.
:::

::: play
- Misprediction rate of a loop's closing branch against the loop's trip count N, when the loop runs again and again.
- A 1-bit predictor (solid) misses twice per loop: on the exit and again on the first iteration of the next run. A 2-bit counter (dashed) misses only the exit.
- A predictor that keeps h bits of branch history (dotted line) learns the whole pattern when N ≤ h + 1 and predicts the exit too. Longer loops still cost one miss per run.
:::
:::

```sim plot
view: graph
x: N = 2..40
y: m = 0..100 %
slider: h = 2..16 step 1 = 8
plot: 100*2/N | samples: 400 | label: 1-bit, %
plot: 100/N | samples: 400 | dashed | color: ch2 | label: 2-bit counter, %
plot: 100/N*step(N - h - 1.5) | samples: 400 | dashed | color: ch3 | label: with h bits of history, %
```

::: predict
## A loop runs 10 iterations, and the program runs the whole loop many times. What fraction of the loop branch's executions does a 2-bit counter mispredict?

- [ ] 0%
- [x] 10%
- [ ] 20%
- [ ] 50%

::: reveal
10%: one miss per run of the loop, on the exit. The counter sits in "strongly taken"; the exit moves it only to "weakly taken", so the first iteration of the next run is still predicted taken. A 1-bit predictor would flip to "not taken" on the exit and miss the first iteration too: 20%. A predictor with 10 or more bits of history sees nine takens in a row and knows the exit is next: 0%.
:::
:::

::: nameit
## Counters and tables

- A **branch history table** (BHT) is indexed by low bits of the branch's address. A 2-bit saturating counter per entry predicts taken in its two upper states and needs two wrong outcomes to change its mind. A table of $2^n$ entries holds $2^{n+1}$ bits.
- Different branches that share an entry **alias**. With B active branches spread uniformly over $2^n$ entries, a given branch shares its entry with at least one other with probability $1 - (1 - 2^{-n})^{B-1}$.

## Using history

- **Correlating** predictors index by the outcomes of recent branches as well: `if (a) …; if (a && b) …` correlate.
- **gshare** indexes the counter table by the branch address XOR an h-bit global history register, spreading each branch's patterns across the table.
- **Tournament** predictors run a local and a global predictor and use a third table of counters to choose per branch. **TAGE** keeps several tables indexed by geometrically longer histories and uses the longest that matches.

## Targets and returns

- A **branch target buffer** (BTB) caches each taken branch's target so fetch can redirect in the same cycle. A BTB miss on a taken branch costs a few cycles even when the direction was predicted right.
- A **return address stack** pushes on calls and pops on returns; it predicts returns perfectly while the call depth fits.

## The cost

$$\Delta\text{CPI} = f_\text{branch} \times (1 - \text{accuracy}) \times \text{penalty}$$
:::

::: example
## Branches are 20% of instructions and a misprediction costs 15 cycles on a core whose base CPI is 0.5. Compare 90% and 97% accuracy.

::: solution
1. **At 90% accuracy.**
   $$\begin{aligned} \Delta\text{CPI} &= 0.2 \times 0.1 \times 15 \\ &= 0.30 \end{aligned}$$
   for a total CPI of 0.80.
2. **At 97% accuracy.**
   $$\begin{aligned} \Delta\text{CPI} &= 0.2 \times 0.03 \times 15 \\ &= 0.09 \end{aligned}$$
   for a total CPI of 0.59.
3. **Speedup.**
   $$0.80/0.59 = 1.36$$
4. **Why accuracy matters more over time.** The wider and deeper the core, the more accuracy is worth, because the base CPI shrinks while the penalty grows.

**Answer:** the 97% predictor gives a CPI of 0.59 against 0.80, making the core 1.36 times faster.
:::
:::

::: example
## A program has 2000 active branches and a 4096-entry table of 2-bit counters. How many bits is the table, and what's the chance a given branch shares its entry?

::: solution
1. **Table size.**
   $$4096 \times 2 = 8192\ \text{bits}$$
   which is 1 KB.
2. **Chance of sharing.** The branch's entry is free only if none of the other 1999 branches lands there:
   $$1 - (1 - 1/4096)^{1999} = 0.39$$
3. **Harmful or not.** Many of those collisions are harmless (the branches agree), but some are destructive, which is why larger tables, tagged tables (as in TAGE) and hashing with history improve accuracy.

**Answer:** the table is 8192 bits (1 KB), and a given branch shares its entry with probability 0.39.
:::
:::

::: example
## Branches are 20% of instructions, predicted 96% right with a 14-cycle misprediction penalty. Taken branches are 12% of instructions, and 5% of them miss in the BTB, costing 2 cycles each. What CPI do branches add?

::: solution
1. **Direction mispredictions.**
   $$0.2 \times 0.04 \times 14 = 0.112$$
2. **Target misses in the BTB.**
   $$0.12 \times 0.05 \times 2 = 0.012$$
3. **Total.**
   $$0.112 + 0.012 = 0.124$$
   cycles per instruction, about 12% on a core with a base CPI near 1.
4. **Which matters more.** The direction predictor matters most, but a small BTB can cost as much as a few points of accuracy.

**Answer:** branches add 0.124 cycles per instruction.
:::
:::

::: check
given: N = 4 | 8 | 25 | 100
answer: 100*2/N
unit: %
tolerance: 0.5%

## A loop of {N} iterations runs many times. What's a 1-bit predictor's misprediction rate on its closing branch?

::: right
Right. Two misses per run: {answer}%.
:::

::: misses
- [100/N] A 1-bit predictor also misses the first iteration of the next run.
- [any] Not yet. Count misses per run of the loop.
:::
:::

::: check
given: N = 4 | 8 | 25 | 100
answer: 100/N
unit: %
tolerance: 0.5%

## The same loop, {N} iterations, with a 2-bit counter. What's the misprediction rate?

::: right
Right. One miss per run: {answer}%.
:::

::: misses
- [100*2/N] The counter only drops to weakly taken on the exit.
- [any] Not yet. Count misses per run.
:::
:::

::: check
given: f = 0.15 | 0.25; a = 0.9 | 0.95 | 0.99; P = 10 | 20
answer: f*(1 - a)*P
tolerance: 0.5%

## Branches are {f} of instructions, the predictor is {a} accurate, and a misprediction costs {P} cycles. How much CPI do mispredictions add?

::: right
Right. $f(1 - a)P$ = {answer}.
:::

::: misses
- [f*a*P] Only the wrong predictions cost cycles.
- [any] Not yet. Frequency × miss rate × penalty.
:::
:::

::: check
given: c = 0.4 | 0.8; f = 0.18 | 0.22; a = 0.88 | 0.92; b = 0.96 | 0.98; P = 12 | 18
answer: (c + f*(1 - a)*P)/(c + f*(1 - b)*P)
tolerance: 0.5%

## A core has base CPI {c}, {f} branches and a {P}-cycle misprediction penalty. What speedup comes from improving accuracy from {a} to {b}?

::: right
Right. {answer}.
:::

::: misses
- [(1 - a)/(1 - b)] Speedup is about total CPI, not the miss rates alone.
- [any] Not yet. Compare total CPI.
:::
:::

::: check
given: n = 10 | 12 | 14; B = 500 | 3000
answer: 1 - (1 - 2^(-n))^(B - 1)
tolerance: 0.5%

## {B} active branches share a predictor of $2^{\given{n}}$ entries, indexed uniformly. What's the probability a given branch shares its entry with at least one other?

::: right
Right. $1 - (1 - 2^{-n})^{B-1}$ = {answer}.
:::

::: misses
- [B/2^n] That's the expected number of other branches per entry, not a probability.
- [any] Not yet. All B − 1 others must miss this entry.
:::
:::

::: check
given: f = 0.15 | 0.2; t = 0.6 | 0.7; h = 0.85 | 0.95; c = 2 | 3
answer: f*t*(1 - h)*c
tolerance: 0.5%

## Branches are {f} of instructions and {t} of them are taken. The BTB finds the target of {h} of taken branches; a BTB miss costs {c} cycles. What CPI does it add?

::: right
Right. $f \cdot t \cdot (1 - h) \cdot c$ = {answer}.
:::

::: misses
- [f*(1 - h)*c] Only taken branches need a target.
- [any] Not yet. Taken branches that miss the BTB, times the cost.
:::
:::

::: check
kind: parts
given: f = 0.15 | 0.25; a = 0.9 | 0.95 | 0.99; P = 10 | 20; n = 10 | 12 | 14; B = 500 | 4000

## Branches are {f} of instructions, predicted with accuracy {a} and a {P}-cycle penalty, using a table of $2^n$ 2-bit counters (n = {n}) shared by {B} active branches.

::: part
answer: f*(1 - a)*P
tolerance: 0.5%

### What CPI do mispredictions add?

::: misses
- [f*a*P] Only the wrong predictions cost cycles.
- [any] $f(1 - a)P$.
:::
:::

::: part
answer: 2^(n + 1)
unit: bits
tolerance: 0

### How many bits is the table?

::: misses
- [any] Two bits per entry.
:::
:::

::: part
answer: 1 - (1 - 2^(-n))^(B - 1)
tolerance: 0.5%

### What is the chance a given branch shares its entry?

::: misses
- [any] $1 - (1 - 2^{-n})^{B-1}$.
:::
:::
:::

::: check
kind: derivation
vars: c = 0.3..2, f = 0.05..0.3, a = 0.8..0.999, P = 5..30, T = 0.5..3

## A core has base CPI c; branches are a fraction f of instructions, predicted with accuracy a and a penalty of P cycles.

::: step
answer: c + f*(1 - a)*P

### What is its CPI?
:::

::: step
answer: 1 - (T - c)/(f*P)

### What accuracy would reach a CPI of T?
:::

::: right
Right. Each point of accuracy is worth $fP/100$ cycles per instruction, more as pipelines deepen.
:::
:::

::: explain
## Why does a 2-bit counter predict loops better than a 1-bit predictor?

::: model
A loop branch is taken every iteration except the last. A 1-bit predictor simply remembers the last outcome, so the exit flips it to "not taken", and the next time the loop starts it mispredicts the first iteration as well: two misses each time the loop runs. A 2-bit counter needs two consecutive surprises to change its prediction. The single not-taken exit only moves it from strongly to weakly taken, so it still predicts taken when the loop starts again. It pays only for the exit, halving the misses, and in general it ignores one-off anomalies while still adapting to a branch whose behavior really changes.
:::
:::

::: practice

::: check
given: N = 5 | 16 | 50
answer: 100/N
unit: %
tolerance: 0.5%

## 2-bit misprediction rate on a {N}-iteration loop?

::: misses
- [any] One miss per run.
:::
:::

::: check
given: f = 0.17 | 0.24; a = 0.93 | 0.985; P = 14 | 22
answer: f*(1 - a)*P
tolerance: 0.5%

## Misprediction CPI: {f} branches, {a} accuracy, {P}-cycle penalty?

::: misses
- [any] $f(1 - a)P$.
:::
:::

::: check
given: n = 11 | 13; B = 800 | 5000
answer: 1 - (1 - 2^(-n))^(B - 1)
tolerance: 0.5%

## Aliasing chance: {B} branches, $2^{\given{n}}$ entries?

::: misses
- [any] $1 - (1 - 2^{-n})^{B-1}$.
:::
:::
:::
