by scott_s · 13y ago · 0 comments
He is not accusing the compilers of executing undefined behavior. He is accusing them of exploiting undefined behavior to "optimize" code.
His points are:
1. Current compilers will perform optimizations based on undefined behavior. That is, during the optimization phase, they will say "Aha! That's not defined! I'll instead do this much, much faster thing as an optimization."
2. Lots of real code has undefined behavior.
3. The programs that result from these codes still produce the answers we expect, mostly.
4. If we take point 1 to its logical conclusion, then point 2 means that point 3 will no longer be true. That is, if compilers aggressively and thoroughly sought out to find all instances of undefined behavior in C code, and just optimized it away, many (most?) programs would cease to do much at all.
For example, the result of x+y is undefined for signed integers in C, because we want it to compile it to a minimum number of instructions on every architecture. No instructions to check for overflow and branching afterwards. No error correction instructions on architectures where semantics differ to the language semantics.
If it does overflow, it's either a target-specific hand optimization or a programmer error, but that varies on a program-by-program basis, hence GCC having -fwrapv, -ftrapv, and the default of "I don't do that, optimize accordingly".