[llvm] [SelectionDAG] Add more cases for UDIV and SDIV (PR #86452)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 15 14:34:46 PDT 2024


https://github.com/AtariDreams updated https://github.com/llvm/llvm-project/pull/86452

>From 9a6cc0ca78235e907864ed23131bb92d1214ac9a Mon Sep 17 00:00:00 2001
From: Rose <gfunni234 at gmail.com>
Date: Sun, 24 Mar 2024 14:09:28 -0400
Subject: [PATCH] [SelectionDAG] Add more cases for UDIV and SDIV

Ported from ValueTracking.
---
 .../lib/CodeGen/SelectionDAG/SelectionDAG.cpp | 23 +++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
index 897bdc71818f8..e302926b48234 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
@@ -5614,14 +5614,29 @@ bool SelectionDAG::isKnownNeverZero(SDValue Op, unsigned Depth) const {
       return true;
     break;
   }
-  case ISD::UDIV:
-  case ISD::SDIV:
+  case ISD::UDIV: {
     // div exact can only produce a zero if the dividend is zero.
-    // TODO: For udiv this is also true if Op1 u<= Op0
     if (Op->getFlags().hasExact())
       return isKnownNeverZero(Op.getOperand(0), Depth + 1);
-    break;
 
+    // If Op0 >= Op1, then the result is at least 1, and therefore not 0.
+    KnownBits Op0 = computeKnownBits(Op.getOperand(0), Depth + 1);
+    KnownBits Op1 = computeKnownBits(Op.getOperand(1), Depth + 1);
+    std::optional<bool> Uge = KnownBits::uge(Op0, Op1);
+    return Uge && *Uge;
+  }
+  case ISD::SDIV: {
+    // div exact can only produce a zero if the dividend is zero.
+    if (Op->getFlags().hasExact())
+      return isKnownNeverZero(Op.getOperand(0), Depth + 1);
+
+    KnownBits Op0 = computeKnownBits(Op.getOperand(0), Depth + 1);
+    KnownBits Op1 = computeKnownBits(Op.getOperand(1), Depth + 1);
+    Op0 = Op0.abs(/*IntMinIsPoison*/ false);
+    Op1 = Op1.abs(/*IntMinIsPoison*/ false);
+    std::optional<bool> Uge = KnownBits::uge(Op0, Op1);
+    return Uge && *Uge;
+  }
   case ISD::ADD:
     if (Op->getFlags().hasNoUnsignedWrap())
       if (isKnownNeverZero(Op.getOperand(1), Depth + 1) ||



More information about the llvm-commits mailing list