Skip to content

Computer Architecture 04 branches

Mugundan edited this page Nov 27, 2026 · 1 revision

Branches and Remedies

Relevant source files

The following references were used as context for generating this wiki page:

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.

Purpose and Scope

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.

The Fork-in-the-Road Analogy

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

Why Branches Hurt the Pipeline

// 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"]
Loading

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)

Remedy 1: Resolve Branches Earlier

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.

Remedy 2: Static Prediction

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

Remedy 3: Dynamic Prediction

The hardware remembers what each branch did before.

1-bit Predictor

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.

2-bit Saturating Counter

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
Loading

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.

Correlating and History-Based Predictors

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 did

A 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"]
Loading
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

Knowing Where: The Branch Target Buffer

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"]
Loading

When the Guess Is Wrong

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
Loading

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

Remedy 4: Remove the Branch

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.

Key Points

  • 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.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally