Can analysis detect undefined expressions?

Chris Dollin kers at hplb.hpl.hp.com
Fri Jun 21 19:51:24 AEST 1991


Dave Harris says:

   Not arguing that the result is undefined as you say.  But....
   I for one would quickly scrap any compiler that went to the additional work
   of embedding code to yield a value of anything other than 1,2,3 or 4 for i.
   It would mean the compiler would have to detect the undefined statement
   first before it could even do this.  Its one thing for a compiler to give 
   you a warning, but quite another for it to go out of its way to make mince
   meat out of your code.  It would be just one more thing that could go 
   accidently wrong .

True, if the compiler ``went out of its way'' to do so. But consider the
smaller (indeed, the original) example:

    (i = 1) == (i = 2)

and suppose that the compiler compiles it as

    Ri = 1 || Ri = 2; Ranswer = (Ri == Ri)

where Ri is the register allocated to i, "||" denotes parallel execution, ";"
sequential execution, Ranswer is where the answer goes. Perhaps we're on some
machine (VLIW ?) where instructions can be executed in parallel, and maybe
parallel stores to the same register interfere - perhaps the bitwise OR of the
two operands gets written, perhaps you get junk, perhaps the machine traps,
perhaps it scrambles the PC, perhaps it turns into a butterfly and flies to
Berkeley.

With the first of these choices, the conditional delivers TRUE, but i becomes
3. The compiler has done no ``additional work'' - it has just exploited
knowledge about the semantics of C. (It's a pretty idiot savant of a compiler,
of course, because it should probably have an internal check to ensure it never
generates such a rubbish instruction. Then again, if it *did* check, you might
get a compiler message as well:

    Mishap - internal error or source code exploits undefined behaviour
    Somewhere near: (probably a garbled location)

What fun.)

The moral of the story is: there are more architectures in Heaven and Earth,
Horatio, then are dreamed of in your philosophy.



--

Regards, Chris ``GC's should take less than 0.1 second'' Dollin.



More information about the Comp.lang.c mailing list