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
0 answers

Do modern x86-64 CPUs speculate on the branch destination?

Given the following code: func_pointer functions[] = { &func1, &func2, ..., &funcn } void dispatch(int i) { functions[i](); } The address of the destination is not known in the compile time. Can the CPU speculate the destination of the call in…
Bogi
  • 2,274
  • 5
  • 26
  • 34
0
votes
1 answer

How to break out of a loop of Consumers

Based on the response given by user @eitan https://stackoverflow.com/a/37334159/11214643, on how to perform readable switch cases for auto casting using lambdas, but also based on user @Al-Mothafar 's question, which I guess is a valid point, to try…
Delark
  • 1,141
  • 2
  • 9
  • 15
0
votes
1 answer

Is there any technology to "cache" the result of a branch choice?

In my code there's a regular: if a if statement is true, it will keep true for a while, and if it changes to false, it will keep false for a while. Since the performance in this code matters, I want to make the branch predict more…
user2269707
0
votes
1 answer

java code to calculate running time for sorting algorithms

I have a java code that calculate the running time for multiple sorting algorithms such as "Merge sort , Bubble sort and so on ..". The running time after the first algorithm is not calculated correctly due to branch prediction. So is there anyway…
Sholi
  • 11
  • 5
0
votes
0 answers

Branch Misprediction Recovery in RISC-V

I'm now trying to implement pipeline CPU based on RV32I ISA. My CPU has renaming algorithm for data hazards and branches prediction for control hazards. This is my example code for renaming algorithm and branch prediction : addi x1, x0, 25 addi…
0
votes
2 answers

Intel PIN: How do I see speculative instructions?

I'm writing a PIN tool where I want to see speculatively executed instructions that were eventually squashed. I.e. if a branch direction was predicted, some instructions were executed speculatively, the branch direction was resolved and the…
Farhad
  • 516
  • 3
  • 14
0
votes
0 answers

If vs function call performance when handling different scenarios

Inspired from my most favorite stackoverflow question I'm trying to decide what is more 'convenient' when facing up a classical problem in programming, i.e. executing some code instead some other according to any current scenario. To make it brief,…
user1832484
  • 371
  • 3
  • 8
0
votes
0 answers

How can I create a 3-bit counter gshare branch predictor out of a 2-bit counter gshare branch predictor?

I've been trying to figure out which parts of this code involve the 2-bit counter, because I have to make it into a 3-bit counter. For the GSHARE_SIZE table size, I think the correct size for a 3-bit counter would be 17 instead of the 2-bit 18,…
0
votes
0 answers

How does `g++ -O3` generated `xmm` things affect branch prediction for unsorted array?

I think code tells everything: ➜ project cat branch_prediction_victim.cpp #include #include #include int main(int argc, char* argv[]) { const size_t array_length = 32768; int array_aka[array_length]; …
http8086
  • 1,306
  • 16
  • 37
0
votes
1 answer

branch simulator with C++

I am using C++ to simulate branch predictor and output the prediction into trace.txt.out file. I use cout to check the prediction in command window and the prediction is right. However the .out file cannot be opened. When I use cat trace.txt.out |…
Stephane
  • 75
  • 7
0
votes
0 answers

Does a processor stall even if there is (theoretically) perfect branch prediction irresp. of whether the Branch is taken or not-taken?

I am going through the textbook Computer Organization and Design and I am a bit confused with the Branch Prediction and how it works with a 5 stage pipeline scenario - IF ID EX MEM WB. Consider the following sequence of instructions: TOP: SUB X2,…
rgbk21
  • 163
  • 10
0
votes
1 answer

is return stack implemented in Zynq 7000 SOC

I am working on some research project based on ZC706 board that contain Zynq-7000 soc. i need to know that Cortex-A9 Cpu in Zynq-7000 implemented Return Stack Buffer (Return Stack Buffer is an program flow speculation technique like branch…
0
votes
1 answer

Computer Organization - How does "Predict taken"(always taken) branch prediction work?

I can understand how "predict untaken" work. It just move on fetching PC+4 instruction. Until the branch is resolved, if the branch is taken, then flushes all the instructions fetched before. But I don't understand how does "predict taken" work. I…
user3087000
  • 731
  • 1
  • 13
  • 24
0
votes
0 answers

How do i implement 1 bit branch prediction in c++ using if and if else statements?

I am doing a project for my computer architecture module and the project implementation is rather vague. Im just not sure how to implement a branch prediction algorithm in c++ This is what i have attempted so far: int random(int& branchNum);…
0
votes
0 answers

One bit branch prediction

I have the following code; for ( int i = 0; i < 100 ; i++) { for( int j = 0; j < 100 ; j++) { System.out.println(j+""); In this code I am gonna predict the branches by the method of one bit branch prediction. Let us say the first…
Davis
  • 188
  • 1
  • 13