[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Using __builtin_expect (likely/unlikely macros)

From: Alex Gramiak
Subject: Re: Using __builtin_expect (likely/unlikely macros)
Date: Tue, 16 Apr 2019 09:47:57 -0600
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.2 (gnu/linux)

Eli Zaretskii <address@hidden> writes:

> OK, it's possible that I don't understand the exact semantics of
> __builtin_expect in these situations.
> The problem is that you used LIKELY like this:
>   if (A)
>     do_A;
>   else if (B)
>     do_B;
>   else if (C)
>     do_C;
>   else if (LIKELY (D))
>     do_D;
>   else
>     cant_happen ();
> Essentially, the above is a moral equivalent of a 'switch' with the
> 'default' case aborting because it "cannot happen".  In such code, the
> order of the clauses doesn't necessarily tell anything about their
> likelihood; up front, they all are equally "likely".  So using LIKELY
> only in the last one sends a wrong signal: that last condition is
> neither more nor less likely than all the others.  Actually, in some
> cases it might be _less_ likely than the preceding ones, because if I
> knew that some of these conditions happens much more frequently, I'd
> test it first.

It was my understanding that since an else if is equivalent to else { if
... }, it would only affect the last two branches. Though I could easily
be wrong here.

> Now, it's possible that the effect of __builtin_expect doesn't care
> about this issue.  The GCC manual doesn't help to figure out whether
> this is the case, because it only talks about a simple case of a
> single 'if' clause, and doesn't tell any details about what GCC is
> allowed to do when it sees __builtin_expect.  But just by looking at
> how the code looks, I immediately raised a brow.

Right, considering the confusion it would be counterproductive to use
them in this fashion. A workaround to the confusion would be to do:

      if (LIKELY (D))
        cant_happen ();

reply via email to

[Prev in Thread] Current Thread [Next in Thread]