[clang-tools-extra] [clang-tidy] Detect std::popcount opportunity within modernize.use-std-bit (PR #185740)
Victor Chernyakin via cfe-commits
cfe-commits at lists.llvm.org
Wed Mar 11 00:06:49 PDT 2026
================
@@ -111,7 +114,69 @@ unsigned invalid_bithacks(integer_like w, unsigned x, signed y, unsigned z) {
}
template <class T>
-T bithacks_generic(T x) {
- // substitution only valid for some instantiation of bithacks_generic
+T has_one_bit_bithack_generic(T x) {
+ // substitution only valid for some instantiation of has_one_bit_bithack_generic
return x && !(x & (x - 1));
}
+
+/*
+ * popcount pattern
+ */
+namespace std {
+using size_t = decltype(sizeof(0));
+template<size_t N> class bitset {
+ public:
+ bitset(unsigned long);
+ size_t count() const;
+};
+}
+
+unsigned popcount_bitset(unsigned x) {
+ // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: use 'std::popcount' instead [modernize-use-std-bit]
+ // CHECK-FIXES: return std::popcount(x);
+ return std::bitset<sizeof(x) * 8>(x).count();
+}
+
+unsigned popcount_bitset_short(unsigned short x) {
+ // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: use 'std::popcount' instead [modernize-use-std-bit]
+ // CHECK-FIXES: return std::popcount(x);
+ return std::bitset<sizeof(x) * 8>(x).count();
+}
+
+unsigned popcount_bitset_larger(unsigned x) {
+ // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: use 'std::popcount' instead [modernize-use-std-bit]
+ // CHECK-FIXES: return std::popcount(x);
+ return std::bitset<sizeof(x) * 16>(x).count();
+}
+
+unsigned popcount_bitset_uniform_init(unsigned x) {
+ // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: use 'std::popcount' instead [modernize-use-std-bit]
+ // CHECK-FIXES: return std::popcount(x);
+ return std::bitset<sizeof(x) * 16>{x}.count();
+}
+
+unsigned popcount_bitset_expr(unsigned x) {
+ // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: use 'std::popcount' instead [modernize-use-std-bit]
+ // CHECK-FIXES: return std::popcount(x + 1);
+ return std::bitset<sizeof(x) * 8>{x + 1}.count();
+}
+
+/*
+ * Invalid has_one_bit patterns
+ */
+template<std::size_t N> class bitset {
+ public:
+ bitset(unsigned long);
----------------
localspook wrote:
```suggestion
bitset(unsigned long long);
```
https://github.com/llvm/llvm-project/pull/185740
More information about the cfe-commits
mailing list