Re: constant folding vs exceptions (Paul Eggert)
Fri, 28 Aug 1992 20:59:16 GMT

          From comp.compilers

Related articles
Re: constant folding at parse time twpierce@amhux1.amherst.EDU (Tim Pierce) (1992-08-19)
constant folding vs exceptions (1992-08-26)
Re: constant folding vs exceptions (1992-08-28)
| List of all articles for this month |

Newsgroups: comp.compilers
From: (Paul Eggert)
Organization: Twin Sun, Inc
Date: Fri, 28 Aug 1992 20:59:16 GMT
References: 92-08-114 92-08-163
Keywords: parse, optimize (Henry Spencer) writes:
> In fact, ANSI C handed down a much stricter line on this:....
> The only restriction is that if overflows are
> visible, optimizations can't add or remove overflows.

Actually, in ANSI C, the behavior on overflow is undefined, so a
conforming implementation optimization can remove overflows.

Spencer's right that the Ritchie compiler's treatment of integer overflow
was broken, but unfortunately the C Standard lets a compiler behave in
this way. (C's not alone in this regard, of course; e.g. the Fortran
standard has the same problem.) That's too bad, since the problems that
it leads to can be quite mysterious. For example, in the following code:

i = 0;
if (0 < j)
i = j;
assert (0 <= i);

integer overflow can cause the assertion to fail!

There's a trick to this, of course. Here's a complete C program
containing the above code. Assume a 32-bit int.

#include <assert.h>
int big = 2147483647;
main() {
int i, j;
j = big + 1; /* This overflows. */

i = 0;
if (0 < j)
i = j;
assert (0 <= i);

Suppose the compiler optimizes `main's body into something like this:

j = big + 1; /* This overflows. */

i = 0;
if (0 <= big)
i = j;
assert (0 <= i);

The C Standard allows this optimization, because it works when `big + 1'
does not overflow, and the code can do anything it pleases when `big + 1'
_does_ overflow. However, I suspect most programmers would say this
optimization is incorrect, because it gives `i' a negative value when
`big' is INT_MAX.

This is not a contrived example. I derived the above program from a bug I
encountered when building DEC SRC Modula-3 with GCC 2.2.2 -O on a Sparc.
Happily, though, the GCC maintainers are programmers, not language
lawyers; they've agreed that this behavior is a bug, and it'll be fixed in
the next release.

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.