[cfe-users] Weird optimization

Csaba Raduly rcsaba at gmail.com
Mon Feb 23 06:58:53 PST 2015

This is, in fact, a great illustration of an optimization enabled by
undefined behavior. The compiler can say: "I don't have to make it
work correctly for 0x8000000000000000ul, and for every other case it's
faster this way".

A very good article about undefined behavior:

On Mon, Feb 23, 2015 at 12:22 PM, Artem Alimarin
<artem.alimarin at gmail.com> wrote:
> Hi Csaba,
> Yes, thanks. nasal demons, indeed. I forgot that the signed integer overflow
> causes undefined behavior unlike unsigned integer overflow, which causes
> wrap around.
> The code
>     return (long)(0ul - (unsigned long)x) > 0;
> does what I want.
> I am impressed by clang's ability to use this undefinedness to enable
> optimizations like (-x) > 0 to x < 0, which seems to be valid for all valid
> arguments.
> Best regards,
> Artem
> On 23-2-2015 9:44, Csaba Raduly wrote:
>> cast to an unsigned type to negate
>> this value to itself

GCS a+ e++ d- C++ ULS$ L+$ !E- W++ P+++$ w++$ tv+ b++ DI D++ 5++
The Tao of math: The numbers you can count are not the real numbers.
Life is complex, with real and imaginary parts.
"Ok, it boots. Which means it must be bug-free and perfect. " -- Linus Torvalds
"People disagree with me. I just ignore them." -- Linus Torvalds

More information about the cfe-users mailing list