[patch] convert.c: Fix PR tree-optimization/25125.

Paolo Bonzini bonzini@gnu.org
Wed Dec 21 10:11:00 GMT 2005


>>unsigned short
>>f (short a)
>>{
>>  short b;
>>
>>  if (a > 0)
>>    return 0;
>>  b = ((int) a) + - (int) 32768;
>>  return b;
>>}
>
> For a = 0, that seems to be the correct result.
> For a = -1, the original wants to do b = -32769, which seems undefined,  
> and thus the result is correct. Similarly for even more negative a.
> 
> Where is the actual bug here?

The point is that *truncation* is defined to use modulo arithmetic. 
Arithmetic operations are undefined on overflow.  So, summing -1 and 
-32768 as shorts is undefined (but this cannot be expressed in C on a 
32-bit machine, because everything promotes to int), but the above is 
the same as (short)(-32769) which is 32767.

On a 16-bit machine, the above would be undefined because it would 
indeed run into an overflow while summing -1 and -32768.

But GCC was trying to do the sum in 16-bits even on 32-bit machines, and 
this is possible only if we can guarantee that operations that overflow 
are defined.

Paolo



More information about the Gcc-patches mailing list