Standard way to supply hints to branches

Walter Bright newshound2 at digitalmars.com
Fri Sep 13 08:17:14 UTC 2024


On 9/12/2024 3:49 PM, Manu wrote:
> You're not meant to do anything about it; just accept that your suggestion to 
> rely on contorting the code and a prayer that the compiler emits the code you'd 
> like to see (it doesn't) is not a reasonable suggestion.
> This needs a proper solution.

dmd does emit the expected code.

I used -O on gcc, not -O2, and it produced the expected result. -O2 does not, as 
you discovered.

There's also the do-while solution:

```
void bar();
int gax(int i)
{
     do
     {
         if (i) break;
         bar();
         return 1;
     } while (0);
     return 0;
}
```
which produces the same result with gcc -O:
```
gax:
     mov       EAX,0
     test      EDI,EDI
     jne       L55
     sub       RSP,8
     call      bar at PC32
     mov       EAX,1
     add       RSP,8
L55:    rep
     ret
```

I do not know why -O2 behaves differently. I don't know why gcc does not respect 
the code order given by the programmer.

Expecting these kinds of micro-optimizations to work reliably have a long 
history of becoming pessimizations. Given the complexity of modern optimizers 
and code generators, trying to control the sausage that comes out is going to be 
frustrating. Since they are "hints", there is no guarantee whatsoever any 
particular compiler will take the hints.

One thing you can try is to ask Iain and Martin to automatically add 
[[likely]]/[[unlikely]] hints to if statements so that code generation order 
mimics dmd's, which does put the code in the order presented.


More information about the Digitalmars-d mailing list