j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

Defined checking for overflow #296

Open tkoenig1 opened 1 year ago

tkoenig1 commented 1 year ago

This may be a duplicate; if so, please merge.

It is currently hard to impossible to check if an arithmetic operation on integers will overflow. It's a bit of a chickend-and-egg problem: If the operation ist performed and then checked, that violates the standard already.

It would be useful to have a set of intrinsics to check for such overflow. These could come in two flavors: One which returns both the result of the operation and an indication if it is valid or not, and one which just does the check.

One possible syntax could be

  call add_overflow(a,b,c,overfl)

which would (conceptually) promote the INTENT(IN) arguments a and b to infinite precision, calculate the INTENT(OUT) argument c = a + b and then check if c was representable. If it was, the INTENT(OUT) argument overfl wold be set to .false., otherwise c would become undefined and overfl would be set to .true.

Compilers already have such functionality, for example in https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html , and I think that C23 will also introduce it. So, it is likely that this will be implemented efficiently.

tkoenig1 commented 1 year ago

Comments? Or is it sufficiently non-controversial that I should write up a proposal?

klausler commented 1 year ago

Since negation can overflow, one could not use call add_overflow(a,-b,c,overfl) to perform a subtraction with an overflow test, and so you'll need a complete suite of operations. I think that's your plan, but if not, it should be.

"Unsigned" variants that return the carry bit rather than the overflow flag would also seem to be useful.

tkoenig1 commented 1 year ago

Since negation can overflow, one could not use call add_overflow(a,-b,c,overfl) to perform a subtraction with an overflow test, and so you'll need a complete suite of operations. I think that's your plan, but if not, it should be.

That is the plan, indeed.

These functions should probably be generic - anything that is allowed for an operator in Fortran could also be allowed for the checked functions.

"Unsigned" variants that return the carry bit rather than the overflow flag would also seem to be useful.

True, although the value is somewhat less there (if one assumes wraparound semantics). Also, in this case, the main result should not be undefined.

Instead of

call add_overflow(a,b,c,overfl)

it would be possible to write

c = a + b
overfl = a < c