4 ms·
Yes, there are a number of optimizations that require UB, or something like it. For example, say you have this valid C or Rust code: if (my_signed_int + 1
by smitherfield 9y ago
Yes, there are a number of optimizations that require UB, or something like it. For example, say you have this valid C or Rust code:
if (my_signed_int + 1 > my_signed_int) {
foo();
}
Since signed integer overflow is UB in C, C compilers can optimize out the conditional, but since Rust specifies that overflow may wrap, the compiler can’t assume the condition is true.
- steveklabnik 9y agoTo be clear here, overflow is a "program error" in Rust; it's specified to panic in debug builds, and any build where it doesn't panic is defined as wrapping two's compliment. I tried to toss this into godbolt, but the optimizer is too good of course, it will optimize away the entire if if my_signed_int is a literal. Here's one without optimizations: https://godbolt.org/g/tBZcTA https://godbolt.org/g/tBZcTA It seems to compare 1 to 1, and then branch. My guess, though this isn't my area of specialty, is that this is because it is also assuming that overflow can't happen, making this always true. Clang, interestingly enough, does the load, add, and compare https://godbolt.org/g/gPjgVc https://godbolt.org/g/gPjgVc
- smitherfield 9y agoRust does do the loop condition (well, comparing `my_signed_int` to INT_MAX) even with optimizations: https://godbolt.org/g/dnBEJi https://godbolt.org/g/dnBEJi (You need to put a side effect such as I/O in the conditional branch for it not be optimized away, "pub" before the function declaration for it not to be eliminated as dead code, and pass `my_signed_int` as an argument so the condition isn't constant-folded). Clang OTOH optimizes away the condition with even the lowest optimization level (-Og) turned on, as you'd expect: https://godbolt.org/g/8ftkED https://godbolt.org/g/8ftkED
- steveklabnik 9y agoAh, nicely done.