Tournament Predictors, the Return Stack and the Bit Budget

S2.12 ended with two predictors, each good at other branches. This page lets them compete for every branch. It then repairs the one target that no table can remember, and counts what all of it costs.

You Will Be Able To

  • Explain how a chooser picks between two predictors, and when it changes its mind.
  • Follow a return stack through calls and returns, and say what a stack that is too small loses.
  • Count the bits of a predictor, part by part.
Lesson
S2.28
Time
30 min
Runs on
Your browser
Check
6 questions

A function is called from two places. Its return goes back to the first place, then to the second. A table that remembers the last target is wrong both times. Yet the core itself knows the answer: it saved the return address at the call.

Before You Start

You need the 2-bit table and gshare from S2.12, and the branch target buffer from S2.27.

You need calls, returns and the return address from S2.3, and a stack: the last thing put in is the first taken out.

Five questions this page answers
Question
1How does a tournament predictor decide which of its two predictors to use?
2When does a chooser move?
3Why is a branch target buffer bad at returns?
4What does a return stack hold, and what happens when it is full?
5Which part of a predictor costs the most bits?

The Idea: Let Them Compete, and Remember the Calls

Some branches want a plain counter, and some want history. So keep both predictors, and ask both. A third small table decides whose guess is used.

That third table holds a chooser for each entry. It is one more 2-bit counter. It counts towards the predictor that was right when the other was wrong. The whole thing is a tournament predictor.

The direction is now well served. One target is not: the target of a return. A function returns to wherever it was called from, and that changes from call to call.

The fix uses what a call already does. A call stores its return address. Let the fetch store it too, on a small stack of its own. This is the return stack.

A call puts its return address on the stack. That is a push. A return takes the newest address off again. That is a pop. Calls and returns come in pairs, so the popped address is the right target.

All these tables cost bits, and a chip has a limit for them. The sum of all stored bits is the bit budget of the predictor.

New Words

New words on this page
WordMeaning
Tournament predictorTwo predictors and a chooser that picks one of the two guesses for each branch.
ChooserA 2-bit counter that says which of two predictors to trust. It moves towards the one that was right alone.
Return stackA small stack beside the fetch that holds the return addresses of the calls that have not returned yet.
Bit budgetThe number of stored bits that a predictor may use, all tables together.

One Picture: Who Guesses What

Two Predictors, a Chooser, and Two Sources for the TargetStep through the picture. It shows how one guess is put together from five small memories.
  • Memory
  • Control / FSM
  • Processor
Two Predictors, a Chooser, and Two Sources for the TargetStep through the picture. It shows how one guess is put together from five small memories. component 2-bit table guesses from theaddress alone component gshare guesses from theaddress and the lastoutcomes component Chooser a 2-bit counter foreach entry: which ofthe two to trust component Branch targetbuffer the last target, and amark for a return component Return stack the return addressesof the calls that arestill open component Next PC a target, or the PCplus 4 guess 1guess 2taken?this is a returnthe last targetthe top address
  1. component 2-bit tableguesses from the address alone
    • guess 1 → Chooser
  2. component gshareguesses from the address and the last outcomes
    • guess 2 → Chooser
  3. component Choosera 2-bit counter for each entry: which of the two to trust
    • taken? → Next PC
  4. component Branch target bufferthe last target, and a mark for a return
    • this is a return → Return stack
    • the last target → Next PC
  5. component Next PCa target, or the PC plus 4
  6. component Return stackthe return addresses of the calls that are still open
    • the top address → Next PC
  1. Two guesses

    Both predictors are asked for every branch. Often they agree. Sometimes they do not.

  2. The chooser

    A third table holds a 2-bit counter for each entry. At 0 and 1 it passes on the guess of the plain table. At 2 and 3 it passes on the guess of gshare.

  3. The target of a branch or a call

    The branch target buffer gives the address where this instruction went the last time.

  4. The target of a return

    The buffer also remembers that an entry belongs to a return. Then the target is taken from the top of the return stack.

Read the diagram as text
  • 2-bit table: guesses from the address alone
  • gshare: guesses from the address and the last outcomes
  • Chooser: a 2-bit counter for each entry: which of the two to trust
  • Branch target buffer: the last target, and a mark for a return
  • Return stack: the return addresses of the calls that are still open
  • Next PC: a target, or the PC plus 4
  • 2-bit table → Chooser: guess 1
  • gshare → Chooser: guess 2
  • Chooser → Next PC: taken?
  • Branch target buffer → Return stack: this is a return
  • Branch target buffer → Next PC: the last target
  • Return stack → Next PC: the top address

