[llvm-dev] LLVM Optimizations strange behavior/bug

Tim Northover via llvm-dev llvm-dev at lists.llvm.org
Sat Apr 22 11:23:07 PDT 2017

On 22 April 2017 at 04:18, Garba Peter via llvm-dev
<llvm-dev at lists.llvm.org> wrote:
> Any idea if this is a bug or why clang does show this behavior ?

The code is pretty rife with undefined behaviour. Casting a "char *"
pointer to an "unsigned *" and dereferencing it violates strict
aliasing (actually just doing the cast is dodgy, but usually not a
problem in practice).

When I change those lines to use memcpy instead and compile with
-fsanitize=undefined, apparently 4 of the shift operations are
shifting by a negative amount (also undefined behaviour). I expect
Clang is marking those as undef and simplifying everything down to a
constant based on that.

Certainly I start getting non-constant results when I fix those. Also,
beware that shifting a signed int is only valid if the input is
positive and the result is still fits, and you can only shift from 0
to the 1 less than the bit-width of the type. Generally you almost
always want to do bitwise fiddling on unsigned quantities because of
that first one.



More information about the llvm-dev mailing list