From 6ff2db181f3dc8a9c95f6f9564c0bb1db7cae8e3 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Thu, 21 Jan 2021 03:48:32 -0500 Subject: bit_util: Unify implementations of MostSignificantBit32/MostSignificantBit64 We can use the standardized CLZ facilities to perform this. This also allows us to make utilizing functions constexpr and eliminate the inclusion of an intrinsics header. --- src/common/bit_util.h | 48 +++++++++++++----------------------------------- 1 file changed, 13 insertions(+), 35 deletions(-) (limited to 'src/common') diff --git a/src/common/bit_util.h b/src/common/bit_util.h index 685e7fc9b..69fb4e5e4 100644 --- a/src/common/bit_util.h +++ b/src/common/bit_util.h @@ -7,10 +7,6 @@ #include #include -#ifdef _MSC_VER -#include -#endif - #include "common/common_types.h" namespace Common { @@ -21,48 +17,30 @@ template return sizeof(T) * CHAR_BIT; } -#ifdef _MSC_VER - -[[nodiscard]] inline u32 MostSignificantBit32(const u32 value) { - unsigned long result; - _BitScanReverse(&result, value); - return static_cast(result); -} - -[[nodiscard]] inline u32 MostSignificantBit64(const u64 value) { - unsigned long result; - _BitScanReverse64(&result, value); - return static_cast(result); -} - -#else - -[[nodiscard]] inline u32 MostSignificantBit32(const u32 value) { - return 31U - static_cast(__builtin_clz(value)); +[[nodiscard]] constexpr u32 MostSignificantBit32(const u32 value) { + return 31U - static_cast(std::countl_zero(value)); } -[[nodiscard]] inline u32 MostSignificantBit64(const u64 value) { - return 63U - static_cast(__builtin_clzll(value)); +[[nodiscard]] constexpr u32 MostSignificantBit64(const u64 value) { + return 63U - static_cast(std::countl_zero(value)); } -#endif - -[[nodiscard]] inline u32 Log2Floor32(const u32 value) { +[[nodiscard]] constexpr u32 Log2Floor32(const u32 value) { return MostSignificantBit32(value); } -[[nodiscard]] inline u32 Log2Ceil32(const u32 value) { - const u32 log2_f = Log2Floor32(value); - return log2_f + ((value ^ (1U << log2_f)) != 0U); +[[nodiscard]] constexpr u32 Log2Floor64(const u64 value) { + return MostSignificantBit64(value); } -[[nodiscard]] inline u32 Log2Floor64(const u64 value) { - return MostSignificantBit64(value); +[[nodiscard]] constexpr u32 Log2Ceil32(const u32 value) { + const u32 log2_f = Log2Floor32(value); + return log2_f + static_cast((value ^ (1U << log2_f)) != 0U); } -[[nodiscard]] inline u32 Log2Ceil64(const u64 value) { - const u64 log2_f = static_cast(Log2Floor64(value)); - return static_cast(log2_f + ((value ^ (1ULL << log2_f)) != 0ULL)); +[[nodiscard]] constexpr u32 Log2Ceil64(const u64 value) { + const u64 log2_f = Log2Floor64(value); + return static_cast(log2_f + static_cast((value ^ (1ULL << log2_f)) != 0ULL)); } } // namespace Common -- cgit v1.2.3