[llvm] [InstCombine] Fold (X + C) + (Y & ~C) to X + (Y | C) (PR #191334)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Sun Apr 12 09:59:36 PDT 2026
================
@@ -1523,6 +1523,47 @@ static Instruction *foldBoxMultiply(BinaryOperator &I) {
return nullptr;
}
+static Instruction *
+foldAddWithMaskedOverwrite(BinaryOperator &Add,
+ InstCombiner::BuilderTy &Builder) {
+ Value *LHS = Add.getOperand(0), *RHS = Add.getOperand(1);
+ Value *X, *Y;
+ const APInt *C;
+
+ auto Match = [&](Value *AddOp, Value *AndOp) -> Instruction * {
+ if (!match(AddOp, m_c_Add(m_Value(X), m_APInt(C))) ||
+ !match(AndOp, m_c_And(m_Value(Y), m_SpecificInt(~*C))))
+ return nullptr;
+
+ // Replacing one add with {or, add}. Avoid growth if both sides are shared.
+ if (!AddOp->hasOneUse() && !AndOp->hasOneUse())
+ return nullptr;
+
+ bool PreserveNSW = false;
+ bool PreserveNUW = false;
+ if (auto *InnerAdd = dyn_cast<OverflowingBinaryOperator>(AddOp)) {
+ PreserveNSW = Add.hasNoSignedWrap() && InnerAdd->hasNoSignedWrap();
+ PreserveNUW = Add.hasNoUnsignedWrap() && InnerAdd->hasNoUnsignedWrap();
+ }
+
+ Value *NewOr =
+ Builder.CreateOr(Y, Constant::getIntegerValue(Add.getType(), *C));
+ Value *NewAdd = Builder.CreateAdd(X, NewOr);
+ if (auto *NewAddInst = dyn_cast<Instruction>(NewAdd)) {
+ NewAddInst->setHasNoSignedWrap(PreserveNSW);
+ NewAddInst->setHasNoUnsignedWrap(PreserveNUW);
+
+ return NewAddInst;
+ }
+
+ return nullptr;
+ };
+
+ if (Instruction *I = Match(LHS, RHS))
----------------
dtcxzyw wrote:
Move this transformation into `foldAddLikeCommutative`.
https://github.com/llvm/llvm-project/pull/191334
More information about the llvm-commits
mailing list