[LLVMbugs] [Bug 17332] New: Missed optimization of shifts into roll/rorl when avoiding undefined behavior

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Mon Sep 23 06:06:28 PDT 2013


http://llvm.org/bugs/show_bug.cgi?id=17332

            Bug ID: 17332
           Summary: Missed optimization of shifts into roll/rorl when
                    avoiding undefined behavior
           Product: clang
           Version: trunk
          Hardware: PC
                OS: All
            Status: NEW
          Severity: normal
          Priority: P
         Component: LLVM Codegen
          Assignee: unassignedclangbugs at nondot.org
          Reporter: jonathan.sauer at gmx.de
                CC: llvmbugs at cs.uiuc.edu
    Classification: Unclassified

Created attachment 11268
  --> http://llvm.org/bugs/attachment.cgi?id=11268&action=edit
Disassembly of first rol/ror (no masking, roll and rorl)

The following two functions rotate an unsigned integer to the left and the
right, respectively:

unsigned int rol(unsigned int value, unsigned int amount)
{
    return (value << amount) | (value >> (32 - amount));
}

unsigned int ror(unsigned int value, unsigned int amount)
{
    return (value >> amount) | (value << (32 - amount));
}

On x86_64, clang r191183 with -O2 compiles them into a rol/ror instruction
(disassembly attached):

% ~/LLVM/build/Release+Asserts/bin/clang++ -S -O2 -o - clang.cpp

Unfortunately the code results in undefined behavior when <amount> is zero, as
then <value> gets shifted by 32 bits which, assuming <unsigned int> has a size
of 32 bits, is undefined behavior according to ยง5.8p1:

| The behavior is undefined if the right operand is negative, or greater than
| or equal to the length in bits of the promoted left operand

Of course it's easy to fix the functions by masking the lower five bits of
<amount>, which in this case results in no functionality change:

unsigned int rol(unsigned int value, unsigned int amount)
{
    return (value << amount) | (value >> ((32 - amount) & 31));
}


unsigned int ror(unsigned int value, unsigned int amount)
{
    return (value >> amount) | (value << ((32 - amount) & 31));
}


This however does not result in a rol/ror instruction (disassembly attached);
instead the code is compiled into two shifts, a negation and an or.

Now I'm a bit stuck between a rock and a hard place: On the one hand I want to
avoid undefined behavior (especially when using clang's UB sanitizer), on the
other hand I'd like clang to generate the optimum code.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20130923/3bb3ecd3/attachment.html>


More information about the llvm-bugs mailing list