[libcxx-commits] [libcxx] [libc++] Use _BitInt and __builtin_popcountg in bitset::count() (PR #160679)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Sep 25 06:26:36 PDT 2025


================
@@ -867,7 +867,16 @@ bitset<_Size>::to_string(char __zero, char __one) const {
 
 template <size_t _Size>
 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 size_t bitset<_Size>::count() const _NOEXCEPT {
-  return static_cast<size_t>(std::count(__base::__make_iter(0), __base::__make_iter(_Size), true));
+#  if defined(_LIBCPP_COMPILER_CLANG_BASED) && !defined(_LIBCPP_CXX03_LANG)
+  if constexpr (_Size == 0) {
+    return 0;
+  } else if constexpr (_Size <= __base::__bits_per_word) {
+    return __builtin_popcountg(static_cast<unsigned _BitInt(_Size)>(__base::__first_));
+  } else
----------------
ldionne wrote:

Do we really need this `else`? Can't we have

```c++
#if defined(CLANG)
if constexpr (...) {
  // A
} else if constexpr (...) {
 // B
}
#endif

return std::count(...);
```

Seems a bit simpler and equivalent. Are you worried about the mere presence of `return std::count(...)` preventing inlining?

https://github.com/llvm/llvm-project/pull/160679


More information about the libcxx-commits mailing list