arthrop0d

Brief articles on varied topics.

CPU Branch Predictors and Speculative Execution

performancecomputer science

A CPU branch predictor is hardware that guesses which way a conditional branch will go—and often where execution will continue—before the branch’s condition has been calculated. The processor uses that guess to keep fetching and executing instructions instead of waiting.

The problem: branches interrupt the instruction stream

Consider a loop with a conditional test:

for (int i = 0; i < n; i++) {
    if (items[i] > limit)
        count++;
}

At the if, the CPU may not yet know whether items[i] > limit is true. The value might still be coming from the cache or from an earlier instruction. Yet modern processors fetch and decode several instructions every cycle, often executing independent instructions out of order. If the processor waits for every branch result before fetching more instructions, much of that machinery sits idle.

A branch predictor fills this gap. It makes a likely choice, allowing the processor to continue down one path. The processor is then speculating: doing work based on an assumption that has not been confirmed.

Without prediction, a taken-or-not-taken branch can create a pipeline bubble, a cycle in which part of the processor has no useful instruction to process. Deeper pipelines and wider processors make these stalls more expensive, because more instruction-fetch and execution capacity is left unused.

What the history tables record

A predictor does not usually remember complete program traces. It stores compact evidence about earlier branches, especially their outcomes. For a conditional branch, an outcome is normally represented as taken—jump to the branch target—or not taken—continue with the next instruction.

The simplest useful record is a branch history register, a small bit field containing recent outcomes. For example, after the outcomes taken, taken, not taken, taken, the history might be 1101. Some processors keep history for each branch, called local history. Others keep one history shared across many branches, called global history. Local history captures a branch’s own repeating pattern; global history can capture relationships between branches, such as an error check that tends to follow a successful validation.

The history bits are used to select an entry in a pattern history table (PHT). A PHT is an array of small prediction records, commonly two-bit saturating counters. A counter has four states, ranging from strongly not taken to strongly taken. It moves one step toward taken after a taken outcome and one step toward not taken after a not-taken outcome, stopping at either extreme.

Two bits matter because one unusual result should not immediately reverse a stable prediction. A loop-closing branch, for example, is taken many times and then not taken once when the loop ends. A two-bit counter can predict the repeated taken outcomes and tolerate that one exit without permanently changing its expectation.

The table is indexed rather than searched by the full address and history. A predictor may combine some bits of the branch’s address with global or local history; designs use different combinations. Because the table is finite, unrelated branches can map to the same entry. This aliasing means one branch can partly train a record used by another, reducing accuracy.

The history table normally predicts direction, not the destination address. A separate structure called a branch target buffer (BTB) caches the address that a taken branch is expected to jump to. The processor can therefore predict both “taken” and “fetch instructions starting at this address.” Some predictors also have specialized structures for indirect branches, whose destination can vary among several addresses.

How speculation uses the prediction

When the instruction fetch unit reaches a branch, the predictor supplies a direction and, when needed, a target. Fetch continues from that predicted location. The processor decodes those instructions and may execute them before the original branch has finished calculating its condition.

The results are kept in temporary processor state rather than immediately becoming permanent program-visible state. In an out-of-order CPU, instructions wait in structures such as a reorder buffer, which tracks them until they can be completed in the original program order. This lets the CPU exploit independent work while preserving the behavior the program requires.

Eventually, the branch’s real condition is evaluated. The processor compares the actual result with the prediction:

Discarding this wrong-path work is often called a pipeline flush, although the exact recovery process varies by processor. Work that changed only temporary internal state is abandoned. The CPU must still preserve the defined behavior of the program; speculation does not let an incorrect path commit ordinary register or memory results as if it had really run.

Why a misprediction costs performance

A correct prediction saves time because fetching and executing continue without interruption. A misprediction costs performance in several ways:

  1. The processor spends cycles executing or preparing instructions that will be discarded.
  2. The fetch unit must stop following the wrong path and find the correct instruction address.
  3. The front end must refill its fetch, decode and scheduling queues with instructions from the correct path.
  4. Useful instructions behind the branch may have been delayed by wrong-path work competing for execution resources.

The cost is therefore not just the time needed to evaluate the condition. It is the time to detect the mistake and restart useful progress, often measured as several to dozens of cycles depending on the processor and branch location. A misprediction inside a tight, frequently executed loop can have a noticeable effect even when each individual penalty is small.

This is why performance tools and CPU documentation report branch-miss or branch-misprediction counters. They do not mean the program produced a wrong result. They mean the hardware guessed the control-flow direction incorrectly and had to recover. Predictable branches—such as a loop that usually continues—are cheap for the CPU to handle. Branches with irregular, data-dependent outcomes train the history tables poorly, causing more flushes and reducing the benefit of speculative execution.

← All articles