On Wed, 25 Jun 2025, LIU Hao wrote:
在 2025-6-25 16:08, Martin Storsjö 写道:
The null pointer access in itself is UB, and Clang would previously
optimize based on that being UB, assuming that that code is
unreachable, so it would assume that the printf function never
returns and not generate any code after that call.
Change the pointer into a volatile char, which makes Clang not
infer things about it in the same way, and actually retain the
null pointer write.
This fixes hangs in this testcase on armv7 with msvcrt.
In order to inhibit this optimization, I think this might be better?
char *p = NULL;
__asm__ ("" : "+m"(p)); // pretend `p` is being modified
I'd rather avoid using asm for this purpose, fwiw.
If we insist on use of `volatile` I'd expect the pointer itself is volatile:
char * volatile p = NULL;
That works too, but works in entirely different ways. With the target
being volatile char, the point is that the store must happen (even if the
compiler _knows_ the target is null). With the pointer being volatile, it
forces loading the pointer address from the stack before doing the store.
Either works, I guess it's a matter of taste.
But a different way of inhibiting the optimization entirely, without using
volatile, is to make the variable a global; then the compiler can't assume
anything about it (even if we're running in main, as constructors or
similar could have changed it).
That's probably the simplest, requiring the least amount of magic or odd
constructs.
// Martin
_______________________________________________
Mingw-w64-public mailing list
Mingw-w64-public@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public