# CS152 Lecture 15: Branch Prediction ### Section 1: The Cost of Branches and Foundations of Branch Prediction Out-of-order superscalar processors can issue and complete multiple instructions per cycle by keeping dozens of instructions in flight simultaneously. However, all of that parallel machinery stalls or wastes vast amounts of work if the processor does not know *which* instructions to fetch next. Whenever the fetch unit encounters a conditional branch, it faces a **control-flow penalty**: modern processors may have **more than 10 pipeline stages between next-PC calculation (`PC` $\to$ `I-cache` $\to$ `Fetch Buffer` $\to$ `Decode` $\to$ `Issue Buffer`) and branch resolution** at the end of `Execute`. How much work is lost if the pipeline waits or fetches down the wrong instruction stream? Roughly: $$\text{Lost Work} \approx (\text{Loop Length} \times \text{Pipeline Width}) + \text{Buffer Occupancy}$$ Let's break this expression down term by term: - $\text{Loop Length}$ is the number of pipeline stages between `Fetch` (where the next `PC` is needed) and `Execute` (where the branch outcome is actually computed). - $\text{Pipeline Width}$ is how many instructions the frontend fetches and decodes per cycle. Multiplying $\text{Loop Length} \times \text{Pipeline Width}$ counts all instructions actively flowing through the frontend pipeline stages. - $\text{Buffer Occupancy}$ accounts for younger instructions sitting in intermediate queues (`Fetch Buffer`, `Issue Buffer`, and `Reorder Buffer`) behind the unresolved branch. Together, the expression quantifies the total number of in-flight instructions flushed—or the total instruction slots wasted—whenever control flow goes off track. #### Worked Example: Measuring the Misprediction Penalty Consider a **4-way superscalar** processor with **8 pipeline stages from fetch to dispatch**, an **80-entry Reorder Buffer (ROB)**, and **3 cycles from issue to branch resolution**: 1. Suppose a branch is at the head of the ROB and resolves late. Up to $8 \times 4 = 32$ instructions can be sitting in the frontend stages between fetch and dispatch. 2. Up to $80 - 1 = 79$ younger instructions can already be sitting behind that branch in the ROB. 3. On a single misprediction, the processor could throw away: $$8 \times 4 + (80 - 1) = 32 + 79 = \mathbf{111\text{ instructions}}$$ Because flushing 111 instructions is catastrophic, notice how sensitive performance is to **prediction accuracy**. Suppose $1/6$ of all executed instructions are branches: - At **90% accuracy**, $10\%$ of branches mispredict, so $1/6 \times 0.10 = 1/60$ instructions mispredict—one flush every **60 instructions**. - Improving accuracy from **90% to 95%** cuts the misprediction rate in half (from $10\%$ to $5\%$), **removing 50% of branch mispredicts** and doubling the average run between flushes from **60 instructions to 120 instructions**. #### Software and Hardware Approaches to Control Flow Engineers tried several ways to shrink this penalty before settling on dynamic prediction: - **Software — Loop unrolling:** Eliminates loop-closing branches and increases the straight-line run length between branches. - **Software — Instruction scheduling:** Schedules instructions to compute the branch condition as early as possible. This offers limited value because branches often sit directly on the critical dataflow path through the code. - **Hardware — Delay slots:** Executes independent instructions placed immediately after a branch to replace pipeline bubbles with useful work. This requires compiler cooperation and quickly hits diminishing returns on wide, deep pipelines (filling $4 \times 10 = 40$ delay slots is impossible). - **Hardware — Speculation (Branch Prediction):** Predicts which way the branch will go and speculatively executes instructions beyond the branch. Because modern branch predictors achieve **$>95\%$ accuracy**, speculation dominates. Doing it safely requires two kinds of hardware support: 1. **Prediction structures:** Branch History Tables (BHTs), Branch Target Buffers (BTBs), and specialized predictors. 2. **Mispredict recovery mechanisms:** Keeping result computation separate from commit (via the ROB), killing instructions following a mispredicted branch, and restoring architectural/rename state to the point immediately after the branch. #### Static Branch Prediction Before building dynamic predictors, how well can we predict branches *statically* at compile time? Overall, a conditional branch is taken roughly **60–70%** of the time, but direction depends strongly on target direction: - **Backward branches** (typically loop-closing branches jumping back to the top of a loop) are taken **~90%** of the time. - **Forward branches** (typically `if-then-else` skips) are taken only **~50%** of the time. Some ISAs encode preferred directions directly in the opcode (e.g., Motorola MC88110 had `bne0` preferred taken and `beq0` preferred not-taken), while others allow the compiler to set a static prediction bit per branch instruction (e.g., HP PA-RISC, Intel IA-64), achieving **~80% accuracy**. To push past 80% into the 95%+ range needed by deep superscalars, hardware must learn dynamically from runtime execution history. *[Editor Note: removed course title slide, previous-lecture recap slide, quiz logistics slide, and acknowledgements.]* #### ✎ Check Your Understanding 1. In a 4-way superscalar with 6 frontend stages from fetch to dispatch and a 64-entry ROB, what is the maximum number of instructions that might be discarded on a single branch misprediction? **Answer:** Up to $6 \times 4 + (64 - 1) = 24 + 63 = \mathbf{87\text{ instructions}}$. 2. Why does improving branch prediction accuracy from $90\%$ to $95\%$ double the average number of instructions executed between mispredictions? **Answer:** Because the misprediction rate drops from $1 - 0.90 = 10\%$ to $1 - 0.95 = 5\%$, cutting the frequency of mispredictions in half. --- ### Section 2: Dynamic Branch Direction Predictors Dynamic branch prediction exploits two patterns observed in real programs: 1. **Temporal correlation:** The way a specific branch resolved in the past is often a good predictor of how that same branch will resolve the next time it executes. 2. **Spatial (global) correlation:** Several nearby branches may resolve in a highly correlated manner along a preferred execution path. #### The Branch History Table (BHT) Framework To exploit temporal correlation, hardware uses a **Branch History Table (BHT)**: a $2^k$-entry table of $N$-bit state machines indexed by the lower $k$ bits of the `Fetch PC` (ignoring the bottom two `00` bits for 4-byte-aligned instructions). Look at how the fetch hardware operates in parallel: - **Top/Left path (Instruction Fetch & Target Calc):** `Fetch PC` reads the `I-Cache`, which produces the `Instruction` (`Opcode | offset`). The `Opcode` tells us `Branch?` (whether this instruction is even a branch), while an adder computes `Target PC = Fetch PC + offset`. - **Right path (Direction Prediction):** Simultaneously, the $k$-bit `BHT Index` reads one entry of the $2^k$-entry BHT to output `Taken / ¬Taken?`. Notice an important property: **a BHT is a "lossy" hash table**. It stores no tags—if two branches have the same lower $k$ PC bits, they **alias** and overwrite each other's state. When the branch eventually resolves in Execute, hardware updates that entry's state based on the actual outcome. #### 1-Bit vs. 2-Bit Hysteresis Predictors Suppose each BHT entry is just **1 bit** ($N = 1$), simply remembering the last direction the branch took. What goes wrong on a standard loop (`for (i=0; i<10; i++)`)? A 1-bit predictor suffers **two mispredicts on every single execution of the loop**: 1. On the **first iteration**, it predicts the loop-closing backward branch *not-taken* (because the loop exited on the final iteration the last time the loop ran). 2. On the **last iteration**, it predicts the backward branch *taken* (because the previous 9 iterations stayed inside the loop). To fix this, we use **2 branch prediction bits per entry** ($N = 2$) and **change the prediction only after two consecutive mistakes!** Look carefully at how the 4-state hysteresis state machine is structured—its state encodes `(predict taken / not taken) × (last prediction right / wrong)`: - State **`11`** (*Predict Taken, last right*): On `Taken` $\to$ stays at `11`. On `Not taken` $\to$ moves to `10`. - State **`10`** (*Predict Taken, last wrong*): Still predicts `Taken`! On `Taken` $\to$ returns to `11`. On `Not taken` (two consecutive misses!) $\to$ jumps directly to **`00`** (*Predict Not Taken, last right*). - State **`00`** (*Predict Not Taken, last right*): On `Not taken` $\to$ stays at `00`. On `Taken` $\to$ moves to `01`. - State **`01`** (*Predict Not Taken, last wrong*): Still predicts `Not Taken`! On `Not taken` $\to$ returns to `00`. On `Taken` (two consecutive misses!) $\to$ jumps directly to **`11`**. Notice why this beats a 1-bit predictor on loops: when the loop exits on the last iteration, state `11` drops only to `10`—so on the next entry into the loop, it *still* predicts `Taken`, cutting loop mispredicts from 2 down to 1! A **4K-entry BHT with 2 bits/entry** achieves **~80–90% correct predictions**. #### Exploiting Spatial Correlation: Two-Level and GShare Predictors Can we do better than 90%? Consider this C code (Yeh and Patt, 1992): ```c if (x[i] < 7) then y += 1; if (x[i] < 5) then c -= 4; ``` Look at the correlation between the two branches: **if the first condition (`x[i] < 7`) is false, the second condition (`x[i] < 5`) is guaranteed to be false too!** A per-branch BHT cannot see what happened at the *previous* branch. To capture spatial correlation, we add a global **History register ($H$)**—a $P$-bit shift register that records the `Taken / ¬Taken` outcomes of the **last $P$ branches executed** by the processor. This creates a **Two-Level Branch Predictor** (used in the Intel Pentium Pro with $P=2$, achieving **~95% accuracy**): - The $k = \log_2(M)$ bits of `Fetch PC` index into $2^P$ parallel BHT tables, each with $M$ entries of $N$ bits. - The $P$-bit global history shift register controls a $2^P$-to-1 multiplexer at the bottom, selecting which BHT column's prediction (`Taken / ¬Taken?`) corresponds to the current path of recent branches. Multiplying the number of BHT tables by $2^P$ grows hardware exponentially with history length $P$ (for $P=10$, you would need $1024$ separate BHT tables!). The **GShare Two-Level Predictor** avoids this blowup: - Keep a single $10$-bit global `Branch history` shift register and a single $1024$-entry table of $2$-bit predictors. - Combine the $10$-bit `Branch history` with the lower $10$ bits of the `Branch address` using a bitwise **Exclusive OR (XOR)**, and use that $10$-bit XORed index to read the $1024$-entry table! Why XOR instead of concatenating? XOR distributes different `(PC, global history)` pairs across the entire table, giving each branch multiple virtual slots depending on how execution arrived there, without needing $1024\times$ more memory. #### Tournament Branch Predictor (Alpha 21264) Different branches prefer different predictors: loop branches love local per-branch history, while `if/else` chains love global path history. The **Alpha 21264 Tournament Predictor** runs *both* in parallel and learns which one to trust per branch (achieving **90–100% accuracy** across applications): 1. **Local Path:** `PC` indexes a **Local history table ($1,024 \times 10\text{b}$)** to retrieve that specific branch's last 10 outcomes; that 10-bit pattern indexes a **Local prediction table ($1,024 \times 3\text{b}$)**. 2. **Global Path:** A **Global History ($12\text{b}$)** shift register indexes a **Global Prediction table ($4,096 \times 2\text{b}$)**. 3. **Choice Selector:** The same $12$-bit Global History also indexes a **Choice Prediction table ($4,096 \times 2\text{b}$)** of 2-bit saturating counters that learns whether the local or global predictor has been more accurate recently, driving a mux to output the final `Prediction`. *(Crucial detail: the `Global History` register is **speculatively updated** with each prediction at fetch time so back-to-back branches see the latest predicted path, and **restored** if a mispredict occurs!)* #### TAGE: Tagged Geometric History Length Prediction Two-bit counters, GShare, and the tournament predictor are older designs. A stronger one is **TAGE** (Seznec and Michaud, 2006), which at equal storage outperformed every predictor entered in the first Championship Branch Prediction (December 2004). TAGE combines two ideas: 1. **Geometric history lengths.** A base predictor $T_0$ (a PC-indexed table of 2-bit counters) is backed by $M$ tagged tables $T_1 \dots T_M$. Table $T_i$ is indexed by a hash of the PC and the most recent $L(i)$ global history bits, where the lengths grow geometrically: $$L(i) = \text{int}\left(\alpha^{i-1} \cdot L(1) + 0.5\right)$$ With $\alpha = 2$ and $L(1) = 2$, an 8-component predictor uses history lengths $\{0, 2, 4, 8, 16, 32, 64, 128\}$. A few tables capture very long correlations while most of the storage goes to short histories. 2. **Partial tags.** Each tagged entry holds a 3-bit signed prediction counter `ctr`, a partial **tag**, and a 2-bit **useful** counter `u`. Unlike a BHT, a tagged table only offers a prediction when its tag matches, so unrelated branches stop aliasing. **Prediction:** all tables are read in parallel, and the **hitting table with the longest history** (the *provider*) supplies the prediction. The prediction the next-longest hit would have given is the *alternate* prediction; with no tag hit at all, the base predictor decides. **Update:** - The provider's `ctr` is trained on every branch. - Its `u` counter is updated only when the provider and the alternate prediction disagree: incremented if the provider was right, decremented if wrong. All `u` counters are periodically aged toward zero so stale entries can be replaced. - **On a misprediction**, TAGE tries to allocate one new entry in a table with a *longer* history than the provider, choosing a table whose candidate entry has `u = 0`. If none is free, the `u` counters of those candidate entries are decremented instead. The global history is hundreds of bits long and is **updated speculatively** at prediction time, so it must be restored on a misprediction; a circular buffer makes that a single head-pointer restore. The same paper applies the scheme to indirect branch targets as **ITTAGE**. #### Why Not Just Execute Both Directions? You might wonder: *Instead of predicting, why not speculatively execute both the taken and not-taken paths at every branch?* - The hardware resource requirement grows exponentially with the number of concurrent unresolved branches ($2^b$ paths for $b$ branches!). - Even for a single branch, **only half of the processor's resources engage in useful work** while the other half computes discarded instructions. - With $>95\%$ branch prediction accuracy, **it is far more cost-effective to dedicate 100% of execution resources to the predicted direction**. #### ✎ Check Your Understanding 1. Suppose a 2-bit hysteresis BHT entry is in state `11` (Predict Taken, last right). The branch resolves as `Not taken` once, and then `Taken` on the next execution. What state does the entry visit after each outcome, and did it ever predict `Not taken`? **Answer:** After `Not taken`, it transitions from `11` to `10` (which still predicts `Taken`). After `Taken`, it returns to `11`. It **never** predicted `Not taken` because changing prediction requires two consecutive mistakes. 2. How does a GShare predictor capture 10 bits of global branch history without multiplying BHT storage by $2^{10} = 1024$? **Answer:** It bitwise-XORs the 10-bit global branch history register with 10 bits of the branch's PC to index a single $1024$-entry predictor table. 3. In a TAGE predictor, tables $T_2$ and $T_4$ hit and $T_1$, $T_3$ miss. Which table provides the prediction, and what happens on a misprediction? **Answer:** $T_4$ (the longest-history hit) provides it, with $T_2$ as the alternate prediction. On a misprediction TAGE tries to allocate a new entry in a table with a longer history than $T_4$, picking one whose candidate entry has `u = 0`, or decrements those `u` counters if none is free. --- ### Section 3: Predicting Branch Targets and High-Bandwidth Fetch Even a 100%-accurate BHT has two critical blind spots: 1. **A BHT only predicts branch *direction* (`Taken / ¬Taken`).** It cannot redirect the fetch stream until the branch's target address is computed! 2. **We cannot even use a BHT prediction until we know the fetched instruction *is* a branch**—which only happens *after* decoding! Look at what this costs in a deep frontend such as the **UltraSPARC-III fetch pipeline** (`A`: PC Gen/Mux $\to$ `P`: Inst Fetch 1 $\to$ `F`: Inst Fetch 2 $\to$ `B`: Branch Addr Calc/Begin Decode $\to$ `I`: Complete Decode $\to$ `J`: Steer $\to$ `R`: Reg File Read $\to$ `E`: Integer Execute): - For **conditional direct branches**, the target (`PC + offset`) isn't known until stage `B`/`I`—creating a **3-cycle fetch bubble** even on a *correct* BHT prediction! - For **indirect branches** (such as Jump Register, `JR`), the target lives in a register and isn't known until stage `R`/`E`—creating a **6-cycle bubble**! #### The Branch Target Buffer (BTB) To redirect the `PC` in the *very first cycle*—**before the branch is even fetched or decoded**—we add a **Branch Target Buffer (BTB)**. A $2^k$-entry direct-mapped (or set-associative) BTB is accessed in parallel with the `I-Cache` using the current `PC`: - Unlike a BHT, the BTB stores **tags (`Entry PC`)**, a **`Valid`** bit, and the **`predicted target PC`**. - Only **taken** branches and jumps are stored in the BTB. - When `PC` indexes the BTB, hardware compares the stored `Entry PC` against the full `PC`: if `match && valid`, the `predicted target PC` immediately becomes the next `PC`; if the match fails, the frontend simply fetches `PC + 4`. #### Combining BTB and BHT Because every BTB entry must store a full PC tag and a full target PC, **BTB entries are considerably more expensive than BHT entries** (which are just 2 bits each!). So real processors combine them: - A small, fast **BTB** sits at fetch (`P`) to redirect the `PC` immediately with zero bubbles and accelerate indirect branches (`JR`). - A much larger, more accurate **BHT** sits later at decode (`B`) and **overrides/corrects** the fetch stream whenever the small BTB misses a branch that the BHT predicts taken (or disagrees on direction). - Both the BTB and BHT are updated only after the branch resolves in `E`. #### Indirect Branches (`JR`) and the Subroutine Return Stack (RAS) How well does a BTB handle the three common uses of indirect Jump Register (`JR`) instructions? 1. **Switch statements** (jump to matching case): BTB works well *if* the same case is taken repeatedly. 2. **Dynamic function calls** (jump to runtime function pointer, e.g., C++ virtual function calls): BTB works well *if* objects usually have the same type. 3. **Subroutine returns** (jump to return address): BTB works well *only* if the function always returns to the same caller—**which fails whenever one helper function is called from many distinct call sites!** To fix subroutine returns, processors add a tiny hardware **Subroutine Return Address Stack (RAS)** (typically $k = 8\text{--}16$ entries). Look at nested calls `fa() { fb(); }`, `fb() { fc(); }`, `fc() { fd(); }`: - Whenever a function call (`JAL`/`CALL`) is decoded/executed, hardware **pushes its return address** (`&fb()`, `&fc()`, `&fd()`) onto the stack. - Whenever a subroutine return (`JR ra`) is decoded, hardware **pops the top return address** from the stack to predict the next `PC`—giving near-100% accuracy regardless of how many call sites share the function! #### High-Bandwidth Fetch: Alpha 21264 I-Cache and Trace Caches In wide out-of-order machines, **performance is often limited by instruction fetch bandwidth**: speculative execution fetches **2–3$\times$ more instructions than are committed**, mispredict penalties are dominated by the time to refill the instruction window, and taken branches break sequential cache-line fetches. How do architects fetch wide and fast around taken branches? 1. **Increasing Taken Branch Bandwidth (Alpha 21264 I-Cache):** Fetching 4 instructions per cycle at ~1 GHz leaves no time for tag comparisons or branch prediction inside the single-cycle fetch loop. Alpha 21264 folds **Line Predict** and **Way Predict** bits directly into every cached instruction block! On the **`fast fetch path`**, each block directly supplies the predicted next cache line and way for the very next cycle—taking tag checks (`Tag Way 0/1`), instruction decode, and branch prediction *completely out of the critical 1-cycle fetch loop*! If the separate tag check or BTB later disagrees, it corrects the PC; a 2-bit hysteresis counter per block prevents overtraining the line predictor. 2. **The Taken Branch Limit and Trace Caches:** Integer programs execute a taken branch roughly every **6–9 instructions**. To sustain wide superscalar execution (say, 8+ instructions/cycle), the frontend must execute **multiple taken branches per cycle**, which requires predicting multiple branches per cycle and **fetching multiple non-contiguous basic blocks per cycle**. Using a multiported I-cache is too expensive, interleaving suffers bank conflicts, and merging blocks adds latency before decode. - **Key Idea — Trace Cache** (used in the Intel Pentium 4 to store decoded micro-operations): Dynamically **pack multiple non-contiguous basic blocks** along a hot taken-branch path (e.g., `[Red block + BR] -> [Green block + BR] -> [Blue block + BR]`) **into one contiguous trace cache line**! - The Trace Cache is indexed by both the **starting PC address** *and* the **next $n$ branch predictions**, allowing a **single fetch** to deliver multiple basic blocks across multiple taken branches in one cycle. #### ✎ Check Your Understanding 1. Why is a BTB unable to accurately predict `JR` instructions used for subroutine returns when a utility function like `printf` or `malloc` is called from dozens of places in a program, and what hardware structure solves this? **Answer:** A BTB only remembers the single most recent target for that `JR` instruction's PC, so it mispredicts whenever the function returns to a different call site. A **Subroutine Return Address Stack (RAS)** pushes return addresses on calls and pops them in LIFO order on returns. 2. How does a Trace Cache overcome the taken-branch fetch limit of one basic block per cycle? **Answer:** It stores dynamically linked sequences of non-contiguous basic blocks contiguously inside a single trace cache line (indexed by start address and the next $n$ branch predictions), delivering multiple basic blocks in a single fetch. --- ### Section 4: Branch Misprediction Recovery in Out-of-Order Superscalars Both in-order and out-of-order superscalars can share the exact same frontend branch predictors (`BTB`, `BHT`, `RAS`, `Trace Cache`) and span 10–30 pipeline stages, but their **misprediction recovery** differs sharply: - **In-order issue:** Designed so no instruction issued after a branch can write back before the branch resolves; completed values sit in the bypass network until commit. On mispredict, simply kill all instructions in the pipeline behind the branch. - **Out-of-order issue:** Multiple instructions *younger* than the branch in program order can execute and **complete** (writing results into ROB entries or physical registers) *before* the branch resolves! Wait: we already have an in-order commit point at the ROB head for precise traps. **Could we simply handle branch mispredictions at commit, just like precise traps?** **No!** What is the problem with waiting until commit? If a branch depends on a slow load or divide, waiting for the branch to reach the head of the ROB before squashing wastes dozens of cycles fetching and executing useless wrong-path instructions while starving the correct path! Instead, **out-of-order machines resolve branches out-of-order** as soon as the branch executes: - **Multiple unresolved branches** can sit in the ROB simultaneously. - When a branch resolves and discovers a misprediction, hardware **kills only the instructions in Decode, Fetch, and the ROB that follow that mispredicted branch** (leaving older instructions untouched), and **injects the correct PC** into Fetch. - **How does hardware track which ROB instructions depend on which unresolved branch?** The **MIPS R10000** tags each in-flight instruction with **4 mask bits** corresponding to up to 4 active speculative branches. As each branch resolves correctly, its mask bit is cleared across the machine and reused for the next branch; if it mispredicts, every instruction carrying that branch's mask bit is killed in one cycle! Remember from our earlier discussion of register renaming: killing instructions in the middle of the ROB also means **restoring the Rename Table** to the exact state it held right after the mispredicted branch! How fast can hardware restore the rename table? - **MIPS R10000** keeps **4 full rename-table snapshots**—one for each of the 4 allowed outstanding speculative branches. - **Alpha 21264** keeps **80 snapshots**—one for every single instruction in its 80-entry ROB, enabling single-cycle rename recovery for any branch (or trap) at any position! #### ✎ Check Your Understanding 1. Why don't out-of-order processors wait until a mispredicted branch reaches the commit stage at the head of the ROB to trigger recovery? **Answer:** Waiting until commit would waste many cycles fetching and executing wrong-path instructions and delay refilling the pipeline with the correct path; resolving branches out-of-order cuts the misprediction penalty dramatically. 2. In the MIPS R10000, what happens to the 4 branch mask bits and 4 rename-table snapshots when a speculative branch resolves as *correctly* predicted? **Answer:** Its corresponding mask bit is cleared across all dependent instructions in the ROB/queues, and both that mask bit and its rename-table snapshot become free to be reused by a newly decoded branch.