likely and unlikely

Bruce Evans brde at optusnet.com.au
Sat Mar 13 09:24:45 UTC 2010


On Fri, 12 Mar 2010, Max Laier wrote:

> On Friday 12 March 2010 13:42:59 Stefan Farfeleder wrote:
>> On Fri, Mar 12, 2010 at 01:26:08PM +0100, Ed Schouten wrote:
>>> Hi Ivan,
>>>
>>> * Ivan Voras <ivoras at freebsd.org> wrote:
>>>> Wouldn't it be more convenient to have a single global definition of
>>>> them, under #ifdef __GNUC__ for example in sys/stddef.h ?
>>>
>>> Wouldn't it be better to have them in sys/cdefs.h?
>>
>> Putting macros 'likely' and 'unlikely' into sys/cdefs.h creates a big
>> namespace violation problem; C code using those identifiers will break.
>
> In addition, I don't think it's a good thing to make these too easy to use ...

IIndeed.  The existing spelling of them in sys/cdefs.h (__predict_true
and __predict_false) is bad enough.

> I found that they are a pessimisation more often than not.  In addition, it
> seems that at least our base gcc version does forget to apply any other
> optimizations if it encounters one of these.

Interesting.  I thought they were about as useful as "register".  But the
compiler ignores "register", so "register" is not even a pessimization.

> My point is: Handle with care!!!  Trust your compiler/CPU predictors/... -
> most of the time, they are smarter than you are ;)

These macros may have useful 15-25 years ago for i386, i486 and Pentium1,
since CPU branch predictors were either nonexistent or not so good.
After that, CPU branch predictors became quite good.  The macros should
have been mostly unused 15-25 years ago too, since they optimize for
unreadability and unwritability.  Fortunately they are rarely used in
FreeBSD.  They were imported from NetBSD in 2003 where they are used
more (306 instances in 2005 NetBSD /sys vs 28 instances in 2004 FreeBSD
/sys; there are 2208 instances of likely() in 2004 linux-2.6.10).

Bruce


More information about the freebsd-arch mailing list