If you've ever poked at high-performance C code, you've probably seen GCC's __builtin_expect extension being used to manually hint the likelihood of a

Peeking under the hood of GCC's __builtin_expect

submited by
Style Pass
2021-05-26 23:00:04

If you've ever poked at high-performance C code, you've probably seen GCC's __builtin_expect extension being used to manually hint the likelihood of a branch being taken a particular way.

The Linux kernel famously contains macros for likely and unlikely branches, which perform the appropriate __builtin_expect incantations.

…but, how does this all work? What does "hinting" mean, exactly, and how does __builtin_expect translate to generated assembly?

The program returns 1 if the number of parameters it is passed is even, and 0 otherwise (remember that the executable name is, by convention, always passed in argv[0]). We use a compile-time define, EXPECT, as a parameter to __builtin_expect. Our return value, x, is marked as volatile to prevent the compiler from optimizing it out.

We can compile two versions of this binary: one with EXPECT = 1 and one with EXPECT = 0, and see how they differ. Recall that for EXPECT = 1, we are telling the compiler that we expect the x = 1 branch to be more likely, and vice-versa.

Leave a Comment