On Monday, 6 January 2014 at 00:43:22 UTC, Thiez wrote:
On Monday, 6 January 2014 at 00:20:59 UTC, deadalnix wrote:
void foo(int* ptr) {
*ptr;
if (ptr is null) {
// do stuff
}
// do stuff.
}
The code look stupid, but this is quite common after a first
pass of optimization/inlining, do end up with something like
that when a null check if forgotten.
The problem here is that the if can be removed, as you can't
reach that point if the pointer is null, but *ptr can also be
removed later as it is a dead load.
The resulting code won't crash and do random shit instead.
If you read
http://people.csail.mit.edu/akcheung/papers/apsys12.pdf there
is a nice instance where a compiler moved a division above the
check that was designed to prevent division by zero, because it
assumed a function would return (when in fact it wouldn't). I
imagine a similar scenario could happen with a null pointer,
e.g.:
if (ptr is null) {
perform_function_that_never_returns();
}
auto x = *ptr;
If the compiler assumes that
'perform_function_that_never_returns()' returns, it will
recognize the whole if-statement and its body as dead code.
Optimizers can be a little too smart for their own good at
times.
Your example is a bug in the optimizer. Mine isn't.