benchmark icon indicating copy to clipboard operation
benchmark copied to clipboard

[BUG] DoNotOptimize() doesn't prevent gcc/clang from optimizing out array lookup

Open gizlu opened this issue 2 years ago • 3 comments

Describe the bug DoNotOptimize() doesn't prevent gcc from optimizing out array lookup.

System

  • x86, godbolt, gcc 12.1, clang 14.0.0, google benchmark 1.6.1

To reproduce See assembly produced for this: https://godbolt.org/z/ahPss8hvY On clang -O2 everything is ok - addition and mov from LUT array On gcc -O2 - mov is missing

Expected behavior DoNotOptimize() should prevent gcc from optimizing out array lookup

Edit: example minimisation

gizlu avatar Jul 18 '22 13:07 gizlu

Update: Removing const specifier from array definition triggers this bug also on clang. See https://godbolt.org/z/fETxqYaqn

gizlu avatar Jul 22 '22 15:07 gizlu

Just a note.

There are special cases for GCC but even applying the same rules for clang, it still optimizes away.

https://godbolt.org/z/KTW4sf6P9

HFTrader avatar Mar 07 '23 16:03 HFTrader

It looks like just doing something with the passed variable prevents GCC from optimizing it. GCC seems to sense that the generated assembly is empty.

https://godbolt.org/z/esd8hE6T9

This works:

template <class Tp>
inline BENCHMARK_ALWAYS_INLINE void DNO(Tp const& value) {
  asm volatile("xor %0, %0" : : "r,m"(value) : "memory");
}

HFTrader avatar Mar 07 '23 16:03 HFTrader