[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
Tue May 7 07:48:57 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:

The first link is the general proof with any values. noundef %CA/%CB/%CM are the constants. In general the flags from the add/mul need to be dropped.
The second link was a specific example where certain constant can keep nuw/nsw, but it is specific to those constants.

It does look like if all the input adds/mul are nsw/nuw then we might be able to keep some flags on the remaining instructions. I'm not sure if it's worth it considering all the other transforms in DAG, but I can try and add that to the patch.

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


More information about the llvm-commits mailing list