[libc-commits] [libc] [libc][__support][bit] Switch popcount to Brian Kernighan’s Algorithm (PR #95625)
via libc-commits
libc-commits at lists.llvm.org
Fri Jun 14 17:01:48 PDT 2024
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-libc
Author: Ryan Beltran (rpbeltran)
<details>
<summary>Changes</summary>
This swaps the algorithm used for popcount to Brian Kernighan’s Algorithm[1] when __builtin_popcount is not available.
The while loop runs once per set bit instead of once per digit as before which is slightly better on average.
[1] https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
---
Full diff: https://github.com/llvm/llvm-project/pull/95625.diff
1 Files Affected:
- (modified) libc/src/__support/CPP/bit.h (+4-3)
``````````diff
diff --git a/libc/src/__support/CPP/bit.h b/libc/src/__support/CPP/bit.h
index 8a8951a18bfa1..4aea066d26ab0 100644
--- a/libc/src/__support/CPP/bit.h
+++ b/libc/src/__support/CPP/bit.h
@@ -271,9 +271,10 @@ template <typename T>
[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
popcount(T value) {
int count = 0;
- for (int i = 0; i != cpp::numeric_limits<T>::digits; ++i)
- if ((value >> i) & 0x1)
- ++count;
+ while (value) {
+ value &= value - 1;
+ ++count;
+ }
return count;
}
#define ADD_SPECIALIZATION(TYPE, BUILTIN) \
``````````
</details>
https://github.com/llvm/llvm-project/pull/95625
More information about the libc-commits
mailing list