home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ogicse!das-news.harvard.edu!spdcc!iecc!compilers-sender
- From: eggert@twinsun.com (Paul Eggert)
- Newsgroups: comp.compilers
- Subject: Re: constant folding vs exceptions
- Keywords: parse, optimize
- Message-ID: <92-08-174@comp.compilers>
- Date: 28 Aug 92 20:59:16 GMT
- Article-I.D.: comp.92-08-174
- References: <92-08-114@comp.compilers> <92-08-163@comp.compilers>
- Sender: compilers-sender@iecc.cambridge.ma.us
- Reply-To: eggert@twinsun.com (Paul Eggert)
- Organization: Twin Sun, Inc
- Lines: 59
- Approved: compilers@iecc.cambridge.ma.us
-
- henry@zoo.toronto.edu (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.
- --
- Send compilers articles to compilers@iecc.cambridge.ma.us or
- {ima | spdcc | world}!iecc!compilers. Meta-mail to compilers-request.
-