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

via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 9 18:15:12 PDT 2025


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

>From a972c3aeb94ac7aaa606d150046ca820eed42505 Mon Sep 17 00:00:00 2001
From: Rose <gfunni234 at gmail.com>
Date: Wed, 9 Jul 2025 21:04:24 -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 | 16 +++++++++-------
 llvm/test/CodeGen/X86/pr31045.ll              |  8 ++++----
 2 files changed, 13 insertions(+), 11 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index 9ffdda28f7899..b74903564f785 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -9979,13 +9979,15 @@ 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) if Y is a constant.
+  // FIXME: We can also do this with single-use sub, but this causes an infinite
+  // loop
+  if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB) {
+    SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
+    if (isa<ConstantSDNode>(N00)) {
+      SDValue NotY = DAG.getNOT(DL, N00, VT); // N00 = ~N00
+      return DAG.getNode(ISD::ADD, DL, VT, N01, NotY);
+    }
   }
 
   // fold (not (add X, -1)) -> (neg X)
diff --git a/llvm/test/CodeGen/X86/pr31045.ll b/llvm/test/CodeGen/X86/pr31045.ll
index 4aa73d79d8cfc..a873fc6fd4959 100644
--- a/llvm/test/CodeGen/X86/pr31045.ll
+++ b/llvm/test/CodeGen/X86/pr31045.ll
@@ -21,11 +21,11 @@ define void @_Z1av() local_unnamed_addr #0 {
 ; CHECK-NEXT:    movl struct_obj_3+8(%rip), %eax
 ; CHECK-NEXT:    movzbl var_46(%rip), %ecx
 ; CHECK-NEXT:    movzbl var_49(%rip), %edx
-; CHECK-NEXT:    andl $1, %eax
-; CHECK-NEXT:    addl %eax, %eax
-; CHECK-NEXT:    subl %ecx, %eax
-; CHECK-NEXT:    subl %edx, %eax
+; CHECK-NEXT:    addl %ecx, %edx
 ; CHECK-NEXT:    notl %eax
+; CHECK-NEXT:    addl %eax, %eax
+; CHECK-NEXT:    orl $253, %eax
+; CHECK-NEXT:    addl %edx, %eax
 ; CHECK-NEXT:    movzbl %al, %eax
 ; CHECK-NEXT:    movw %ax, struct_obj_12+5(%rip)
 ; CHECK-NEXT:    movb $0, var_163(%rip)



More information about the llvm-commits mailing list