by lmm · 6y ago · 0 comments
That's very much disputed. The C standard requires programs' behaviour to be as-if executed on the C abstract machine when they terminate. It's not at all clear whether the standard imposes any requirements on programs that would not terminate when executed on the C abstract machine.
"An iteration statement whose controlling expression is not a constant expression, that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate."
(I'm personally not happy that this is stated in terms of that the implementation may assume rather than what a program may do.)
Note that this does not apply to infinite loops with constant conditions. For example, given `while (1) { /* ... */ }`, the above doesn't apply and the implementation may not assume the loop will terminate.
Where is that guaranteed? I can see that the above rule suggests that the implementation may not make that assumption, but it doesn't actually rule it out.
pub fn mul1(mut a: i32, b:i32) -> i32 {
let mut out = 0;
while a != 0 {
out += b;
a-=1;
}
out
}
pub fn mul2(a: i32, b: i32) -> i32 {
if a == 0 {
0
} else {
b + mul2(a-1, b)
}
}
Both are optimized to imul. But that's not actually correct: neither of these should terminate for negative a!Incidentally, this is actually a rust bug, caused by LLVM performing this optimization despite it being illegal in rust.
Presumably the same is true for LLVM IR, which would mean that it's Rust's responsibility to emit code that checks for that case since in Rust under/overflow is defined. Very interesting compiler bug! I noticed that they haven't fixed it for the latest version. Did you submit the bug report to Rust?
I think it depends on the flags the multiplication operation is emitted with; namely, the nsw and nuw (no signed/unsigned wrap) would denote whether the optimization LLVM does is correct. If rust emits those flags then that would be a Rust bug; if Rust does not, then it might be an LLVM bug (I'm not sure what LLVM's semantics are for regular imul without flags).
But you could also have something like:
while(true) {
if(some condition) {
do stuff;
break;
}
}
In this case, a compiler might be allowed to assume that 'some condition' happens to be true eventually.If "some condition" is actually testing a variable for equality, then you could do constant-folding.
(And to make it closer to our situation, assume that the loop being executed was looking for something that actually has a counterexample that could be found after a long time; instead of Fermat's last theorem.)