The Branch Target Buffer: Index, Tag and Aliasing

A guess of "taken" is worth nothing while the fetch does not know where to go. This page gives the fetch a table of targets, and finds out what happens when the tables are small.

You Will Be Able To

  • Explain why a prediction needs a target in IF, and what a branch target buffer stores.
  • Work out which entry of a table an address uses.
  • Say what aliasing does to a counter, and why the target buffer has a tag.
Lesson
S2.27
Time
30 min
Runs on
Your browser
Check
6 questions

S2.11 counted right guesses. A right guess saves cycles only if the next fetch goes to the right address. In IF the branch is not even decoded. So the target must come from a memory of earlier runs.

Before You Start

You need the 2-bit counter from S2.11, and the penalty of 2 cycles from S2.10.

You need the idea of a cache from S0.7: a small memory that keeps what was used before.

Five questions this page answers
Question
1Why is a right guess of "taken" not enough?
2What does an entry of a branch target buffer hold?
3Which bits of an address choose the entry?
4What happens when two branches use the same counter?
5Why does the target buffer need a tag, and the counter table none?

The Idea: Remember Where It Went

The fetch must pick the next address at the end of IF. If the guess is taken, it needs the target then. But the target adder is in EX.

So remember the target too. When a branch or a jump leaves the line, store where it went. Next time the same address is fetched, look it up. This table is the branch target buffer, or BTB.

A table has a fixed number of entries. An address uses one of them, chosen by a few of its low bits. Those bits are the index.

Many addresses have the same index. For a counter that is tolerable: a wrong guess is only a wasted flush. Two branches that push one counter are said to alias.

For a target it is not tolerable. An entry written by one branch must not move the PC for another instruction. So each entry also stores which address wrote it. That stored address is the tag.

The PC is moved only when the counter says taken and the tag equals the address. Everything else is fetched in line, exactly as before.

New Words

New words on this page
WordMeaning
Branch target buffer (BTB)A small table that remembers, for an address, where the branch or jump at that address went.
IndexThe low bits of an address that choose the entry of a table.
TagWhat an entry stores to say which address wrote it. Here: the whole address.
HitA lookup that finds a valid entry whose tag equals the address. Anything else is a miss.
AliasingTwo branches with the same index use the same entry, and each changes what the other reads.
Counter tableA table of 2-bit counters with no tag, read with the index.

One Picture: A Counter and a Target for the Same Address

Two Tables Beside the PCStep through the picture. It follows one fetch of the lab: the inner loop branch of "loops", at address 1c, with tables of eight entries.
  • Processor
  • Memory
  • Control / FSM
Two Tables Beside the PCStep through the picture. It follows one fetch of the lab: the inner loop branch of "loops", at address 1c, with tables of eight entries. component PC the address of theinstruction in IF: 1c component Counter table eight 2-bit counters,no tag component Branch targetbuffer eight entries: valid,tag, target component Tag compare does the entry belongto this address? component Next PC the target, or the PCplus 4 index: bits 4 to 2index: bits 4 to 2the stored tagtaken?hit, with the target
  1. component PCthe address of the instruction in IF: 1c
    • index: bits 4 to 2 → Counter table
    • index: bits 4 to 2 → Branch target buffer
  2. component Counter tableeight 2-bit counters, no tag
    • taken? → Next PC
  3. component Branch target buffereight entries: valid, tag, target
    • the stored tag → Tag compare
  4. component Tag comparedoes the entry belong to this address?
    • hit, with the target → Next PC
  5. component Next PCthe target, or the PC plus 4
  1. The index

    The address is 1c. Divided by 4 that is 7. With eight entries, both tables are read at entry 7.

  2. The counter

    The counter of entry 7 holds 3. It says taken. It cannot say whose counter it is.

  3. The tag

    The target entry holds a tag. It is compared with the address 1c. They are equal: the entry was written by this branch. That is a hit.

  4. The next PC

    Taken, and a hit: the next PC is the stored target, 0c. All of this happened in IF, before the instruction was even decoded.

