llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.39k stars 12.15k forks source link

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

Open jeremy-rifkin opened 2 years ago

jeremy-rifkin commented 2 years ago

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.

llvmbot commented 2 years ago

@llvm/issue-subscribers-clang-codegen

molinari commented 2 years ago

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
jeremy-rifkin commented 2 years ago

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!)

Long5hot commented 1 year ago

has anyone started working on this??

UmeshKalappa0 commented 1 year ago

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