Left shift of negative value

Andrew Haley aph@redhat.com
Tue Dec 1 17:10:00 GMT 2015

On 12/01/2015 05:08 PM, Andrew Haley wrote:
> On 12/01/2015 05:01 PM, Richard Earnshaw wrote:
>> On 01/12/15 16:07, Andrew Haley wrote:
>>> Do we support left shift of a negative value?  Technically it's
>>> undefined and ubsan warns about it.  However, a ton of software would
>>> surely break if we didn't do the obvious right thing.  I can't find
>>> anything in the GCC manual.
>> I don't believe we do, or can as of today.  Firstly, there are two
>> possible 'obvious' behaviours: 1) The value is treated as signed and a
>> negative shift turns into a positive shift in the other direction; 2)
>> The value is treated as unsigned and the value is treated by a massive
>> shift in the same direction that exceeds the normally supported range of
>> the type.  Which one is the default will probably depend on your hardware.
>> Consider the case where the value is in a variable.  To support negative
>> shifts as reversed shifts on machines where they don't automatically
>> convert negative values to reversed shifts you'd have to do an explicit
>> range check before every shift using that value.  Something I know we
>> don't do today since I've never seen such checks come out on ARM, nor
>> are there any hooks in the compiler to deal with it.
> No, a shift *of* a negative value, not a shift *by* a negative value!
> i.e. an arithmetic right shift.

That explanation was even more confusing.  Sorry.

I mean something like  -12345 << 4


More information about the Gcc-help mailing list