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

__builtin_expect - how to determine if this does anything for my processor?

I understand what this does: Built-in Function: long __builtin_expect (long exp, long c) but I don't know how to determine if this actually has any effect on my processor. Would this show up in the assembly?
Bob
  • 4,576
  • 7
  • 39
  • 107
0
votes
1 answer

How does branch prediction speed up anything?

If I have the following structure: if( condition() ){ doA(); } else { doB(); } then how does branch prediction help me? Even if branch A is predicted correctly, then I still need to evaluate doA() and condition() - just not in this order.…
0
votes
1 answer

Why branch predictor cannot be trained in another process.

In the Spectre variant 2, the branch target buffer (BTB) can be poisoned in another process. If the branch predictor is also using the virtual address to index the branch, why we can not train the branch predictor like training BTB in Spectre v1…
winter
  • 51
  • 4
0
votes
1 answer

Can I implement Branch target buffer in two stage pipelined RISC architecture?

I am trying to implement the BTB in low-level microcontroller such as PIC16. I don't know is it feasible or not. So wanted your suggestion. Thanks.
0
votes
1 answer

Is there a loop construct that repeats n times without calculating some conditional?

This question arose out of the context of optimizing code to remove potential branch prediction failures.. in fact, removing branches all together. For my example, a typical for-loop uses the following syntax: #include #include…
0
votes
1 answer

Is there any case where the Bimodal will be better than Not take?

Considering these two methods: Dynamic Bimodal: Where we have 4 stages, 2 stages for each (taken or not taken), and alternating every time the algorithm predicts wrong, changing from taken<->not taken after 2 consecutive wrong…
0
votes
1 answer

branch prediction, and optimized code

I have following set of code blocks, the purpose of the both block is same. I had to implement the 2nd block to avoid inverse logic and to increase the readability. BTW, in the production code the condition is very complex. The question is - I know…
0
votes
1 answer

Why short circuit logical operator is supposed to be faster

This question is not about optimizing code, but its a technical question about performance difference of short circuit logical operators and normal logical operators which may go down to how they are performed on hardware level. Basically logical…
0
votes
1 answer

ARM Branch Prediction based on code

so I'm trying to study for this test and one of the things on the study guide gives us some ARM Code and tells us to fill in a branch prediction table based on how the code runs. I can understand how I'm supposed to do it, but with branch…
PCRevolt
  • 129
  • 1
  • 1
  • 8
0
votes
1 answer

What Is the Cost of a Correctly Predicted Branch (On Any CPU)

Based from what I read, it seems like the cost might be 0 cycles. Is it really 0 cycles? If the cost is 0 cycles, does this include the jump instruction itself instead of just the possible flush in the CPU instruction cache? I appreciate answers on…
cpp plus 1
  • 67
  • 9
0
votes
3 answers

expanding multiple "if"s with same condition result in performance gain

Let's say I have void f(const bool condition) { if (condition) { f2(); else { f3(); } f4(); if (condition) { f5(); } else { f6(); } } since condition never changes, the above can be simplied to the following void…
Monster Hunter
  • 846
  • 1
  • 12
  • 24
0
votes
1 answer

Actual parameter checking performance impact

Question is quite simple - Does checking the actual parameters given to a function incur a performance penalty? Exported library functions usually tend to check actual parameters passed by user code: if (arg1 == NULL || arg2 == NULL) return…
smichak
  • 4,716
  • 3
  • 35
  • 47
0
votes
2 answers

late lhr / ghr update in long pipeline

I'm wondering if it is a viable scenario in long pipelines, when younger branch instruction is already processed by branch prediction mechanism, but corresponding lhr (or ghr, depending on implementation) still hasn't been updated with actual result…
Bob
  • 137
  • 1
  • 6
0
votes
0 answers

Reverse engineering history pattern length in branch predictor

I'm trying to find the length of the history pattern in the branch predictor of my computer's processor. I generated variable length array of bits and have if conditions based on the value of the bit. I will then plot the run time of different…
samira
  • 399
  • 1
  • 3
  • 12
0
votes
2 answers

Is Haswell dual path execution CPU?

Haswell now has 2 Branch Units - as shown here: http://arstechnica.com/gadgets/2013/05/a-look-at-haswell/2/ Does it mean that Haswell is dual path execution CPU? In terms of: http://ditec.um.es/~jlaragon/papers/aragon_ICS02.pdf And does it mean…
Alex
  • 12,578
  • 15
  • 99
  • 195