It happens because LLVM (specifically instcombine) does the following transformation:
(float)x + 1.0 => (float)(x + 1)
For some values the expression before and after yield different results:
x = -994576864
(float)x = -994576896.000000
(float)x + 1.0 = -994576896.000000
(float)(x + 1) = -994576832.000000
I’m curious if this is a correct transformation and why.
Looks broken to me; I don’t think there’s UB in the original program.
The fold in visitFAdd() should check if the sitofp is guaranteed to produce an exact result? Ie, if the int value input to the sitofp could possibly be different when converted back using fptosi, then the transform does not work.
define float @test(i32 %x) {
%mul = mul i32 %x, 58
%conv = sitofp i32 %mul to float
%add = fadd float %conv, 1.0
ret float %add
}
I agree. There’s implementation-defined behavior on the conversion of (arg*58) to int, but that shouldn’t be at issue here. The transform of (float)x + 1 => (float)(x + 1) is bogus.