Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[libc][support][bit] use new type generic builtins #86746

Merged
merged 2 commits into from
Apr 5, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions libc/src/__support/CPP/bit.h
Expand Up @@ -72,6 +72,14 @@ has_single_bit(T value) {
/// Only unsigned integral types are allowed.
///
/// Returns cpp::numeric_limits<T>::digits on an input of 0.
// clang-19+, gcc-14+
#if __has_builtin(__builtin_ctzg)
template <typename T>
[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
countr_zero(T value) {
return __builtin_ctzg(value, cpp::numeric_limits<T>::digits);
}
#else
template <typename T>
[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
countr_zero(T value) {
Expand Down Expand Up @@ -99,16 +107,25 @@ ADD_SPECIALIZATION(countr_zero, unsigned short, __builtin_ctzs)
ADD_SPECIALIZATION(countr_zero, unsigned int, __builtin_ctz)
ADD_SPECIALIZATION(countr_zero, unsigned long, __builtin_ctzl)
ADD_SPECIALIZATION(countr_zero, unsigned long long, __builtin_ctzll)
#endif // __has_builtin(__builtin_ctzg)

/// Count number of 0's from the most significant bit to the least
/// stopping at the first 1.
///
/// Only unsigned integral types are allowed.
///
/// Returns cpp::numeric_limits<T>::digits on an input of 0.
// clang-19+, gcc-14+
#if __has_builtin(__builtin_clzg)
template <typename T>
[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
countl_zero(T value) {
return __builtin_clzg(value, cpp::numeric_limits<T>::digits);
}
#else
template <typename T [[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<
nickdesaulniers marked this conversation as resolved.
Show resolved Hide resolved
cpp::is_unsigned_v<T>, int>
countl_zero(T value) {
if (!value)
return cpp::numeric_limits<T>::digits;
// Bisection method.
Expand All @@ -129,6 +146,7 @@ ADD_SPECIALIZATION(countl_zero, unsigned short, __builtin_clzs)
ADD_SPECIALIZATION(countl_zero, unsigned int, __builtin_clz)
ADD_SPECIALIZATION(countl_zero, unsigned long, __builtin_clzl)
ADD_SPECIALIZATION(countl_zero, unsigned long long, __builtin_clzll)
#endif // __has_builtin(__builtin_clzg)

#undef ADD_SPECIALIZATION

Expand Down