Date: Mon, 5 Jun 2023 19:43:03 +0200
Hello, I have a question about following snippet of code
---- void bar(volatile int& b){ b=42; } void foo() { int a = -1; bar(a); } ---- With GCC, clang and MSVC, and optimization enabled, a is set to 42, even if a is not a volatile object, and bar completely inlined inside foo: ---- bar(int volatile&): mov DWORD PTR [rdi], 42 ret foo(): mov DWORD PTR [rsp-4], 42 ret ---- This surprised me, because as far as I know, the standard mostly talks about glvalues > Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine. > Reading an object designated by a volatile glvalue (7.2.1), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. and not about pointers marked as volatile to objects that are not. Thus my understanding was that since a is not volatile, compilers are allowed to optimize the "mov DWORD PTR [rsp-4], 42" away. Is my interpretation incorrect and are those optimizations not allowed, or are compilers less aggressive when there are volatile pointers, as some code bases/users might "hide" non-volatile objects behind pointers to volatile objects to try to avoid some optimization? (removing volatile from the function signature as bar optimizes foo as expected) Best Federico
Received on 2023-06-05 17:43:08