Skip to content

DoNotOptimize on values with const members #764

@ldionne

Description

@ldionne

DoNotOptimize produces an error when used on a variable with a const member:

$ clang++ --version
clang version 9.0.0

$ cat <<EOF | clang++ -xc++ - -isystem <path-to-google-benchmark> -std=c++17
#include <benchmark/benchmark.h>

struct Foo { int const data = 0; };

int main() {
    Foo foo{};
    benchmark::DoNotOptimize(foo);
}
EOF

The output is:

In file included from <stdin>:1:
<snip>/include/benchmark/benchmark.h:322:28: error: invalid lvalue in asm
      output
  asm volatile("" : "+r,m"(value) : : "memory");
                           ^~~~~
<stdin>:12:16: note: in instantiation of function template specialization 'benchmark::DoNotOptimize<Foo>' requested
      here
    benchmark::DoNotOptimize(foo);
               ^
1 error generated.

I assume this is because Clang looks at the output operands of the inline assembly and sees that one of the members of foo is const, and thus can't be written to. This used to work until Clang 6 if I'm not mistaken. I'm not sure this is an actual problem with Google Benchmark, but could you please suggest an alternative? I can think of the following:

  1. Use ClobberMemory() instead. This is a bigger hammer than I'd like, however.
  2. Pass a char* to the object instead, like so:
    Foo foo{};
    char* foop = reinterpret_cast<char*>(&foo);
    benchmark::DoNotOptimize(*foop);
    I'm not sure this has the intended effect.
  3. Do not make the member const. This is not really an option in my case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions