[llvm] [SelectionDAG] fold (not (sub Y, X)) -> (add X, ~Y) (PR #147825)

via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 9 13:49:29 PDT 2025


https://github.com/AZero13 created https://github.com/llvm/llvm-project/pull/147825

This replaces (not (neg x)) -> (add X, -1) because that is covered by this.

>From c9088c126abfcd8d066bb617281cd7f29acbada7 Mon Sep 17 00:00:00 2001
From: Rose <gfunni234 at gmail.com>
Date: Wed, 9 Jul 2025 16:48:35 -0400
Subject: [PATCH] [SelectionDAG] fold (not (sub Y, X)) -> (add X, ~Y)

This replaces (not (neg x)) -> (add X, -1) because that is covered by this.
---
 llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index 9ffdda28f7899..90c673dd7e83b 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -9979,13 +9979,13 @@ SDValue DAGCombiner::visitXOR(SDNode *N) {
     }
   }
 
-  // fold (not (neg x)) -> (add X, -1)
-  // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
-  // Y is a constant or the subtract has a single use.
-  if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB &&
-      isNullConstant(N0.getOperand(0))) {
-    return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
-                       DAG.getAllOnesConstant(DL, VT));
+  // fold (not (sub Y, X)) -> (add X, ~Y) is subtract is a single use
+  // or Y is a constant.
+  if (isAllOnesOrAllOnesSplat(N1) && N0.getOpcode() == ISD::SUB) {
+    ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N0.getOperand(0));
+    if (Const || N0.hasOneUse())
+      return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
+                         DAG.getNOT(DL, N0.getOperand(0), VT));
   }
 
   // fold (not (add X, -1)) -> (neg X)



More information about the llvm-commits mailing list