Questions tagged [branch-prediction]

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Why is it faster to process a sorted array than an unsorted array? Stack Overflow's highest-voted question and answer is a good introduction to the subject.


In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline.

Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Two-way branching is usually implemented with a conditional jump instruction. A conditional jump can either be "not taken" and continue execution with the first branch of code which follows immediately after the conditional jump - or it can be "taken" and jump to a different place in program memory where the second branch of code is stored.

It is not known for certain whether a conditional jump will be taken or not taken until the condition has been calculated and the conditional jump has passed the execution stage in the instruction pipeline.

Without branch prediction, the processor would have to wait until the conditional jump instruction has passed the execute stage before the next instruction can enter the fetch stage in the pipeline. The branch predictor attempts to avoid this waste of time by trying to guess whether the conditional jump is most likely to be taken or not taken. The branch that is guessed to be the most likely is then fetched and speculatively executed. If it is later detected that the guess was wrong then the speculatively executed or partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay.

The time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good branch predictor.

Source: http://en.wikipedia.org/wiki/Branch_predictor


The Spectre security vulnerability revolves around branch prediction:


Other resources

Special-purpose predictors: Return Address Stack for call/ret. ret is effectively an indirect branch, setting program-counter = return address. This would be hard to predict on its own, but calls are normally made with a special instruction so modern CPUs can match call/ret pairs with an internal stack.