The direction comes from a tournament of two predictors. The target comes from the target buffer, or for a return from the stack.

The parts of the predictor of this page, and their bits
PartSizeBits
2-bit table16 counters32
gshare16 counters and 4 history bits36
Choosers16 counters32
Branch target buffer32 entries of 59 bits: valid, a tag of 25 bits, a target of 32 bits, the mark for a return1888
Return stack4 addresses of 32 bits128
All together2116

The whole direction predictor is 100 bits: about 5 percent. The targets are the expensive part.

The Smallest Example, Worked by Hand

The program "calls" calls a function f from two places, at 10 and at 18. Then it calls a second function g, at 1c. Follow the stack.

The first calls and returns of "calls"
StepWhat happensThe stack after itThe return goes toThe target buffer would say
1the call at 10: push 1414
2f returns: popempty14nothing yet
3the call at 18: push 1c1c
4f returns: popempty1c14: wrong
5the call at 1c: push 2020
6g returns: popempty20nothing yet

The addresses are those of the recorded trace. In the next round, step 2 goes to 14 again, and the target buffer says 1c.

The return of f goes to 14 and to 1c in turn. The target buffer always holds the other one. The stack holds the right one, because the call just before put it there.

The Rules

  1. Rule 1: Both predictors guess for every branch, and both learn from every branch.

    The chooser only selects which guess is used.

  2. Rule 2: A chooser moves only when exactly one predictor was right.

    It counts towards that one. When both were right or both wrong, it stays.

  3. Rule 3: A call pushes the address behind it. A return pops.

    The popped address is the guess for the target of the return.

  4. Rule 4: The fetch must know that an instruction is a return.

    The branch target buffer marks the entry. So the first time a return is met, the stack is not used.

  5. Rule 5: A full stack loses its oldest address at the next push.

    A return that finds the stack empty falls back on the target buffer.

  6. Rule 6: Every stored bit counts against the budget.

    A target costs far more bits than a direction.

Sources for These Rules

Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.8. It describes tournament predictors: several predictors for a branch, and a selector that works like a 1-bit or 2-bit predictor and favours the one that was more accurate. Its section 4.11 lists a return stack of 8 entries in one real core. How a return stack is pushed and popped is not described in the books of this library. It is given here as commonly taught, and it is not checked against a source. The sizes, the fallback to the target buffer, and the rule that a full stack loses its oldest address are choices of this lab. The cycle counts are sums from the measured cycles of ap_rv32, which has none of these parts: 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. It holds the whole predictor of the picture and replays three recorded traces.

The first part follows the alternating branch at 0c of "pattern", and shows the tournament at work.

Printed by the lab on Icarus: the first 8 times of the branch at 0c. The counts equal those of a second model in JavaScript.
 n | did | table says | gshare says | chooser | tournament says
 1 | T   | N          | N           | 1       | N wrong
 2 | N   | T          | N           | 1       | T wrong
 3 | T   | N          | N           | 2       | N wrong
 4 | N   | T          | T           | 2       | T wrong
 5 | T   | N          | N           | 2       | N wrong
 6 | N   | T          | N           | 2       | N right
 7 | T   | N          | T           | 3       | T right
 8 | N   | T          | N           | 3       | N right

Rule 2 at work: read row 2. The table says taken and is wrong. gshare says not taken and is right. In row 3 the chooser has moved from 1 to 2.

From row 3 on the chooser passes on the guess of gshare. gshare is still warming up in rows 3 to 5. From row 6 on it is right, and so is the tournament.

Rule 1 at work: the plain table goes on learning, although nobody listens to it for this branch.

Right guesses of each predictor alone and of the tournament, out of all conditional branches.
trace   | branches | 2-bit table | gshare | tournament
loops   |      132 |         111 |    103 |        111
pattern |      160 |          77 |    139 |        147
calls   |       80 |          27 |     63 |         62

On "loops" the tournament equals the plain table. On "pattern" it is better than both of its parts: 147 against 77 and 139. It uses the table for one branch and gshare for another.

On "calls" it gets 62, one fewer than gshare alone. The choosers need a warm-up of their own.

