llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

clang optimizer bydefault performs FMA optimization, even if target backend doesn't support it

Open Long5hot opened this issue 3 years ago • 4 comments

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

Long5hot avatar Jun 08 '23 13:06 Long5hot

@llvm/issue-subscribers-clang-frontend

llvmbot avatar Jun 08 '23 14:06 llvmbot

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

Long5hot avatar Jun 30 '23 09:06 Long5hot

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.

Long5hot avatar Jul 20 '23 17:07 Long5hot

https://reviews.llvm.org/D158632

Long5hot avatar Aug 26 '23 06:08 Long5hot