Read the diagram as text
  • PC: the address of the instruction in IF: 1c
  • Counter table: eight 2-bit counters, no tag
  • Branch target buffer: eight entries: valid, tag, target
  • Tag compare: does the entry belong to this address?
  • Next PC: the target, or the PC plus 4
  • PC → Counter table: index: bits 4 to 2
  • PC → Branch target buffer: index: bits 4 to 2
  • Branch target buffer → Tag compare: the stored tag
  • Counter table → Next PC: taken?
  • Tag compare → Next PC: hit, with the target

A guess moves the PC only when both tables agree: the counter says taken, and the target buffer has a target for this very address.

What each table stores in an entry
TableAn entry holdsBits, with 8 entriesWhen two addresses share the entry
Counter tablea 2-bit counter2both push the same counter
Branch target buffera valid bit, a tag of 27 bits, a target of 32 bits60the newer one replaces the older; the older then misses

With 8 entries the index is 3 bits. An address has 30 bits above bits 1 and 0, so 27 of them are left for the tag.

The Smallest Example, Worked by Hand

The program "loops" has three branches, at the addresses 0c, 1c and 24 in hex. Which entry does each use?

Bits 1 and 0 of an instruction address are always 0. So first divide the address by 4. Then keep the remainder of a division by the number of entries.

The entry of each branch
AddressDivided by 4With 4 entriesWith 8 entries
0c333
1c737
24911

With 4 entries, the branches at 0c and 1c alias. With 8 entries each branch has an entry of its own.

With 4 entries, the two branches share one counter and one target entry. The counter survives that, because both branches are mostly taken.

The target entry does not. Each of the two writes its own target and its own tag. The other one then finds a tag that is not its own: a miss.

The Rules

  1. Rule 1: A guess of taken needs a target in IF.

    The branch target buffer gives it. Without a hit, the fetch stays in line, whatever the counter says.

  2. Rule 2: The entry of an address is given by its low bits, without bits 1 and 0.

    With 8 entries those are bits 4 to 2.

  3. Rule 3: The target buffer is written when a branch or a jump leaves the line.

    It stores the tag and the target. A jump needs no counter: it always leaves.

  4. Rule 4: A target is used only when the tag equals the address.

    So an entry written by another instruction never moves the PC.

  5. Rule 5: Counters have no tag.

    Branches that alias push one counter. That can make a guess worse, and now and then better.

  6. Rule 6: A wrong guess costs a flush, and a right one saves it.

    Sending a branch to a target when it is not taken costs 2 cycles that the plain core would not have lost.

Sources for These Rules

Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.8. The prediction buffer is indexed by the low bits of the address. Another branch with the same low bits may have written the entry, and that does not harm correctness. A predictor still needs the target, which a branch target buffer holds, organized like a cache with tags. Harris and Harris (ARM edition), section 7.7.3, puts the predictor in the fetch stage. The sizes of the tables, the full address as the tag, and writing the target buffer on every taken branch are choices of this lab. The cycle counts are sums from the measured cycles of ap_rv32, which has no such tables: docs/soc/ap_rv32-blueprint.md, sections 8.4 and 14.2.

Now Run It

The lab at the end of this page is test code again. It replays the recorded branches and jumps with a counter table and a target buffer of the same size.

The first part uses the program "calls" and tables of 4 entries. It compares each branch with a counter of its own.

Printed by the lab on Icarus. The counts equal those of a second model in JavaScript.
calls with tables of 4 entries
branch | entry | times | right with its own counter | right with the table
30     |     0 |    40 |                          0 |                    0
54     |     1 |    20 |                          9 |                   10
24     |     1 |    20 |                         18 |                   16

Rule 2 at work: the branches at 54 and 24 both use entry 1. The branch at 30 has entry 0 for itself.

Rule 5 at work: the branch at 24 ends a loop and is taken 19 times in 20. Alone it is guessed right 18 times. Sharing a counter with the branch at 54, it gets 16.

The branch at 54 follows a scrambled number. It gains one right guess from the sharing. Aliasing is not always a loss.

The second part uses "loops". It replays the trace once for each table size and counts the cycles.

