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

Why is this statement with bitwise operators the same as this if statement?

I was reading this question Why is it faster to process a sorted array than an unsorted array? and the best answer provided by Mysticial. The answer does a great job of explaining what is happening and why and also says this: So what can be…
user3282276
  • 3,674
  • 8
  • 32
  • 48
0
votes
1 answer

Branch predictor function in raytrace algorithm

Has anyone tried a custom branch prediction algorithm for GPU computing in any raytracing collision test kernel (Cuda, Opencl)? Should I even worry about performance for low depth(2-5)? Example: trace for the first group of rays check for…
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
0
votes
1 answer

Can the F# compiler use currying to separate code paths based on type?

Can the F# compiler separate out code paths by currying a function in which different types imply different paths through subsequent called functions? Consider the following discriminated union. There are 2 possibilities, which are theoretically…
0
votes
0 answers

Is branch-prediction a big issue in PHP?

Is branch prediction a big issue in PHP too? I am referring to this answer: Why is processing a sorted array faster than an unsorted array? So in C++ and Java a sorted array is computed faster than an unsorted, because the processor can predict…
rubo77
  • 19,527
  • 31
  • 134
  • 226
0
votes
0 answers

Branch history for branch prediction inside a function on intel X86-64

Is branch history preserved across function calls or does it get re-initialized every time the function is entered.
san
  • 4,144
  • 6
  • 32
  • 50
0
votes
1 answer

Branch target prediction vs branch prediction

branch target predication(BTP) is not the same as branch predication(BP). I understand that BTP finds where the branch will jump to, where as BP just decides which branch will probably be taken. Is BTP dependant on BP, if BTP doesn't use BP to…
Jonathan.
  • 53,997
  • 54
  • 186
  • 290
0
votes
1 answer

Intrusive, circular, branchless, doubly linked list - how to have the list to identify the node member fields?

The code is posted here: https://ideone.com/ul2PiS What I'm trying to do is allow the user to specify the list nodes as member fields of the classes which will be added to the lists. Currently, this is done with a macro using offsetof() which means…
0
votes
5 answers

Avoid IF ELSE Branching

I was looking at branching, and I wanted to avoid branching in a loop, which basically was doing this for(z=0; z<8; z++){ if(0xff&&(array[z])!=0 ){ break; } } so my plan was actually to replace it with the following : for(z=0; z<8;…
Anoracx
  • 438
  • 7
  • 24
0
votes
1 answer

Linux Kernel: likely() vs unlikely()

These two methods seem to be extensively used inside linux kernel code. I know the foundations of branch prediction, but I would like to know how these two functions affect the operation of if() statements. Also do they work at the level of CPU…
Ace
  • 1,501
  • 4
  • 30
  • 49
0
votes
1 answer

How branch predictor and branch target buffer co-exist?

My question is how they co-exist and work together in modern CPU architecture?
fyang29
  • 25
  • 1
  • 4
0
votes
1 answer

Pipeline branch prediction performance example

I am working through examples of pipeline hazards and am looking at Question 2 from the following document I have found this which has helped somewhat. As I understand, the strategies work the following way: Stall until everything is known: will…
0
votes
1 answer

Perceptron branch predictor implementation in C

I was reading the paper, http://www.cs.utexas.edu/~lin/papers/hpca01.pdf, on Dynamic Branch Prediction with Perceptrons. I was wondering how to implement the perceptron branch predictor in C if given a list of 1000 PC addresses (word addresses) and…
David
  • 583
  • 1
  • 10
  • 27
0
votes
1 answer

Branch mispredictions

This question may be silly but i will ask it anyway. I've heard about branch prediction from this Mysticial's answer and i want to know if it is possible for the following to happen Lets say i have this piece of C++ code while(memoryAddress =…
Lan Pac
  • 365
  • 4
  • 14
0
votes
1 answer

Multiplying is faster than branching

To get an idea of if-statement vs selective-multiplication, I tried the code below and saw that multiplying the result by 0 instead of failed-if-statement(false) and multiplying by 1 instead of passed-if-statement(true), if-statement is slower and…
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
0
votes
2 answers

Ruby Benchmarking Accuracy - Branch Prediction at its finest?

So this morning I decided to play around with Benchmarking for the first time. I was curious about the speed different between code with "do-end" block formatting vs. "{ }" formatting. So I stored the Benchmark code in a Proc so I could call it…
Sean Larkin
  • 6,290
  • 1
  • 28
  • 43