ccpu-architecturecompiler-optimizationmicro-optimizationbranch-prediction

Preserving the Execution pipeline with branch layout in C source? Which prediction do CPUs or compilers start with?


Return types are frequently checked for errors. But, the code that will continue to execute may be specified in different ways.

if(!ret)
{
   doNoErrorCode();
}
exit(1);

or

if(ret)
{
   exit(1);
}
doNoErrorCode();

One way heavyweight CPU's can speculate about the branches taken in near proximity/locality using simple statistics - I studied a 4-bit mechanism for branch speculation (-2,-1,0,+1,+2) where zero is unknown and 2 will be considered a true branch.

Considering the simple technique above, my questions are about how to structure code. I assume that there must be a convention among major compilers and major architectures. These are my two questions

  1. When the code isn't an often-visited loop which boolean value is biased for when the pipeline is being filled ?
  2. Speculation about branching must begin at either true or false or zero ( the pipeline must be filled with something). Which is it likely to be ?

Solution

  • The behavior varies among CPUs, and the compiler often reorders instructions. You will find all the information you need in these manuals: http://agner.org/optimize/.

    In my opinion the only way to know what happens is to read the assembly code generated by the compiler.