llvm-project
llvm-project copied to clipboard
clang optimizer bydefault performs FMA optimization, even if target backend doesn't support it
Clang frontend loses precision when doing operation on floats and doubles the main cause of this is After simplyfying FMA operations. PR : https://godbolt.org/z/xzMc8xWKd
#include<stdlib.h>
#include<stdio.h>
double * compilerCalculated() {
double *HeapArray = (double *)malloc(sizeof(double)*20);
double count = 1.0;
for(int IDX =1 ; IDX <=20 ; IDX++) {
HeapArray[IDX] = 0.1 * count + 1.0;
count++;
}
return HeapArray;
}
int main() {
// With -O2 this will emit fma for fma supported Target, but mul and add for non supported
double array[20] ; //= {1.1, 1.2, 1.3, 1.4, 1.5,1.6, 1.7, 1.8, 1.9, 2.0};
double count;
scanf("%lf",&count); //Give 1 as Input
for(int IDX =1 ; IDX <=20 ; IDX++) {
array[IDX] = 0.1 * count + 1.0;
count++;
}
int isFailed = 0;
double *heapArray = compilerCalculated();
for(int i=1; i<=20; i++) {
printf("%0.16lf %0.16lf \n",array[i],heapArray[i]);
if(array[i] != heapArray[i]) {
isFailed =1;
}
}
if(isFailed)
printf("Test Failes\n");
else
printf("Test Passes\n");
return isFailed;
}
compile with
clang test.c -O2 -emit-llvm -S -o optlevel2.ll
@llvm/issue-subscribers-clang-frontend
Result on X86
x86 Arch result Compiler result
1.1000000000000001 1.1000000000000001
1.2000000000000000 1.2000000000000000
1.3000000000000000 1.3000000000000000
1.3999999999999999 1.3999999999999999
1.5000000000000000 1.5000000000000000
1.6000000000000001 1.6000000000000001
1.7000000000000002 1.7000000000000000
1.8000000000000000 1.8000000000000000
1.8999999999999999 1.9000000000000001
2.0000000000000000 2.0000000000000000
2.1000000000000001 2.1000000000000001
2.2000000000000002 2.2000000000000002
2.2999999999999998 2.3000000000000003
2.4000000000000004 2.3999999999999999
2.5000000000000000 2.5000000000000000
2.6000000000000001 2.6000000000000001
2.7000000000000002 2.7000000000000002
2.7999999999999998 2.8000000000000003
2.9000000000000004 2.8999999999999999
3.0000000000000000 3.0000000000000000
Test Failes
Update : Found the Cause for this issuse, Which is opt optimizer bydefault performs FMA with ffp-contract=on even if target doesn't support it. For this particular case Default subtarget X86 doesnt support FMA, so it doesn't emit fma instruction but front-end performs FMA by default.
https://reviews.llvm.org/D158632