Last active
April 16, 2024 10:45
-
-
Save WiwilZ/dc6a608f5ac3ff797a570577d26430b6 to your computer and use it in GitHub Desktop.
DoNotOptimize function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #if defined(_MSC_VER) && !defined(__clang__) | |
| namespace detail { | |
| #pragma optimize("", off) | |
| void DoNotOptimizeImpl(const void*) noexcept {} | |
| #pragma optimize("", on) | |
| } | |
| [[msvc::forceinline]] void DoNotOptimize(const auto& x) noexcept { | |
| Detail::DoNotOptimizeImpl(&x); | |
| } | |
| #else | |
| #include <type_traits> | |
| namespace detail { | |
| template <typename T> | |
| concept InRegister = std::is_trivially_copyable_v<T> && sizeof(T) <= sizeof(T*) && !std::is_pointer_v<T>; | |
| template <typename T> | |
| concept InMemory = !InRegister<T>; | |
| } | |
| [[gnu::always_inline]] void DoNotOptimize(const detail::InRegister auto& x) noexcept { | |
| asm volatile("" : : "r"(x)); | |
| } | |
| [[gnu::always_inline]] void DoNotOptimize(const detail::InMemory auto& x) noexcept { | |
| asm volatile("" : : "m"(x) : "memory"); | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment