You can't ignore the lack of thread safety. Data races yield undefined behaviour and this code has a data race, so the answer to "Can the compiler assume under strict aliasing that this check for flag being false can be eliminated?" is "The compiler can do whatever it wants."
If you fix that and make the code thread safe with a std::atomic<bool>
, the question disappears: the compiler cannot discard the check because it has to conform to the memory model requirements of atomic variables.
If instead the schedule
call didn't do anything related to multithreading, the compiler has to preserve the semantics of the abstract machine. The abstract machine does check the value of the flag, but a compiler might be able to perform static analysis that proves the flag will always have a certain value (either always false
or always true
) and skip the check. That's allowed under the as-if rule: it is not possible to write a C++ program that can reliably tell the difference between the two possibilities (optimise or not).
So, for the second example, the answer is "The compiler can do whatever it wants, as long as the observable behaviour is the same as if it performed the check."