The row "none" is the real core ap_rv32: its cycles are measured. The other rows are sums from that measurement.
loops: the counters and the targets in tables of the same size
entries | branches right | next fetch right | cycles
   none |             18 |               18 |    515
      1 |            114 |               20 |    511
      2 |            114 |               20 |    511
      4 |            111 |               38 |    475
      8 |            111 |              111 |    329
     16 |            111 |              111 |    329

Read the row for 1 entry. The one counter is right 114 times in 132. But only 20 next fetches are right, and 4 cycles are saved.

Rules 3 and 4 at work: three branches write one target entry in turn. Each finds the tag of another, and misses. A right direction without a target saves nothing.

With 4 entries, the branches at 0c and 1c still fight for entry 3. With 8 entries nobody shares: 111 next fetches are right.

Rule 6 at work: 111 taken branches are fetched right, and each saves 2 cycles. 18 branches that are not taken were sent to a target, and each costs 2. 515 minus 222 plus 36 is 329.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A table of targets, read in IFWork out the target in IDA right guess loses no cycle at all. An entry costs about 60 bits here.
A tag in the target bufferNo tagAn add or a load is never sent to a target. The tag is most of the entry, and it needs a comparator.
No tag in the counter tableA tag for each counterTwo bits for each entry. Branches that alias disturb each other.
Index with the low bitsIndex with the high bitsBranches that are close together get different entries. Branches far apart may alias.
Write a target only when the branch left the lineWrite for every branchA branch that is never taken uses no entry. The first taken time is always a miss.

A guess is only a hint. The branch is still decided in EX, as before, and a wrong guess is flushed there. So no table can make the program wrong. It can only make it slow.

The Trap: A Right Guess with Nowhere to Go

Suppose the counters are built first, and the table of targets is left for later. The lab has a switch named TARGETS for that. At 0, only the counters work.

The lab with sixteen counters and no table of targets.
loops: the counters and the targets in tables of the same size
entries | branches right | next fetch right | cycles
   none |             18 |               18 |    515
     16 |            111 |               18 |    515

The counters guess 111 of 132 branches right. The cycle count is 515, the same as with no predictor at all.

The reason is in the column between. Only 18 next fetches are right: the 18 branches that are not taken. For every taken branch the fetch had no target, so it went on in line.

An accuracy figure for the direction alone says little about speed. Count the fetches that went to the right address.

The second trap is a table that is too small. Put every branch of "calls" into one entry.

The program "calls" with tables of one entry.
calls with tables of 1 entries
branch | entry | times | right with its own counter | right with the table
30     |     0 |    40 |                          0 |                   16
54     |     0 |    20 |                          9 |                   10
24     |     0 |    20 |                         18 |                    7

The loop branch at 24 falls from 18 right guesses to 7. The alternating branch at 30 rises from 0 to 16. One counter now holds a mixture of three habits.

At Scale

This lab, 8 entries16 bits of counters, 480 bits of targets: 515 cycles become 329
A core for phonesthousands of bits for the direction, hundreds of entries for targets

This section looks ahead. The tables of this lab have at most 16 entries. Real ones are sized by the number of branches a program keeps meeting.

  1. Not measured on ap_rv32

    The core ap_rv32 has no predictor. The 515 cycles are measured. The 329 are a sum, with the measured penalty of 2 cycles.

  2. A real core

    One textbook describes a phone core, the Cortex-A53. Its conditional predictor has 6 kilobits. It adds an indirect predictor of 256 entries, and a stack of 8 return addresses.

  3. Returns defeat the target buffer

    A return goes to a different address after each call. The stored target is the last one, and it is often wrong. S2.28 adds a small stack for that.

  4. Shorter tags

    Real target buffers often store only a part of the address as the tag. That saves bits and allows a rare false hit. It is common practice.

Try It

Run the lab. In the lower table, compare the rows for 4 and for 8 entries. Which two branches stop sharing?

Set TARGETS to 0 and run again. Which column of the lower table changes, and which does not?

