with clang 13, optimization of undefined behavior incorrectly eliminates conditional earlier in the function
Beginning with clang 13.0.0, the following behavior is observed beginning at -O1:
extern int foo;
void bar(void);
int foo;
void comparison_eliminated() {
// clang 13+ eliminates this conditional at O1+
if ( foo ) {
bar();
}
// ...but only in the presence of undefined behavior.
// Comment out these two lines and the conditional returns.
char* a = 0;
*a = '\0';
}
With clang 12, this behavior does not happen.
I realize with the undefined behavior in place all bets are off to a some degree. But is it expected that eliminating the null dereference here would also result in bar being called unconditionally? Or is there a bug within the UB optimization?
Thanks!
I think the optimizer is within its rights to perform this information. The reasoning likely used is that we can determine that the null pointer dereference cannot happen (as it is UB), so the only valid non-UB execution of the function is that foo is true and bar executes but never returns.
@fhahn Please forgive me if I'm missing something, but:
so the only valid non-UB execution of the function is that foo is true and bar executes but never returns.
What about the case of foo being false? It's non-const, non-static and its value could change over the lifetime of the program. Even if the null pointer dereference is eliminated, bar should only be invoked when foo is actually true, correct?
Clang/LLVM assumes UB can never happen. If foo would be false, the nullptr dereference would be executed, meaning we hit UB and technically anything can happen. In this case , it's bar being executed. In other words, we assume that UB can never happen, hence foo must always be true.
Thank you for the explanation. With those additional details I understand your initial response now. 😅