[libcxx-commits] [libcxx] 274a4c0 - [libc++] Optimize std::has_single_bit (#133063)
via libcxx-commits
libcxx-commits at lists.llvm.org
Fri Nov 21 04:59:43 PST 2025
Author: Alcaro
Date: 2025-11-21T13:59:38+01:00
New Revision: 274a4c0c03af8f37108479328285299414268cfa
URL: https://github.com/llvm/llvm-project/commit/274a4c0c03af8f37108479328285299414268cfa
DIFF: https://github.com/llvm/llvm-project/commit/274a4c0c03af8f37108479328285299414268cfa.diff
LOG: [libc++] Optimize std::has_single_bit (#133063)
Clang translates most implementations of has_single_bit to `(v ^ (v-1))
> v-1` - except the one definition libc++ actually uses.
Proof of correctness: https://godbolt.org/z/d61bxW4r1
(Could also be fixed by teaching Clang to optimize better, but making
source match output feels clearer to me. And it improves unoptimized
performance.)
Added:
Modified:
libcxx/include/__bit/has_single_bit.h
Removed:
################################################################################
diff --git a/libcxx/include/__bit/has_single_bit.h b/libcxx/include/__bit/has_single_bit.h
index d10ab7d6c1791..c49c518f2b98c 100644
--- a/libcxx/include/__bit/has_single_bit.h
+++ b/libcxx/include/__bit/has_single_bit.h
@@ -25,7 +25,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD
template <__unsigned_integer _Tp>
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool has_single_bit(_Tp __t) noexcept {
- return __t != 0 && ((__t & (__t - 1)) == 0);
+ return __builtin_popcountg(__t) == 1;
}
_LIBCPP_END_NAMESPACE_STD
More information about the libcxx-commits
mailing list