Repository navigation
Computer Architecture 04 branches
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Branch predictor
- Wikipedia: Hazard (computer architecture)
- Wikipedia: Speculative execution
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 3
A branch is the processor's version of a fork in the road: an if, a loop test or a function call. The pipeline needs to fetch the next instruction every cycle, but it only learns which way the branch goes several stages later. Waiting wastes cycles; guessing is faster but sometimes wrong. This page explains the problem and the remedies, from simple stalls to modern branch predictors.
This page covers why branches cause control hazards, the cost of waiting, static prediction, dynamic prediction (1-bit, 2-bit counters, history-based predictors), the branch target buffer, the return stack, what happens on a misprediction, and branch-free code. The out-of-order machinery that lets a core run far ahead of a predicted branch is on ILP.
You are driving and reach a junction, but the sign telling you which way to go is 5 km past the junction. You can:
| Option | Processor equivalent | Cost |
|---|---|---|
| Stop and wait until someone tells you | Stall | Always lose time |
| Guess a direction and keep driving; turn back if wrong | Predict and speculate | Free if right, expensive if wrong |
| Remember which way you went last time here | Dynamic prediction | Usually right for repeated trips |
// illustrative: if (x == 0) y = 1; else y = 2;
CMP X0, #0
B.NE else // which instruction comes next?
MOV X1, #1
B done
else:
MOV X1, #2
done:
In the five-stage pipeline from Pipelining, the branch is fetched in IF but its outcome is only known in EX. Meanwhile the fetch stage has to fetch something in the next two cycles.
| Cycle | C1 | C2 | C3 | C4 |
|---|---|---|---|---|
B.NE |
IF | ID | EX (outcome known) | MEM |
| next? | IF ? | ID ? | ||
| next? | IF ? |
flowchart TD
F["Fetch a branch"] --> Q{"Outcome known yet?"}
Q -->|"No (most of the time)"| C{"What to do?"}
C --> S["Stall: fetch nothing<br/>lose cycles on every branch"]
C --> P["Predict: fetch the guessed path"]
P --> R{"Guess right?"}
R -->|"Yes"| OK["No time lost"]
R -->|"No"| FL["Flush wrong instructions<br/>restart at correct path"]
About one instruction in five or six is a branch in typical code, so stalling on every branch would make the processor much slower. In a deep pipeline the outcome may be known 10-20 stages after fetch, which makes waiting far worse.
Sources: Wikipedia: Hazard (computer architecture)
Extra hardware can compare registers in the ID stage instead of EX, so only one cycle is lost instead of two. This helps short pipelines but not deep ones.
The guess is fixed and does not learn:
| Rule | Reasoning |
|---|---|
| Always predict not taken | Simplest: just keep fetching the next instruction |
| Backward taken, forward not taken (BTFN) | A branch jumping backwards is usually a loop, which repeats; forward branches often skip rare cases |
| Compiler hints | The compiler places the likely path as the fall-through, using profile data or __builtin_expect
|
The hardware remembers what each branch did before.
Store one bit per branch: "taken last time" or "not taken last time". Predict the same again.
Problem: a loop that runs 10 times then exits. Each time the loop is entered:
| Visit | Actual | 1-bit predicts | Result |
|---|---|---|---|
| Iterations 1-9 | Taken (loop back) | Iter 1: Not taken (left over from last exit) | 1 miss |
| Iteration 10 | Not taken (exit) | Taken | 1 miss |
Two misses per loop run: one at the exit, one when the loop starts again.
Use two bits, so one surprise is not enough to change the prediction:
stateDiagram-v2
[*] --> StronglyTaken
StronglyTaken --> WeaklyTaken: not taken
WeaklyTaken --> StronglyTaken: taken
WeaklyTaken --> WeaklyNotTaken: not taken
WeaklyNotTaken --> WeaklyTaken: taken
WeaklyNotTaken --> StronglyNotTaken: not taken
StronglyNotTaken --> WeaklyNotTaken: taken
StronglyTaken --> StronglyTaken: taken
StronglyNotTaken --> StronglyNotTaken: not taken
Predict taken in the two "Taken" states. For the 10-iteration loop, the exit moves the counter from Strongly Taken to Weakly Taken, which still predicts taken, so the next run starts correctly. Only one miss per loop run.
Branches often depend on each other or follow patterns:
if (a == 2) a = 0; // branch 1
if (b == 2) b = 0; // branch 2
if (a != b) ... // branch 3 depends on what 1 and 2 didA global history register records the outcomes of the last few branches (for example 1101). The predictor uses the branch address combined with that history to pick a counter, so the same branch can get different predictions in different situations.
flowchart LR
PC["Branch address"] --> X["Combine<br/>(e.g. XOR)"]
GH["Global history<br/>last N outcomes"] --> X
X --> T["Table of 2-bit counters"]
T --> P["Prediction: taken / not taken"]
| Predictor | Idea |
|---|---|
| Gshare | XOR branch address with global history to index one table |
| Tournament | Two predictors plus a chooser that learns which one is better per branch |
| TAGE | Several tables using different history lengths; the longest one that matches wins |
| Perceptron | A tiny neural-network-like weighted sum of history bits |
Modern high-end cores use TAGE-like or perceptron-like designs and are right well over 90% of the time on typical code. The exact designs are not published in detail.
Sources: Wikipedia: Branch predictor
Predicting "taken" is not enough; fetch also needs the target address, in the same cycle, before the instruction is even decoded.
| Structure | Answers | Used for |
|---|---|---|
| Branch target buffer (BTB) | "Is the instruction at this address a branch, and where did it go last time?" | Direct and indirect branches |
| Return address stack (RAS) | "Where will this RET return to?" |
Push on BL (call), pop on RET
|
| Indirect predictor | "Where will this jump through a register go?" | Virtual calls, switch jump tables |
flowchart LR
PC["PC"] --> BTB["BTB lookup"]
PC --> DIR["Direction predictor"]
BTB -->|"target"| MUX{"taken?"}
DIR --> MUX
MUX -->|"yes"| T["Next PC = target"]
MUX -->|"no"| N["Next PC = PC + 4"]
Instructions fetched after a prediction are speculative: they may run, but their results are not made permanent until the branch is confirmed.
sequenceDiagram
participant F as Fetch
participant B as Branch unit
participant P as Pipeline
F->>P: fetch predicted path (speculative)
P->>B: branch reaches execute
B-->>B: compare actual vs predicted
alt correct
B->>P: keep results
else mispredicted
B->>P: flush all younger instructions
B->>F: restart at correct address
end
The misprediction penalty is roughly the number of stages between fetch and branch resolution, often 10-20 cycles on a big core.
Worked example: 20% of instructions are branches, 5% of those are mispredicted, penalty 15 cycles, base CPI 1.
CPI = 1 + 0.20 × 0.05 × 15 = 1 + 0.15 = 1.15
With 10% misprediction instead the CPI is 1.30, so predictor accuracy matters a lot.
Sources: Wikipedia: Speculative execution
If a branch is hard to predict (random data), the compiler can replace it with a conditional select, which has no control hazard at all. On Arm this is CSEL:
// illustrative: y = (x == 0) ? 1 : 2;
MOV X2, #1
MOV X3, #2
CMP X0, #0
CSEL X1, X2, X3, EQ // X1 = (flags say equal) ? X2 : X3
Both values are computed and one is picked. This is a win for unpredictable branches with cheap bodies, and a loss when the branch is predictable and one side is expensive. In compilers this is the select instruction, see LLVM IR: Compare and Select.
- Branch outcomes are known late in the pipeline; stalling on every branch is too slow.
- Dynamic predictors (2-bit counters, history-based tables) guess right most of the time; BTB and return stack supply the target.
- A misprediction flushes all younger instructions; cost ≈ pipeline depth. Unpredictable branches can be replaced with conditional selects.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look