llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Volatile is discarded in the frontend during a cast to a reference to a volatile type

Open jeremy-rifkin opened this issue 4 years ago • 5 comments

Loads and stores of references to volatile variables aren't reflected in the generated IR as being as volatile. None of const_cast<volatile int&>(x), static_cast<volatile int&>(x), or (volatile int&)(x) are properly reflected. If I'm understanding correctly, f0 here should be generating six add instructions and the InstCombine should not be allowed

void f0() {
    const_cast<volatile int&>(x) = const_cast<volatile int&>(x) + 1;
    const_cast<volatile int&>(x) = const_cast<volatile int&>(x) + 1;
    static_cast<volatile int&>(x) = static_cast<volatile int&>(x) + 1;
    static_cast<volatile int&>(x) = static_cast<volatile int&>(x) + 1;
    (volatile int&)x = (volatile int&)(x) + 1;
    (volatile int&)x = (volatile int&)(x) + 1;
}
f0():                                 # @f0()
        add     dword ptr [rip + x], 6
        ret

Volatile is respected if it's in the context of a pointer or a reference variable is created.

https://godbolt.org/z/hE6xxP8To

GCC and MSVC do not fold the increments in f0: https://godbolt.org/z/hEPe66cjT.

jeremy-rifkin avatar May 01 '22 08:05 jeremy-rifkin

@llvm/issue-subscribers-clang-codegen

llvmbot avatar May 01 '22 13:05 llvmbot

Smaller repro where a write is removed in EarlyCSEPass: https://godbolt.org/z/Y9rz64vbr

void asdf(int &x)
{
    static_cast<volatile int &>(x) = 1;
    static_cast<volatile int &>(x) = 2;
}
asdf(int&):                              # @asdf(int&)
        mov     dword ptr [rdi], 2
        ret

molinari avatar Jul 05 '22 06:07 molinari

I think EarlyCSEPass is behaving correctly, clang should be generating store volatiles (which EarlyCSEPass would not remove). (Issue should probably be updated to have a clang frontend label).

(Ps I'm the author of the llvm opt pass view tool on compiler explorer and I'm thrilled to see it being used in bug reports already, especially my own bugs!)

jeremy-rifkin avatar Jul 05 '22 23:07 jeremy-rifkin

has anyone started working on this??

Long5hot avatar Aug 11 '23 05:08 Long5hot

Review :https://reviews.llvm.org/D157890

ukalappa-mips avatar Aug 15 '23 15:08 ukalappa-mips