Replace platform-specific ctz/clz definitions with C++20 <bit> functions

This commit is contained in:
Rangi authored and Eldred Habert committed 2026-11-24 17:57:23 +01:00
1 parent 4af382101b
commit edfb9c15d5
3 files changed
+7 -57

No files matched your search

-47
View File
@@ -40,53 +40,6 @@ static inline void unreachable_() {
#define assume assert
#endif
// Ideally we'd use `std::bit_width`, but it has insufficient compiler support
#ifdef __GNUC__ // GCC or compatible
#define ctz __builtin_ctz
#define clz __builtin_clz
#elif defined(_MSC_VER)
#include <intrin.h>
#pragma intrinsic(_BitScanReverse, _BitScanForward)
static inline int ctz(unsigned int x) {
assume(x != 0);
unsigned long count;
_BitScanForward(&count, x);
return count;
}
static inline int clz(unsigned int x) {
assume(x != 0);
unsigned long count;
_BitScanReverse(&count, x);
return 31 - count;
}
#else
#include <limits.h>
static inline int ctz(unsigned int x) {
assume(x != 0);
int count = 0;
while (!(x & 1)) {
x >>= 1;
++count;
}
return count;
}
static inline int clz(unsigned int x) {
assume(x != 0);
int count = 0;
while (x <= UINT_MAX / 2) {
x <<= 1;
++count;
}
return count;
}
#endif
// Macros for stringification
#define STR(x) #x
#define EXPAND_AND_STR(x) STR(x)
+3 -7
View File
@@ -5,6 +5,7 @@
#include "fix/fix.hpp"
#include <sys/stat.h>
#include <bit>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
@@ -305,14 +306,9 @@ static void
assume(rom0Len == sizeof(rom0));
}
assume(nbBanks >= 2);
// Alter number of banks to reflect required value
// x&(x-1) is zero iff x is a power of 2, or 0; we know for sure it's non-zero,
// so this is true (non-zero) when we don't have a power of 2
if (nbBanks & (nbBanks - 1)) {
nbBanks = 1 << (CHAR_BIT * sizeof(nbBanks) - clz(nbBanks));
}
nbBanks = std::bit_ceil(nbBanks);
// Write final ROM size
rom0[0x148] = ctz(nbBanks / 2);
rom0[0x148] = std::countr_zero(nbBanks / 2);
// Alter global checksum based on how many bytes will be added (not counting ROM0)
globalSum += options.padValue * ((nbBanks - 1) * BANK_SIZE - totalRomxLen);
}
+4 -3
View File
@@ -4,9 +4,10 @@
#include "opmath.hpp"
#include <bit>
#include <stdint.h>
#include "helpers.hpp" // assume, clz, ctz
#include "helpers.hpp" // assume
// Signed overflow is UB, so these compute with unsigned arithmetic, which wraps around.
// Casting back is OK because the types implement two's complement behavior.
@@ -135,9 +136,9 @@ int32_t op_low(int32_t value) {
}
int32_t op_bitwidth(int32_t value) {
return value != 0 ? 32 - clz(static_cast<uint32_t>(value)) : 0;
return std::bit_width(static_cast<uint32_t>(value));
}
int32_t op_tzcount(int32_t value) {
return value != 0 ? ctz(static_cast<uint32_t>(value)) : 32;
return std::countr_zero(static_cast<uint32_t>(value));
}