InstCombine: (float) x + (float) y -> (float) (x + y) incorrect
| Bugzilla Link | 27036 |
| Resolution | FIXED |
| Resolved on | Feb 12, 2020 09:24 |
| Version | trunk |
| OS | MacOS X |
| Reporter | LLVM Bugzilla Contributor |
| CC | @arpilipe,@ekatz,@hfinkel,@jmolloy,@sanjoy |
Extended Description
InstCombiner::visitFAdd optimizes the following code (note: the or and the and instruction are just to show the LLVM that no overflow occurs):
$ cat ../example.ll define float @test(i26 %x, i26 %y) { %xx = or i26 %x, 42074059 %yy = and i26 %y, 14942208 %t0 = sitofp i26 %xx to float %t1 = sitofp i26 %yy to float %rr = fadd float %t0, %t1 ret float %rr }
define i1 @main() { %y = call float @test(i26 42074059, i26 14942208) %rr = fcmp oeq float 0xC163400680000000, %y ret i1 %rr }
To:
$ bin/opt < ../example.ll -instcombine -S > ../example2.ll && cat ../example2.ll
; ModuleID = '
define float @test(i26 %x, i26 %y) { %xx = or i26 %x, -25034805 %yy = and i26 %y, 14942208 %addconv = add nsw i26 %xx, %yy %rr = sitofp i26 %addconv to float ret float %rr }
define i1 @main() { %y = call float @test(i26 -25034805, i26 14942208) %rr = fcmp oeq float %y, 0xC163400680000000 ret i1 %rr }
The results differ when running the optimized and the unoptimized version:
$ bin/lli -force-interpreter ../example.ll; echo $? 1 $ bin/lli -force-interpreter ../example2.ll; echo $? 0
The reason for the difference is that -25034805 cannot be accurately represented with float but the result of the integer addition can be, so the result of the optimized version changes.
Fixed in LLVM 5.0
(add double (sitofp x), fpcst) --> (sitofp (add int x, intcst)) combine in the same function is also buggy for the same reason.
To trigger:
#include <stdio.h> float test(unsigned int arg) { return (float)((int)(arg * 58)) + 1; } int main() { printf("%d\n", (int)test((unsigned int)-831710640)); }
O0 result is -994576896 O3 result is -994576832
Problematic transform: (float)x + 1.0 => (float)(x + 1)
x = -994576864
(float)x = -994576896.000000
(float)x + 1.0 = -994576896.000000 (float)(x + 1) = -994576832.000000
Indeed, this analysis can be done by Float2Int.
The major problem is how pessimistic it has to be though. In this case it wouldn't matter, but in the general case LLVM's value range analyses are very conservative, so F2I doesn't get much of a chance to kick in.
I wonder if we need this in InstCombine at all; I assume that the logic in lib/Transforms/Scalar/Float2Int.cpp is okay?