4 ms·
The article you linked says that compilers can prove a lack of overflow in this example, so UB is not necessary to assume here. It also claims that the compiler
by dooglius 6y ago
The article you linked says that compilers can prove a lack of overflow in this example, so UB is not necessary to assume here. It also claims that the compiler cannot prove this in more complex examples (but gives no explicit examples). What I'm saying is if the compiler cannot prove a lack of overflow in this way, that should be a warning.
- aw1621107 6y ago> The article you linked says that compilers can prove a lack of overflow in this example, so UB is not necessary to assume here. It's trivial to prove in that particular example because it's assumed that count is also an int (both i and count are in 32-bit registers). > It also claims that the compiler cannot prove this in more complex examples (but gives no explicit examples). The example doesn't even have to be that complex; you just need sizeof(n) > sizeof(i) and i to be signed (godbolt example at [0]). In that example, if the compiler can assume signed overflow is UB, then you get fairly sensible code generation. If the compiler cannot make that assumption (add the -fwrapv flag), then you get that movsxd instruction in the middle of the loop body. If you use -O2 instead of -O1, then -fwrapv prevents loop unrolling. > What I'm saying is if the compiler cannot prove a lack of overflow in this way, that should be a warning. I'm curious how frequently this warning might fire in real-life codebases, or when it does fire how frequently it's something the programmer can actually fix. Clang does have -Rpass-missed to emit some diagnostics when an optimization cannot be performed, but it doesn't emit anything in this particular case (though I'm not sure whether it's supposed to). [0]: https://godbolt.org/z/abq3n9 https://godbolt.org/z/abq3n9