The 60 returns of "calls": how many are fetched right without a return stack, and with one of depth 4.
the returns of calls, fetched right
stack depth | returns | right
          0 |      60 |    19
          4 |      60 |    58

Rules 3 and 4 at work: without the stack, 19 returns are right. Those are the returns of g, which has one caller. With the stack, 58 are right. Only the first time of each of the two returns is lost.

Cycles: measured on the real core ap_rv32, and as sums with the predictor of this page.
trace   | ap_rv32, measured | with the predictor | and the return stack
loops   |               515 |                329 |                  329
pattern |               554 |                362 |                  362
calls   |               813 |                603 |                  525

For "calls", the tournament and the target buffer bring 813 cycles down to 603. The return stack brings 603 down to 525. It makes 39 more returns right, and each saves 2 cycles.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Two predictors and a chooserOne larger predictorEach branch gets the kind of predictor that suits it. A third table, and a warm-up for it.
The chooser moves only when the two differ in being rightMove it after every branchIt measures which one is better, not how good both are. It learns nothing while the two agree.
A stack for returnsA larger target bufferA return gets the address of its own call. 128 bits here, and it must be told what is a call and what a return.
A full stack drops the oldest addressRefuse the pushThe newest calls return first, and they stay right. The outermost returns are lost.
Mark returns in the target bufferDecode the instruction firstThe guess is ready in IF. One more bit for each entry, and the first time is always missed.

None of this is in ap_rv32. Its fetch has no table at all, and the hand table above shows why a real fetch wants one.

The Trap: A Return Stack That Is Too Small

A fourth recorded program, "nest", has calls three deep. The main loop calls a function a from two places. a calls b, and b calls c.

The program "nest". Each function keeps its return address in another register while it calls on.
00          addi x5, x0, 6
04          addi x7, x0, 0
08  loop:   jal x1, a
0c          addi x7, x7, 16
10          jal x1, a
14          addi x5, x5, -1
18          bne x5, x0, loop
1c          ebreak
20  a:      addi x20, x1, 0
24          jal x1, b
28          addi x1, x20, 0
2c          jalr x0, 0(x1)
30  b:      addi x21, x1, 0
34          jal x1, c
38          addi x1, x21, 0
3c          jalr x0, 0(x1)
40  c:      addi x7, x7, 1
44          jalr x0, 0(x1)

Try stacks of several depths.

The lab on the trace "nest": returns fetched right for each stack depth, then the cycles with a depth of 4.
the returns of nest, fetched right
stack depth | returns | right
          0 |      36 |    22
          1 |      36 |    22
          2 |      36 |    22
          4 |      36 |    33
trace   | ap_rv32, measured | with the predictor | and the return stack
nest    |               310 |                196 |                  174

Without a stack, 22 of the 36 returns are right. With a stack of depth 1 or of depth 2: still 22. The stack seems to do nothing.

Rule 5 at work: the third call finds a stack of depth 2 full. The oldest address is lost, and that is the return address of a.

The returns of c and b then find their addresses. But those two never needed a stack: each has one caller. The return of a, the only one with two callers, finds the stack empty.

So the stack that is too small helps exactly the returns that needed no help. With a depth of 4, 33 returns are right, and 310 measured cycles become 174 in the sum.

At Scale

The predictor of this lab100 bits of direction, 1888 of targets, 128 of return stack
A phone core, as one textbook gives it6 kilobits for the direction, 256 entries for indirect targets, a return stack of 8

This section looks ahead. The predictor of this page has 2116 bits. Real ones are larger, and the proportions stay.

  1. Not on ap_rv32

    The core ap_rv32 has no predictor, no target buffer and no return stack. The cycles of the row "measured" are real. Every other cycle count on this page is a sum.

  2. How deep are real calls

    Real programs call much deeper than three. A stack of a few entries still helps, because the innermost calls return first and most often. That is common practice.

  3. Guessing ahead of the outcome

    A real fetch pushes and pops as it guesses. After a wrong guess the stack must be put right again. That is common practice, and not built here.

  4. The other jumps through a register

    A jalr that is not a return can go to many places, as in a switch statement. Real cores keep one more predictor for those.

Try It

Run the lab. In the first table, find the row in which the chooser first trusts gshare.

In the line that sets the chooser, remove the condition, so that it moves after every branch towards gshare being right. Which trace loses most?

