|
| 1 | +#pragma once |
| 2 | + |
| 3 | +namespace gamescope::Directives { |
| 4 | + struct FlagSwitcher { |
| 5 | + unsigned long long m_csr = 0ull; |
| 6 | + inline FlagSwitcher(); |
| 7 | + inline ~FlagSwitcher(); |
| 8 | + }; |
| 9 | +} |
| 10 | + |
| 11 | +#if defined(__x86__) || defined(__x86_64__) |
| 12 | +# include <xmmintrin.h> |
| 13 | +# include <pmmintrin.h> |
| 14 | +# define SET_FAST_MATH_FLAGS gamescope::Directives::FlagSwitcher switcher{}; |
| 15 | + |
| 16 | + inline gamescope::Directives::FlagSwitcher::FlagSwitcher() : m_csr{_mm_getcsr()} { |
| 17 | + _mm_setcsr( (unsigned int)m_csr | _MM_DENORMALS_ZERO_ON | _MM_FLUSH_ZERO_ON ); |
| 18 | + } |
| 19 | + |
| 20 | + inline gamescope::Directives::FlagSwitcher::~FlagSwitcher() { |
| 21 | + _mm_setcsr( (unsigned int)m_csr ); |
| 22 | + } |
| 23 | + |
| 24 | +#elif defined(__aarch64__) && __has_builtin(__builtin_aarch64_get_fpcr64) && __has_builtin(__builtin_aarch64_set_fpcr64) |
| 25 | +# define SET_FAST_MATH_FLAGS gamescope::Directives::FlagSwitcher switcher{}; |
| 26 | + |
| 27 | + static constexpr unsigned long long fz_bit = 0x1'00'00'00; |
| 28 | + //based on this stuff: https://github.com/DLTcollab/sse2neon/blob/706d3b58025364c2371cafcf9b16e32ff7e630ed/sse2neon.h#L2433 |
| 29 | + //and this: https://stackoverflow.com/a/59001820 |
| 30 | + static constexpr unsigned long long fz16_bit = 0x8'00'00; |
| 31 | + |
| 32 | + inline gamescope::Directives::FlagSwitcher::FlagSwitcher() : m_csr{__builtin_aarch64_get_fpcr64()} { |
| 33 | + __builtin_aarch64_set_fpcr64(m_csr | fz_bit | fz16_bit); |
| 34 | + } |
| 35 | + |
| 36 | + inline gamescope::Directives::FlagSwitcher::~FlagSwitcher() { |
| 37 | + __builtin_aarch64_set_fpcr64(m_csr); |
| 38 | + } |
| 39 | + |
| 40 | +#else |
| 41 | +# define SET_FAST_MATH_FLAGS |
| 42 | + |
| 43 | +#endif |
| 44 | + |
| 45 | +#ifdef __clang__ |
| 46 | +# define FAST_MATH_ON _Pragma("float_control(push)"); \ |
| 47 | + _Pragma("float_control(precise, off)") //https://clang.llvm.org/docs/LanguageExtensions.html#extensions-to-specify-floating-point-flags |
| 48 | +# define FAST_MATH_OFF _Pragma("float_control(pop)") |
| 49 | + |
| 50 | +#elif defined(__GNUC__) |
| 51 | +# define FAST_MATH_ON _Pragma("GCC push_options"); \ |
| 52 | + _Pragma("GCC optimize(\"-ffast-math\")") |
| 53 | +# define FAST_MATH_OFF _Pragma("GCC pop_options") |
| 54 | + |
| 55 | +#else |
| 56 | +# define FAST_MATH_ON |
| 57 | +# define FAST_MATH_OFF |
| 58 | +#endif |
0 commit comments