Computer architecture details about branch prediction / speculative execution, and its effects on pipelined CPUs

  • Why is it faster to process a sorted array than an unsorted array?
  • Branch prediction - Dan Luu's article on branch prediction, adapted from a talk. With diagrams. Good introduction to why it's needed, and some basic implementations used in early CPUs, building up to more complicated predictors. And at the end, a link to TAGE branch predictors used on modern Intel CPUs. (Too complicated for that article to explain, though!)
  • Slow jmp-instruction - even unconditional direct jumps (like x86's jmp) need to be predicted, to avoid stalls in the very first stage of the pipeline: fetching blocks of machine code from I-cache. After fetching one block, you need to know which block to fetch next, before (or at best in parallel with) decoding the block you just fetched. A large sequence of jmp next_instruction will overwhelm branch prediction and expose the cost of misprediction in this part of the pipeline. (Many high-end modern CPUs have a queue after fetch before decode, to hide bubbles, so some blocks of non-branchy code can allow the queue to refill.)
  • Branch target prediction in conjunction with branch prediction?
  • What branch misprediction does the Branch Target Buffer detect?

Cost of a branch miss


Modern TAGE predictors (in Intel CPUs for example) can "learn" amazingly long patterns, because they index based on past branch history. (So the same branch can get different predictions depending on the path leading up to it. A single branch can have its prediction data scattered over many bits in the branch predictor table). This goes a long way to solving the problem of indirect branches in an interpreter almost always mispredicting (X86 prefetching optimizations: "computed goto" threaded code and Branch prediction and the performance of interpreters — Don't trust folklore), or for example a binary search on the same data with the same input can be really efficient.

Static branch prediction on newer Intel processors - according to experimental evidence, it appears Nehalem and earlier do sometimes use static prediction at some point in the pipeline (backwards branches default to predicted-taken, forward to not-taken.) But Sandybridge and newer seem to be always dynamic based on some history, whether it's from this branch or one that aliases it. Why did Intel change the static branch prediction mechanism over these years?

Cases where TAGE does "amazingly" well


Assembly code layout: not so much for branch prediction, but because not-taken branches are easier on the front-end than taken branches. Better I-cache code density if the fast-path is just a straight line, and taken branches mean the part of a fetch block after the branch isn't useful.

Superscalar CPUs fetch code in blocks, e.g. aligned 16 byte blocks, containing multiple instructions. In non-branching code, including not-taken conditional branches, all of those bytes are useful instruction bytes.


Branchless code: using cmov or other tricks to avoid branches

This is the asm equivalent of replacing if (c) a=b; with a = c ? b : a;. If b doesn't have side-effects, and a isn't a potentially-shared memory location, compilers can do "if-conversion" to do the conditional with a data dependency on c instead of a control dependency.

(C compilers can't introduce a non-atomic read/write: that could step on another thread's modification of the variable. Writing your code as always rewriting a value tells compilers that it's safe, which sometimes enables auto-vectorization: AVX-512 and Branching)

Potential downside to cmov in scalar code: the data dependency can become part of a loop-carried dependency chain and become a bottleneck, while branch prediction + speculative execution hide the latency of control dependencies. The branchless data dependency isn't predicted or speculated, which makes it good for unpredictable cases, but potentially bad otherwise.

363 questions
0
votes
1 answer

Branch prediction and performance

I'm reading a book about computer architecture and I'm on this chapter talking about branch prediction. There is this little exercise that I'm having a hard time wrapping my head around it. Consider the following inner for loop for (j = 0; j < 2;…
0
votes
1 answer

Is generic list construction ignored if the instance already exists?

I've got this code: if (null == _priceComplianceSummaryList) { _priceComplianceSummaryList = new List(); } Resharper flags it as an issue, suggesting, "Replace 'if' statement with respective branch" If I acquiesce, the…
0
votes
1 answer

how to run c code with simplescalar?

I want to simulate perceptron branch predictor with simplescalar. I write a simple code in c programming language. In simplescalar installation guide this command will compile c code: $ $IDIR/bin/sslittle-na-sstrix-gcc –o hello hello.c but I don't…
zara-T
  • 91
  • 11
0
votes
1 answer

Predicting branches

Assume that a processor has a feature that enables the compilier to specify the initial prediction state as either LT or LNT for a branch instruction. Consider a statement of the form IF A > B THEN A = A + 1 ELSE B = B + 1 (a) Generate…
0
votes
1 answer

MIPS - Branching convention with bne

In lecture, our professor said that there is a reason behind using bne in branching rather than using beq(and left us to figure it out), like the example shown below. if ( i == j ) i++ ; j-- ; which compiles down to bne $r1, $r2, L1 #…
Burak.
  • 598
  • 7
  • 19
0
votes
1 answer

Writing small benchmark tests

I'm buying a new PC. That's great, but I'd like to know how much faster it is. Now I could use an already established benchmark - BUT I want to learn WHY it is faster. So my idea was to: 1. write small benchmarks to test very specific stuff 2.…
user45891
  • 780
  • 6
  • 17
0
votes
1 answer

Confused by simplescalr preditor

now I am learning simplescalar source code. But I am confused by the predictor module. It is about bimod predictor. Here is the initialization : case BPred2bit: if (!l1size || (l1size & (l1size-1)) != 0) fatal("2bit table size, `%d', must…
0
votes
1 answer

Testing program for Branch Predictor in Java Have odd result

I read the question Why is it faster to process a sorted array than an unsorted array? today and trying to replicate the result in Java. Here's my code: public class BranchPredictorTest { static int[] getBranchCounts1(List list) { …
Fog Rain
  • 11
  • 3
0
votes
1 answer

What effect will branch prediction have on the following C loop?

My experience with C is relatively modest, and I lack good understanding of its compiled output on modern CPUs. The context: I'm working on image processing for an Android app. I have read that branch-free machine code is preferred for inner loops,…
0
votes
1 answer

What causes spike in branch predictions Vtune

I am launching an application using VTune and profiling it. Once the test is run, I see a spike in branch prediction unit. To optimize my application, I need to figure out what part of the code causes this spike. Is there a way through VTune I can…
user782400
  • 1,617
  • 7
  • 30
  • 51
0
votes
3 answers

Minimize function selection and function call overhead?

I have a large array (image) and I need to do many small configurable computations on that data. I'll post an example here. NOTE: This is not the actual problem, but a minimal / hopefully illustrative example of what I need to do. // different…
S.H
  • 875
  • 2
  • 11
  • 27
0
votes
0 answers

What switches/options force CL (Microsoft C/C++ compiler) to produce "fragmented" procedures?

In the majority of cases a compiled procedure is a bunch of processor instructions that occupies continuous range of bytes in the code section. It of course may contain conditional and unconditional jumps and non-linear execution flow, but looking…
0
votes
0 answers

Are popular processors known to "optimize away" instructions that branch to the next instruction?

I'm reviewing disassembly of some program in Visual Studio and see the following: 001B1015 cmp ebx, edx 001B1017 jae wmain+19h (001B1019h) 001B1019 pop esi This code is just dumb. If jae causes a conditional jump…
sharptooth
  • 167,383
  • 100
  • 513
  • 979
0
votes
0 answers

Which processors are better?

Why computer architects pay more attention on the accuracy of a branch predictor of a dynamic out-of-order processor than a branch predictor of a simple 5-stage in-order processor?
Libathos
  • 3,340
  • 5
  • 36
  • 61
0
votes
0 answers

How can unconditional branches be predicted with a 2-bit predictor?

I found: (Sandy Bridge) Pattern recognition for indirect jumps and calls Indirect jumps and indirect calls (but not returns) are predicted using the same two-level predictor as branch instructions. here on page…
intrigued_66
  • 16,082
  • 51
  • 118
  • 189