[llvm] [InstCombine] optimize powi(X,Y) * X with Ofast (PR #69998)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 4 00:47:35 PST 2024


================
@@ -571,6 +571,55 @@ Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
   return nullptr;
 }
 
+Instruction *InstCombinerImpl::foldPowiReassoc(BinaryOperator &I) {
+  Value *X, *Y, *Z;
+
+  // Make sure all operands have reassoc flag if they are powi.
+  if (!all_of(I.operands(), [](Value *V) {
+        if (match(V, m_Intrinsic<Intrinsic::powi>(m_Value(), m_Value()))) {
+          Instruction *Powi = cast<Instruction>(V);
+          return Powi->hasAllowReassoc();
+        }
+        return true;
+      }))
+    return nullptr;
+
+  auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
+                           Value *Y, Value *Z) {
+    Value *YZ;
+    InstCombiner::BuilderTy &Builder = IC.Builder;
+
+    if (auto *C = dyn_cast<ConstantInt>(Z)) {
+      if (C->isOne())
+        YZ = Builder.CreateAdd(Y, ConstantInt::get(Y->getType(), 1));
+    } else
+      YZ = Builder.CreateAdd(Y, Z);
+
+    auto *NewPow = Builder.CreateIntrinsic(
+        Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
+    return IC.replaceInstUsesWith(I, NewPow);
+  };
+
+  // powi(X, Y) * X --> powi(X, Y+1)
+  // X * powi(X, Y) --> powi(X, Y+1)
+  if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::powi>(m_Value(X),
+                                                               m_Value(Y))),
+                         m_Deferred(X))) &&
+      willNotOverflowSignedAdd(Y, ConstantInt::get(Y->getType(), 1), I))
+    return createPowiExpr(I, *this, X, Y, ConstantInt::get(Y->getType(), 1));
----------------
arsenm wrote:

Repeated ConstantInt::get 

https://github.com/llvm/llvm-project/pull/69998


More information about the llvm-commits mailing list