Change the depth of the return stack in the last three replay lines from 4 to 1. Does any cycle count change? Why not, for these three programs?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: n | did | table says | gshare says | chooser | tournament says 1 | T | N | N | 1 | N wrong 2 | N | T | N | 1 | T wrong 3 | T | N | N | 2 | N wrong 4 | N | T | T | 2 | T wrong 5 | T | N | N | 2 | N wrong 6 | N | T | N | 2 | N right 7 | T | N | T | 3 | T right 8 | N | T | N | 3 | N right trace | branches | 2-bit table | gshare | tournament loops | 132 | 111 | 103 | 111 pattern | 160 | 77 | 139 | 147 calls | 80 | 27 | 63 | 62 the returns of calls, fetched right stack depth | returns | right 0 | 60 | 19 4 | 60 | 58 trace | ap_rv32, measured | with the predictor | and the return stack loops | 515 | 329 | 329 pattern | 554 | 362 | 362 calls | 813 | 603 | 525

Check Yourself

Predict the outputThe program "nest" runs 6 rounds. In each round a is called twice, a calls b, and b calls c: 36 returns in all. There are three different return instructions. This lab uses a return stack of depth 3. What does its last line say?
// Calls three deep, and a return stack that holds three addresses. 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_nest;   // the program "nest": 152 instructions, 78 branches and jumps
    count = 78;
    place_pc[0] = 32'h08;  place_target[0] = 32'h20;  place_kind[0] = 2'd1;   // call
    place_pc[1] = 32'h24;  place_target[1] = 32'h30;  place_kind[1] = 2'd1;   // call
    place_pc[2] = 32'h34;  place_target[2] = 32'h40;  place_kind[2] = 2'd1;   // call
    place_pc[3] = 32'h44;  place_target[3] = 32'h00;  place_kind[3] = 2'd2;   // return
    place_pc[4] = 32'h3c;  place_target[4] = 32'h00;  place_kind[4] = 2'd2;   // return
    place_pc[5] = 32'h2c;  place_target[5] = 32'h00;  place_kind[5] = 2'd2;   // return
    place_pc[6] = 32'h10;  place_target[6] = 32'h20;  place_kind[6] = 2'd1;   // call
    place_pc[7] = 32'h18;  place_target[7] = 32'h08;  place_kind[7] = 2'd0;   // branch
    return_target[0] = 32'h38;
    return_target[1] = 32'h28;
    return_target[2] = 32'h0c;
    return_target[3] = 32'h14;
    events[0 +: 320] = 320'h08785b49382818685a4938281808785b49382818685a4938281808785b49382818685a4938281808;   // events 0 to 39
    events[320 +: 304] = 304'h705b49382818685a4938281808785b49382818685a4938281808785b49382818685a49382818;   // events 40 to 77
  endtask

  // ---- The direction: two predictors, and a chooser for each entry that says which of them to trust.
  logic [1:0] plain [0:15];       // a 2-bit table
  logic [1:0] shared [0:15];      // gshare, with the last 4 outcomes
  int         recent;             // those outcomes, the newest in bit 0
  logic [1:0] chooser [0:15];     // 0 and 1: trust the plain table. 2 and 3: trust gshare
  // ---- The targets: a branch target buffer of 32 entries, and a stack of return addresses.
  logic        target_valid [0:31];
  logic [31:0] target_owner [0:31];   // the tag: the address that wrote the entry
  logic [31:0] target_value [0:31];
  logic        target_return [0:31];  // the entry was written by a return
  int          DEPTH;                 // how many return addresses the stack can hold; 0: no stack
  logic [31:0] stack [0:7];
  int          held;                  // how many it holds now

  function automatic logic [1:0] step(input logic [1:0] old, input logic up);
    if (up) return (old == 2'd3) ? 2'd3 : old + 2'd1;
    return (old == 2'd0) ? 2'd0 : old - 2'd1;
  endfunction
  function automatic string letter(input logic taken);
    return taken ? "T" : "N";
  endfunction

  int branches, right_plain, right_shared, right_both, returns, returns_right, saved, extra;
  task automatic replay(input int depth, input int follow, input int times);
    logic [7:0]  e;
    logic [31:0] pc, went, guess_target;
    logic        taken, says_plain, says_shared, says, known, goes, right;
    int p, a, b, t, seen;
    DEPTH = depth;
    for (int k = 0; k < 16; k++) begin plain[k] = 2'd1;  shared[k] = 2'd1;  chooser[k] = 2'd1; end
    for (int k = 0; k < 32; k++) target_valid[k] = 1'b0;
    recent = 0;  held = 0;  seen = 0;
    branches = 0;  right_plain = 0;  right_shared = 0;  right_both = 0;  returns = 0;  returns_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];
      a     = (pc / 4) % 16;
      b     = a ^ (recent % 16);
      t     = (pc / 4) % 32;
      // The guess of the direction: the chooser picks one of the two predictors.
      says_plain  = plain[a]  >= 2'd2;
      says_shared = shared[b] >= 2'd2;
      says        = (chooser[a] >= 2'd2) ? says_shared : says_plain;
      // The guess of the target. A return takes it from the stack, if the stack holds anything.
      known        = target_valid[t] && target_owner[t] == pc;
      guess_target = target_value[t];
      if (known && target_return[t] && DEPTH > 0 && held > 0) guess_target = stack[held - 1];
      goes  = known && ((place_kind[p] == 2'd0) ? says : 1'b1);
      right = goes ? (taken && guess_target == went) : !taken;
      if (taken && right) saved++;
      if (!taken && !right) extra++;
      if (place_kind[p] == 2'd2) begin returns++;  if (right) returns_right++; end
      if (place_kind[p] == 2'd0) begin
        branches++;
        if (says_plain  == taken) right_plain++;
        if (says_shared == taken) right_shared++;
        if (says        == taken) right_both++;
        if (p == follow) begin
          seen++;
          if (seen <= times) $display("%2d | %s   | %s          | %s           | %0d       | %s %s", seen, letter(taken), letter(says_plain), letter(says_shared), chooser[a], letter(says), says == taken ? "right" : "wrong");
        end
        // Learn. The chooser moves only when exactly one of the two was right: towards that one.
        if ((says_plain == taken) != (says_shared == taken)) chooser[a] = step(chooser[a], says_shared == taken);
        plain[a]  = step(plain[a], taken);
        shared[b] = step(shared[b], taken);
        recent    = (recent * 2 + taken) % 1024;
      end
      if (taken) begin target_valid[t] = 1'b1;  target_owner[t] = pc;  target_value[t] = went;  target_return[t] = (place_kind[p] == 2'd2); end
      // A call pushes the address behind it. A stack that is full loses its oldest address. A return pops.
      if (DEPTH > 0 && place_kind[p] == 2'd1) begin
        if (held == DEPTH) begin for (int k = 0; k < DEPTH - 1; k++) stack[k] = stack[k + 1];  held--; end
        stack[held] = pc + 32'd4;  held++;
      end
      if (DEPTH > 0 && place_kind[p] == 2'd2 && held > 0) held--;
    end
  endtask

  initial begin
    load_nest;
    $display("the returns of %s, fetched right", "nest");
    $display("stack depth | returns | right");
    replay(3, -1, 0);
    $display("%11d | %7d | %5d", DEPTH, returns, returns_right);
    $display("returns=%0d right=%0d", returns, returns_right);
    $finish;
  end
endmodule
ConceptThe plain table was right and gshare was wrong. What does the chooser do?
ConceptBoth predictors were wrong. What does the chooser do?
ConceptWhy is a branch target buffer bad at the return of a function with two callers?
ConceptA return stack of depth 2 meets calls three deep. Which return address is lost?
ConceptIn the predictor of this page, which part has the most bits?

Common Mistakes

Wrong Update only the predictor that the chooser picked.

The other one stops learning, and the chooser can never find out that it has become better.

Fix Let both learn from every branch.

Wrong Predict a return with the branch target buffer alone.

It holds where the function returned the last time. With two callers that is the wrong place.

Fix Push at each call, and pop at each return.

Wrong Size the return stack by the number of functions.

What counts is how many calls are open at the same time.

Fix Size it by the depth of the calls, and expect to lose the outermost returns beyond that.

Remember

  • A tournament predictor asks two predictors and lets a 2-bit chooser pick. The chooser moves only when exactly one of the two was right.
  • A return stack is pushed by a call and popped by a return. It finds return addresses that a target buffer cannot.
  • A full stack loses its oldest address. A stack that is too small loses the returns of the outermost calls.
  • Count every stored bit. Here the direction takes 100 bits and the targets 1888. For "calls": 813 cycles measured on ap_rv32, 525 as a sum with the whole predictor.

Practice

Report a problem with this page