likely/unlikely gcc extensions
February 9th, 2006
If we talk about gcc extensions then probably we shouldn’t talk about likely/unlikely functions. But since they are widely used into the GNU/Linux kernel, they are much more than strictly related.
In the truth, they are not functions, but macros. Let see how they’re defined:
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
You can see these lines in include/linux/compiler.h into your kernel sources. As you can see, likely and unlikely are just macros, the real gcc extension is __builtin_expect.
Pratically talking, __builtin_expect is a way to say to gcc that such condition is easier to happen then another (this is usually called branch prediction) and is needed to optimize the code (a jump, or better, an IP changement, takes a lot of cpu cycles, so if you can, optimize it).
With 1 we say that the if branch is more probable than the else one. While, on the other side, with 0 we say that the else branch is more probable than the if one.
That said, this means that if we know that an if (or an else) is much more probable to happen, we should use such macro.
Please note that we’re talking about kernel code that needs to be extremely optimized. If you’re writing your own application you probably won’t need to use such extensions since rarely you’ll have to do branch prediction (better, the compiler should do this for you).