Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clang vs gcc: different code for volatile access

Consider this example:

volatile unsigned int x;
unsigned int y;

void f() {
    x /= 2;
}
void g() {
    y /= 2;
}

When compiled with -Os, clang-6.0 produces on x64 for both f and g the same shrl <offset>(%rip) instruction pattern (See https://godbolt.org/g/hUPprL), while gcc-7.3 produces this (See https://godbolt.org/g/vMcKVV) for f():

 mov 0x200b67(%rip),%eax # 601034 <x>
 shr %eax
 mov %eax,0x200b5f(%rip) # 601034 <x>

Is this just a missed optimization or is there a justification for gcc to reject shrl <offset>(%rip) in case of volatile access? Who is wrong?

like image 662
Nordic Mainframe Avatar asked Apr 26 '18 09:04

Nordic Mainframe


People also ask

Does Clang optimize better than GCC?

Clang reduces the single-thread compilation time by 5% to 10% compared with GCC. Therefore, Clang offers more advantages for the construction of large projects.

Is GCC and Clang the same?

Clang is designed as an API from its inception, allowing it to be reused by source analysis tools, refactoring, IDEs (etc) as well as for code generation. GCC is built as a monolithic static compiler, which makes it extremely difficult to use as an API and integrate into other tools.

Is Clang slower than GCC?

GCC is slower to compile than clang, so I spend a lot of time compiling, but my final system is (usually) faster with GCC, so I have set GCC as my system compiler.

Is Clang replacing GCC?

Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC), supporting most of its compilation flags and unofficial language extensions.

Is Clang compatible with GCC?

GCC and C99 allow an array's size to be determined at run time. This extension is not permitted in standard C++. However, Clang supports such variable length arrays for compatibility with GNU C and C99 programs. If you would prefer not to use this extension, you can disable it with -Werror=vla.


1 Answers

This is just a missed optimization by gcc. Both implementations preserve the read from and write to x precisely, and thus are correct.

"Under the hood" operating on a memory operand performs the same loads and stores as the longer implementation.

like image 83
PaulR Avatar answered Sep 28 '22 19:09

PaulR