[llvm] [APInt] Add `bitwiseParity`, `compressBits`, and `expandBits` operations (PR #200114)
Max Graey via llvm-commits
llvm-commits at lists.llvm.org
Thu May 28 04:01:07 PDT 2026
================
@@ -3259,3 +3259,61 @@ APInt llvm::APIntOps::clmulh(const APInt &LHS, const APInt &RHS) {
assert(LHS.getBitWidth() == RHS.getBitWidth());
return clmulr(LHS, RHS).lshr(1);
}
+
+APInt llvm::APIntOps::bitwiseParity(const APInt &V) {
+ // This computes `clmul(V, ~0)`,
+ // but we don't use `clmul` because this special case has lower complexity
+ // (logarithmic amount of loop iterations instead of linear in BW).
+ unsigned BW = V.getBitWidth();
+ APInt Result = V;
+ for (unsigned I = 1; I < BW; I <<= 1)
+ Result ^= Result.shl(I);
+ return Result;
----------------
MaxGraey wrote:
What about adding a fast-path via Hillis-Steele scan for single words and reusing it for multi-word as well? It should be a more canonical approach for APint ops
```cpp
// Use Hillis-Steele prefix-xor scan
static inline uint64_t prefixXorScan(uint64_t x) {
x ^= x << 1;
x ^= x << 2;
x ^= x << 4;
x ^= x << 8;
x ^= x << 16;
x ^= x << 32;
return x;
}
APInt APIntOps::bitwiseParity(const APInt &V) {
APInt Result(V.getBitWidth(), 0);
if (V.isSingleWord()) {
Result.U.VAL = prefixXorScan(V.U.VAL);
} else {
unsigned N = V.getNumWords();
uint64_t carry = 0;
for (unsigned i = 0; i < N; ++i) {
uint64_t x = prefixXorScan(V.U.pVal[i]);
Result.U.pVal[i] = x ^ carry;
carry ^= -(x >> 63);
}
}
Result.clearUnusedBits();
return Result;
}
```
https://github.com/llvm/llvm-project/pull/200114
More information about the llvm-commits
mailing list