llvm / llvm/llvm-project

[Flang] Question on SUM result differences between -O0 and -O1

Open
#176,282 3 comments 0 reactions 1 assignee Claimed by @tatsuhito-fj View on GitHub
flang
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

```
Version of flang : 22.0.0git(2f7e218017db69454ea84e1849fcb9a11b1f7fef)/AArch64
```
I have a question about SUM result differences between -O0 and -O1 in Flang on an Arm64 (Aarch64) system.
While inspecting the assembly generated by Flang, I noticed that at -O0 the SUM operation uses `_FortranASumReal4`.
In this configuration, the numerical result at -O0 differs from the result produced at -O1.

Are the result differences between -O0 and -O1 considered correct behavior (e.g., due to optimization or floating-point\
handling)?

Are there any recommended compiler flags in Flang to obtain invariant numerical results across optimization levels?

sample.f90
```fortran
program main
integer,parameter :: N=76
real(kind=4),parameter :: val=1._4
real(kind=4),dimension(1:N,1:N,1:N) :: a3

a3 = val
do i=1, N-1
do j=1, N
do k=1, N
a3(i+1,j,k) = a3(i,j,k) + val
enddo
enddo
enddo
write(1002) a3
rewind 1002
call sub
end program main

subroutine sub
integer,parameter :: N=76
real(kind=4),dimension(1:N,1:N,1:N) :: a
read(1002) a
print *,' SUM: ',sum(a)
end subroutine sub
```
flang
```
$ flang sample.f90 -O0; ./a.out
SUM: 1.6900576E+07

$ flang sample.f90 -O1; ./a.out
SUM: 1.689898E+07

$ flang sample.f90 -Ofast; ./a.out
flang-22: warning: argument '-Ofast' is deprecated; use '-O3 -ffast-math -fstack-arrays' for the same behavior, or '-O3 -fstack-arrays' to enable only conforming optimizations [-Wdeprecated-ofast]
SUM: 1.6900492E+07

$ flang sample.f90 -O3 -fstack-arrays; ./a.out
SUM: 1.689898E+07
```

gfortran
```
$ gfortran sample.f90 -O0; ./a.out
SUM: 16898980.0

$ gfortran sample.f90 -O1; ./a.out
SUM: 16898980.0

$ gfortran sample.f90 -Ofast; ./a.out
SUM: 16900576.0

$ gfortran sample.f90 -O3 -fstack-arrays; ./a.out
SUM: 16898980.0
```

ifx
```
$ ifx sample.f90 -O0; ./a.out
SUM: 1.6898980E+07

$ ifx sample.f90 -O1; ./a.out
SUM: 1.6898980E+07

$ ifx sample.f90 -Ofast; ./a.out
SUM: 1.6898980E+07
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.