[PATCH] D156026: [InstCombine] Contracting x^2 + 2*x*y + y^2 to (x + y)^2

Christoph Stiller via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Jul 22 07:47:44 PDT 2023


rainerzufalldererste created this revision.
rainerzufalldererste added a reviewer: majnemer.
rainerzufalldererste added a project: LLVM.
Herald added a subscriber: hiraditya.
Herald added a project: All.
rainerzufalldererste requested review of this revision.
Herald added a subscriber: llvm-commits.

There's a good chance the floating point version needs some restrictions (like non-NaN etc.)
Also, I'm not familiar with how the tests work yet, so please let me know how to add and run them.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D156026

Files:
  llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp


Index: llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
===================================================================
--- llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -1615,6 +1615,20 @@
         I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
                                    {Builder.CreateOr(A, B)}));
 
+  // (x * x) + ((x << 1) + y) * y -> (x * y)^2
+  // which is:
+  // (x * x) + (2 * x * y) + (y * y) -> (x * y)^2
+  if (match(RHS, m_Mul(m_Value(A), m_Value(B))) && A == B) {
+    Value *C;
+    if (match(LHS, m_Mul(m_Add(m_Shl(m_Specific(A), m_SpecificInt(1)),
+                                 m_Value(C)),
+                          m_Value(B))) &&
+        B == C) {
+      Value *AB = Builder.CreateAdd(A, B);
+      return BinaryOperator::CreateMul(AB, AB, I.getName());
+    }
+  }
+
   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
     return Res;
 
@@ -1846,6 +1860,18 @@
     return Result;
   }
 
+  // (x * x) + ((2 * x) + y) * y -> (x * y)^2
+  // which is:
+  // (x * x) + (2 * x * y) + (y * y) -> (x * y)^2
+  if (match(RHS, m_FMul(m_Value(X), m_Value(Y))) && X == Y) {
+    Value *Z;
+    if (match(LHS, m_FMul(m_FAdd(m_FMul(m_Specific(X), m_SpecificFP(2.0)),
+                                 m_Value(Z)), m_Value(Y))) && Z == Y) {
+      Value *XY = Builder.CreateFAdd(X, Y);
+      return BinaryOperator::CreateFMulFMF(XY, XY, &I);
+    }
+  }
+
   return nullptr;
 }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D156026.543188.patch
Type: text/x-patch
Size: 1503 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20230722/750f49d1/attachment.bin>


More information about the llvm-commits mailing list