I've come across a few scenarios where I want to say a function's return value is likely inside the body of a function, not the if statement that will call it.
For example, say I want to port code from using a LIKELY
macro to using the new [[likely]]
annotation. But these go in syntactically different places:
#define LIKELY(...) __builtin_expect(!!(__VA_ARGS__),0)
if(LIKELY(x)) { ... }
vs
if(x) [[likely]] { ... }
There's no easy way to redefine the LIKELY
macro to use the annotation. Would defining a function like
inline bool likely(bool x) {
if(x) [[likely]] return true;
else return false;
}
propagate the hint out to an if? Like in
if(likely(x)) { ... }
Similarly, in generic code, it can be difficult to directly express algorithmic likelihood information in the actual if
statement, even if this information is known elsewhere. For example, a copy_if
where the predicate is almost always false. As far as I know, there is no way to express that using attributes, but if branch weight info can propagate through functions, this is a solved problem.
So far I haven't been able to find documentation about this and I don't know a good setup to test this by looking at the outputted assembly.
__builtin
are to provide an expected value for a variable, not specific to using it in a branch. (As Nate shows, GCC does this, but clang trunk seems not to) – Giule#define LIKELY(x) (__builtin_expect(!!(x),0))
and use it asif LIKELY(x) { ... }
. That way, porting it would've been easy. (Or one could've even defined anif_likely(x)
macro with theif
keyword moved into the macro definition.) – Mohler