"likely" keyword for D?

Don nospam at nospam.com
Wed Mar 23 01:06:20 PDT 2011


Peter Alexander wrote:
> On 23/03/11 4:59 AM, %u wrote:
>> I just thought of a (crazy) idea:
>>
>> Should D implement a "likely" keyword for if statements?
>> Something like:
>>
>> if likely (x == 2)
>> {
>>      //do something
>> }
>>
>> This would allow the compiler to generate branch prediction code for
>> the program, allowing the programmer to prevent branch predictions.
>>
>> It's a crazy (and new?) idea... any thoughts?
> 
> Would be better as a compiler intrinsic instead of introducing a new 
> keyword.
> 
> GCC uses __builtin_expect:
> 
> long __builtin_expect (long exp, long c)
> 
> if ( __builtin_expect(ptr != 0, 1) )
> {
>     // expect non-null
> }
> 
> In this day and age it's rarely useful. Modern processors have branch 
> prediction tables built in to them, so while you may be able to avoid 
> the first branch misprediction, the CPU will probably predict the rest 
> of them correctly anyway.

For a processor like x86, even in the rare cases where it could make a 
difference, the code to take advantage of it isn't consistent between 
processors. Eg code that will benefit Pentium4 will slow down other 
processors.

AFAIK one of the few processors that strongly benefits from knowledge of 
branch prediction probabilities is the Itanium; but IMHO this is better 
dealt with by profile-guided optimisation than by annotating the source 
code.


More information about the Digitalmars-d mailing list