From 654d8d6cf368233018c3df2f84f1118603839ac5 Mon Sep 17 00:00:00 2001 From: Tiago Freire <67021355+tmiguelf@users.noreply.github.com> Date: Wed, 6 Mar 2024 13:50:45 +0100 Subject: [PATCH] Fixed LTO issue on no discard variable (#1761) Improve `UseCharPointer()` (thus, `DoNotOptimize()`) under MSVC LTO, make it actually escape the pointer and prevent it from being optimized away. --- src/benchmark.cc | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/benchmark.cc b/src/benchmark.cc index 31f2cde8..563c4438 100644 --- a/src/benchmark.cc +++ b/src/benchmark.cc @@ -152,8 +152,16 @@ BENCHMARK_EXPORT std::map*& GetGlobalContext() { return global_context; } -// FIXME: wouldn't LTO mess this up? -void UseCharPointer(char const volatile*) {} +static void const volatile* volatile global_force_escape_pointer; + +// FIXME: Verify if LTO still messes this up? +void UseCharPointer(char const volatile* const v) { + // We want to escape the pointer `v` so that the compiler can not eliminate + // computations that produced it. To do that, we escape the pointer by storing + // it into a volatile variable, since generally, volatile store, is not + // something the compiler is allowed to elide. + global_force_escape_pointer = reinterpret_cast(v); +} } // namespace internal