> Here's an example from the intprops module of gnulib. These are interesting case.
Note that all the computations are constant-folded. And I think this points the fact that we can "have our cake and eat it too" in many cases. Everything we're seeing points to the fact that the cases where assuming undefined behavior for overflow will help optimizations are cases where few if any sane programmers would write the code depending on wrap semantics (e.g., loop variables). And nearly all the cases where wrap semantics are expected (e.g., the above) are such that there's no reasonable optimization benefit in assuming they're undefined. Take constant folding: if we were pendantic about it, we could say, "this folded expression overflows and so is undefined, so let's set its value to be whatever constant would yield the most efficient code in that case". Such behavior would be standard-compliant, but as unfriendly as possible because it wouldn't "optimize" any real code, just break common idioms. I doubt anybody would suggest not implementing wrapping semantics in constant folding. > I would really like to see gcc be able to warn when it is exploiting > optimization opportunities based on undefined wrap semantics, so that code > can easily be made robust against overflow without having to rely on > tedious code audits. In my opinion, the expectation of sane overflow > semantics is just too pervasive in existing code to be able to audit > without compiler assistance. Even if you avoid doing things like the above? The problem is that such opportunities are all OVER the place and, in practice, there are nearly no actual overflows, so the number of false positives of such a warning is HUGE.