[llvm] [DAG] Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB) (PR #90860)

David Green via llvm-commits llvm-commits at lists.llvm.org
Thu May 2 09:28:24 PDT 2024


================
@@ -2838,6 +2838,36 @@ SDValue DAGCombiner::visitADDLike(SDNode *N) {
     return DAG.getNode(ISD::ADD, DL, VT, Not, N0.getOperand(0));
   }
 
+  // Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB).
+  // This can help if the inner add has multiple uses.
+  APInt CM, CA;
+  if (ConstantSDNode *CB = dyn_cast<ConstantSDNode>(N1)) {
+    if (sd_match(N0, m_OneUse(m_Mul(m_Add(m_Value(A), m_ConstInt(CA)),
+                                    m_ConstInt(CM)))) &&
+        TLI.isLegalAddImmediate(
+            (CA * CM + CB->getAPIntValue()).getSExtValue())) {
+      SDValue Mul =
+          DAG.getNode(ISD::MUL, SDLoc(N1), VT, A, DAG.getConstant(CM, DL, VT));
+      return DAG.getNode(
+          ISD::ADD, DL, VT, Mul,
----------------
davemgreen wrote:

This is the generic combine: https://alive2.llvm.org/ce/z/k7Yvo3. In general the flags need removing.

In specific cases the flags might be retained, but it feels to me a bit niche and difficult to specify: https://alive2.llvm.org/ce/z/aK5Az3.

Let me know what you think.

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


More information about the llvm-commits mailing list