[llvm] [InstCombine] Factorise add/sub and max/min using distributivity (PR #101507)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Thu Aug 1 23:05:46 PDT 2024
================
@@ -1505,6 +1505,78 @@ foldMinimumOverTrailingOrLeadingZeroCount(Value *I0, Value *I1,
ConstantInt::getTrue(ZeroUndef->getType()));
}
+/// Return whether "X LOp (Y ROp Z)" is always equal to
+/// "(X LOp Y) ROp (X LOp Z)".
+static bool leftDistributesOverRightIntrinsic(Intrinsic::ID LOp,
+ Intrinsic::ID ROp) {
+ switch (LOp) {
+ case Intrinsic::umax:
+ return ROp == Intrinsic::umin;
+ case Intrinsic::smax:
+ return ROp == Intrinsic::smin;
+ case Intrinsic::umin:
+ return ROp == Intrinsic::umax;
+ case Intrinsic::smin:
+ return ROp == Intrinsic::smax;
+ case Intrinsic::uadd_sat:
+ return ROp == Intrinsic::umax || ROp == Intrinsic::umin;
+ case Intrinsic::sadd_sat:
+ return ROp == Intrinsic::smax || ROp == Intrinsic::smin;
+ default:
+ return false;
+ }
+}
+
+// Attempts to factorise a common term
+// in an instruction that has the form "(A op' B) op (C op' D)
+static Value *
+foldIntrinsicUsingDistributiveLaws(IntrinsicInst *II,
+ InstCombiner::BuilderTy &Builder) {
+ Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
+ Intrinsic::ID TopLevelOpcode = II->getIntrinsicID();
+
+ if (LHS && RHS) {
+ IntrinsicInst *Op0 = dyn_cast<IntrinsicInst>(LHS);
+ IntrinsicInst *Op1 = dyn_cast<IntrinsicInst>(RHS);
+
+ if (!Op0 || !Op1)
+ return nullptr;
+
+ if (Op0->getIntrinsicID() != Op1->getIntrinsicID())
----------------
dtcxzyw wrote:
```suggestion
if (!Op0->hasOneUse() || !Op1->hasOneUse())
return nullptr;
if (Op0->getIntrinsicID() != Op1->getIntrinsicID())
```
We need one-use check here to avoid creating more instructions than before :)
See also https://llvm.org/docs/InstCombineContributorGuide.html#multi-use-handling.
https://github.com/llvm/llvm-project/pull/101507
More information about the llvm-commits
mailing list