[llvm] [InstCombine] Add folds for (add/sub/disjoint_or/icmp C, (ctpop (not x))) (PR #77859)
Nikita Popov via llvm-commits
llvm-commits at lists.llvm.org
Mon Jan 15 02:19:16 PST 2024
================
@@ -740,6 +740,93 @@ static Value *tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ,
return RetVal;
}
+// If `I` has one Const operand and the other matches `(ctpop (not x))`,
+// replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.
+// This is only useful is the new subtract can fold so we only handle the
+// following cases:
+// 1) (add/sub/disjoint_or C, (ctpop (not x))
+// -> (add/sub/disjoint_or C', (ctpop x))
+// 1) (cmp pred C, (ctpop (not x))
+// -> (cmp pred C', (ctpop x))
+Instruction *InstCombinerImpl::tryFoldInstWithCtpopWithNot(Instruction *I) {
+ unsigned Opc = I->getOpcode();
+ unsigned ConstIdx = 1;
+ switch (Opc) {
+ default:
+ return nullptr;
+ // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))
+ // We can fold the BitWidth(x) with add/sub/icmp as long the other operand
+ // is constant.
+ case Instruction::Sub:
+ ConstIdx = 0;
+ break;
+ case Instruction::ICmp:
+ // Signed predicates aren't correct in some edge cases like for i2 types, as
+ // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed
+ // comparisons against it are simplfied to unsigned.
+ if (cast<ICmpInst>(I)->isSigned())
+ return nullptr;
+ break;
+ case Instruction::Or:
+ if (!match(I, m_DisjointOr(m_Value(), m_Value())))
+ return nullptr;
+ [[fallthrough]];
+ case Instruction::Add:
+ break;
+ }
+
+ Value *Op;
+ // Find ctpop.
+ if (!match(I->getOperand(1 - ConstIdx),
+ m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(Op)))))
+ return nullptr;
+
+ Constant *C;
+ // Check other operand is ImmConstant.
+ if (!match(I->getOperand(ConstIdx), m_ImmConstant(C)))
+ return nullptr;
+
+ Type *Ty = Op->getType();
+ Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());
+ // Need extra check for icmp. Note if this check is it generally means the
----------------
nikic wrote:
I think something is missing after "if this check is"?
https://github.com/llvm/llvm-project/pull/77859
More information about the llvm-commits
mailing list