[libcxx-commits] [libcxx] [libc++] Optimize std::has_single_bit (PR #133063)

via libcxx-commits libcxx-commits at lists.llvm.org
Wed Mar 26 02:59:44 PDT 2025


https://github.com/Alcaro created https://github.com/llvm/llvm-project/pull/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.)

>From 549d11d551f8efbc572e4a847f5dfaf0da08709a Mon Sep 17 00:00:00 2001
From: Alcaro <floating at muncher.se>
Date: Wed, 26 Mar 2025 10:46:19 +0100
Subject: [PATCH] [libc++] Optimize std::has_single_bit

---
 libcxx/include/__bit/has_single_bit.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__bit/has_single_bit.h b/libcxx/include/__bit/has_single_bit.h
index 52f5853a1bc8a..ac434092a148f 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 <__libcpp_unsigned_integer _Tp>
 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool has_single_bit(_Tp __t) noexcept {
-  return __t != 0 && (((__t & (__t - 1)) == 0));
+  return (__t ^ (__t - 1)) > __t - 1;
 }
 
 _LIBCPP_END_NAMESPACE_STD



More information about the libcxx-commits mailing list