[flang-commits] [flang] [flang][CodeGen] add nsw to address calculations (PR #74709)

via flang-commits flang-commits at lists.llvm.org
Fri Dec 8 08:46:02 PST 2023


jeanPerier wrote:

> > I was talking about setting `nsw` on the do-variable increment that is generated by the loop lowering.
> 
> @vzakhari Are you sure if this is allowed? do-variables could definitely overflow. Is integer overflow completely undefined in Fortran? I can't find any mention of it in the standard.

I think so. Adding @klausler to validate, but gfortran doc is telling this is forbidden (https://gcc.gnu.org/onlinedocs/gfortran/Behavior-on-integer-overflow.html).

I think the rational is that Fortran specifies the INTEGER type as a subset of mathematical integers in 7.4.3.1, and it also says that aside from parentheses order, Fortran is free to rewrite any expression to its mathematical equivalent (10.1.5.2.4 point 2.).

So it would be valid for the compiler to fold `MAX_INT + 1  .le. 0` to `.false.` since this is mathematically correct. Hence a Fortran programmer should never rely on integer overflow behavior.

In fact, you can check that this is the case with gfortran on the following funny example (gfortran likely rewrites `n + 1 .le. 0` to `n .le. 1` because it is allowed to as per 10.1.5.2.4 point 2.)

```
 integer :: n = 2147483647
 call test(n, n+1)
end

subroutine test(n, n_plus_one)
 integer :: n, n_plus_one
 print *, n+1 .le. 0
 print *, n_plus_one .le. 0
end
```

gfortran 13.2 outputs `F T` taking every C programmer aback !

https://github.com/llvm/llvm-project/pull/74709


More information about the flang-commits mailing list