From 29e0494e56b88edf8abe71c07f8df8f7b7979e20 Mon Sep 17 00:00:00 2001 From: Hediadyoin1 Date: Tue, 16 May 2023 15:07:17 +0200 Subject: [PATCH] AK: Use builtins in fabs implementation and move it to the top Both GCC and Clang inline this function to use bit-wise logic and/or appropriate instructions even on -O0 and allow their use in a constexpr context, see https://godbolt.org/z/de1393vha --- AK/Math.h | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/AK/Math.h b/AK/Math.h index ef3b3a702f3..cd544da4a9b 100644 --- a/AK/Math.h +++ b/AK/Math.h @@ -81,6 +81,18 @@ constexpr size_t product_odd() { return value * product_odd(); } return res; \ } +template +constexpr T fabs(T x) +{ + // Both GCC and Clang inline fabs by default, so this is just a cmath like wrapper + if constexpr (IsSame) + return __builtin_fabsl(x); + if constexpr (IsSame) + return __builtin_fabs(x); + if constexpr (IsSame) + return __builtin_fabsf(x); +} + namespace Rounding { template constexpr T ceil(T num) @@ -494,23 +506,6 @@ constexpr T cbrt(T x) return r; } -template -constexpr T fabs(T x) -{ - if (is_constant_evaluated()) - return x < 0 ? -x : x; -#if ARCH(X86_64) - asm( - "fabs" - : "+t"(x)); - return x; -#elif ARCH(AARCH64) - AARCH64_INSTRUCTION(fabs, x); -#else - return __builtin_fabs(x); -#endif -} - namespace Trigonometry { template