In the first part, change replay(4) to replay(8). Which branches of "calls" still share an entry? Work it out by hand first.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: calls with tables of 4 entries branch | entry | times | right with its own counter | right with the table 30 | 0 | 40 | 0 | 0 54 | 1 | 20 | 9 | 10 24 | 1 | 20 | 18 | 16 loops: the counters and the targets in tables of the same size entries | branches right | next fetch right | cycles none | 18 | 18 | 515 1 | 114 | 20 | 511 2 | 114 | 20 | 511 4 | 111 | 38 | 475 8 | 111 | 111 | 329 16 | 111 | 111 | 329

Check Yourself

Predict the outputThe program "pattern" has 160 branches and no jumps. 51 of the branches are not taken, and the real core needs 554 cycles. Sixteen counters guess 77 of the branches right. This lab has those counters and no table of targets. What does its last line say?
// The program "pattern": sixteen counters, and no table of targets. What does the last line say?
// Test code. It replays the branches that the real core ap_rv32 executed, and counts how often a way of
// guessing would have been right. The core ap_rv32 itself has no such logic: it always fetches on in line.
module tb;
  // ---- The recorded traces. Each is every branch and jump that the real core ap_rv32 executed for one
  // program, in order. One byte for each: bits 7:4 the place (a row of the table of places), bit 3 "it left
  // the line" (a taken branch, or any jump), bits 2:0 which target (used by a return only).
  // In each line of a trace, the first event is the byte at the right-hand end of the number.
  logic [1599:0] events;
  int          count;                 // how many events the trace has
  logic [31:0] place_pc [0:15];       // the address of the branch or jump
  logic [31:0] place_target [0:15];   // where it goes when it leaves the line (not used for a return)
  logic [1:0]  place_kind [0:15];     // 0: a conditional branch. 1: a jal. 2: a return (jalr)
  logic [31:0] return_target [0:7];   // the addresses that the returns of this trace go to
  task automatic load_pattern;   // the program "pattern": 332 instructions, 160 branches and jumps
    count = 160;
    place_pc[0] = 32'h0c;  place_target[0] = 32'h14;  place_kind[0] = 2'd0;   // branch
    place_pc[1] = 32'h18;  place_target[1] = 32'h20;  place_kind[1] = 2'd0;   // branch
    place_pc[2] = 32'h20;  place_target[2] = 32'h28;  place_kind[2] = 2'd0;   // branch
    place_pc[3] = 32'h2c;  place_target[3] = 32'h08;  place_kind[3] = 2'd0;   // branch
    events[0 +: 320] = 320'h38201800382810083828180038201808382018003828100838281800382018083820180038281008;   // events 0 to 39
    events[320 +: 320] = 320'h38281800382018083820180038281008382818003820180838201800382810083828180038201808;   // events 40 to 79
    events[640 +: 320] = 320'h38201800382810083828180038201808382018003828100838281800382018083820180038281008;   // events 80 to 119
    events[960 +: 320] = 320'h30281800382018083820180038281008382818003820180838201800382810083828180038201808;   // events 120 to 159
  endtask

  // ---- Two tables with ENTRIES entries each. An address uses the entry given by its low bits.
  localparam bit TARGETS = 0;   // 1: the table of targets is used. 0: only the counters
  int          ENTRIES;                // set before each replay: 1, 2, 4, 8 or 16
  logic [1:0]  counter [0:15];         // a 2-bit counter in each entry; it starts at 1
  logic [1:0]  own [0:15];             // for comparison: a counter for each branch alone
  logic        target_valid [0:15];    // the table of targets: this entry holds something
  logic [31:0] target_owner [0:15];    // the tag: the address of the branch or jump that wrote the entry
  logic [31:0] target_value [0:15];    // where that branch or jump went
  function automatic int entry_of(input logic [31:0] pc);
    return (pc / 4) % ENTRIES;         // bits 1 and 0 of an instruction address are always 0
  endfunction
  function automatic logic [1:0] step(input logic [1:0] old, input logic taken);
    if (taken) return (old == 2'd3) ? 2'd3 : old + 2'd1;
    return (old == 2'd0) ? 2'd0 : old - 2'd1;
  endfunction

  int branches, branches_right, fetches, fetches_right, saved, extra;
  int times [0:15], own_right [0:15], table_right [0:15];
  task automatic replay(input int entries);
    logic [7:0]  e;
    logic [31:0] pc, went;
    logic        taken, says_taken, has_target, goes, right;
    int p, n;
    ENTRIES = entries;
    for (int k = 0; k < 16; k++) begin counter[k] = 2'd1;  own[k] = 2'd1;  target_valid[k] = 1'b0;  times[k] = 0;  own_right[k] = 0;  table_right[k] = 0; end
    branches = 0;  branches_right = 0;  fetches = 0;  fetches_right = 0;  saved = 0;  extra = 0;
    for (int i = 0; i < count; i++) begin
      e     = events[8 * i +: 8];
      p     = e[7:4];
      taken = e[3];
      pc    = place_pc[p];
      went  = (place_kind[p] == 2'd2) ? return_target[e[2:0]] : place_target[p];
      n     = entry_of(pc);
      // The guess, made in IF: the direction from the counter, the target from the table of targets.
      says_taken = (place_kind[p] == 2'd0) ? (counter[n] >= 2'd2) : 1'b1;   // a jump always leaves the line
      has_target = TARGETS && target_valid[n] && target_owner[n] == pc;
      goes       = says_taken && has_target;                               // without a target the fetch stays in line
      right      = goes ? (taken && target_value[n] == went) : !taken;
      fetches++;
      if (right) fetches_right++;
      if (taken && right) saved++;       // on the real core this cost 2 cycles
      if (!taken && !right) extra++;     // on the real core this cost nothing
      if (place_kind[p] == 2'd0) begin
        branches++;  times[p]++;
        if (says_taken == taken) begin branches_right++;  table_right[p]++; end
        if ((own[p] >= 2'd2) == taken) own_right[p]++;
        counter[n] = step(counter[n], taken);
        own[p]     = step(own[p], taken);
      end
      // The table of targets learns from everything that left the line.
      if (taken) begin target_valid[n] = 1'b1;  target_owner[n] = pc;  target_value[n] = went; end
    end
  endtask

  initial begin
    load_pattern;
    $display("%s: the counters and the targets in tables of the same size", "pattern");
    $display("entries | branches right | next fetch right | cycles");
    replay(16);   // only to count the events; the row of the real core needs no table
    $display("   none | %14d | %16d | %6d", branches - 109, fetches - 109, 554);
    replay(16);
    $display("%7d | %14d | %16d | %6d", ENTRIES, branches_right, fetches_right, 554 - 2 * saved + 2 * extra);
    $display("branches right=%0d next fetch right=%0d cycles=%0d", branches_right, fetches_right, 554 - 2 * saved + 2 * extra);
    $finish;
  end
endmodule
ConceptWhat does an entry of the branch target buffer of this page hold?
ConceptA table has 8 entries. Which entry does the address 2c in hex use?
ConceptTwo branches alias in the counter table. What can go wrong?
ConceptWhy does the target buffer store a tag?
ConceptWith tables of 8 entries, "loops" takes 329 cycles in the sum of this page, against 515 measured. Where do the saved cycles come from?

Common Mistakes

Wrong Judge a predictor by the directions it guesses right.

Without a target, a guess of taken cannot move the PC.

Fix Count the next fetches that went to the right address.

Wrong Leave the tag out of the target buffer to save bits.

Then any instruction with the same index is sent to the stored target, also an add or a load.

Fix Store a tag, and use the target only on a hit.

Wrong Use the whole address to choose the entry.

Bits 1 and 0 are always 0. Half of the index bits would be wasted, and only every fourth entry would be used.

Fix Start the index at bit 2.

Remember

  • A guess of taken needs a target in IF. The branch target buffer remembers where a branch or jump went.
  • The entry of an address is given by its low bits, from bit 2 up.
  • Counters have no tag, so branches alias. The target buffer has a tag, so a target is used only for the address that wrote it.
  • For "loops": 515 cycles measured on ap_rv32; 329 as a sum with tables of 8 entries; still 515 with counters and no targets.

Practice

Report a problem with this page