[LLVMdev] Definition of C/C++ integral conversion(was Re: nsw/nuw for trunc)

Tobias Grosser tobias at grosser.es
Mon Oct 3 01:50:44 PDT 2011


On 10/03/2011 09:42 AM, Tobias Grosser wrote:
> On 09/30/2011 04:46 PM, Duncan Sands wrote:
>>>> 3) If the destination type is signed, the value is unchanged if it
>>>> can be represented in the destination type (and bit-field
>>>> width); otherwise, the value is implementation-defined.
>>>> ----------------------------------------------------
>>>>
>>>> 4.7.3 suggest to me, that the standard does not define a result for
>>>> '(signed char) 999'. I assume you know this section, but I could not
>>>> find a reason why this section should not apply in this case. Any
>>>> ideas?
>>>
>>> It does apply: the value is implementation-defined, and the definition
>>> that any sane implementation uses is 2's complement truncation.
>>
>> Right, implementation defined is not the same as undefined.
>
> Thanks for your help. I found that the undefined behavior on integer
> overflow, is specified in 5 (5):
>
> "If during the evaluation of an expression, the result is not
> mathematically defined or not in the range of representable
> values for its type, the behavior is undefined, unless such an
> expression is a constant expressionappears where an integral
> constant expression is required (5.19)"
>
> This seems to apply to mathematical expressions, but not to
> explicit/implicit type conversions.
>
> Hence, code like
>
> int index = a + 100;
> A[index] = ...
>
> may result on 64bit architectures in a sext(trunc(index)) expression,
> that can be optimized out easily. Very interesting.
I ment '... that can not be ...'.

Also, some interesting detail I found. Integer to floating point 
conversion may actually yield undefined behavior as defined at C99:

6.3.1.4 Real floating and integer

1 When a finite value of real floating type is converted to an integer
   type other than _Bool, the fractional part is discarded (i.e., the
   value is truncated toward zero). If the value of the integral part
   cannot be represented by the integer type, the behavior is
   undefined.50)

Cheers
Tobi



More information about the llvm-dev mailing list