[llvm] [KnownBits] FIX SDIV TO SET LOWEST UNKNOWN BIT TO GET MINIMUM NON ZERO VALUE FOR DENOMINATOR (PR #227224)

via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 29 02:15:34 PDT 2026


https://github.com/anandkvinu updated https://github.com/llvm/llvm-project/pull/227224

>From 6715cc27fe3716c2aab659a00abbe9a9238775af Mon Sep 17 00:00:00 2001
From: Anand K Vinu <20cs113anan at ug.cusat.ac.in>
Date: Tue, 29 Sep 2026 13:42:26 +0530
Subject: [PATCH] [KnownBits] Fix SDiv to set lowest unknown bit to get the
 minimum non-zero denominator

---
 llvm/lib/Support/KnownBits.cpp           |  6 +++++-
 llvm/unittests/Support/KnownBitsTest.cpp | 23 +++++++++++++++++++++++
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Support/KnownBits.cpp b/llvm/lib/Support/KnownBits.cpp
index 70f7a2f4fc887..81221081a4339 100644
--- a/llvm/lib/Support/KnownBits.cpp
+++ b/llvm/lib/Support/KnownBits.cpp
@@ -1255,7 +1255,11 @@ KnownBits KnownBits::sdiv(const KnownBits &LHS, const KnownBits &RHS,
     if (Exact || (-LHS.getSignedMaxValue()).uge(RHS.getSignedMaxValue())) {
       APInt Denom = RHS.getSignedMinValue();
       APInt Num = LHS.getSignedMinValue();
-      Res = Denom.isZero() ? Num : Num.sdiv(Denom);
+      // fix to set the lowest unknown bit to get the minimum non-zero
+      // denominator
+      if (Denom.isZero())
+        Denom.setBit(RHS.countMinTrailingZeros());
+      Res = Num.sdiv(Denom);
     }
   } else if (LHS.isStrictlyPositive() && RHS.isNegative()) {
     // Result is negative if Exact OR LHS u>= -RHS.
diff --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp
index d4b8dff54f3d6..5033fc415b520 100644
--- a/llvm/unittests/Support/KnownBitsTest.cpp
+++ b/llvm/unittests/Support/KnownBitsTest.cpp
@@ -693,6 +693,29 @@ TEST(KnownBitsTest, UnaryExhaustive) {
       },
       [](const APInt &N) { return N * N; }, /*CheckOptimality=*/false);
 }
+// implementing googletest for SDIV having unknown bit in denominator.
+// To set the lowest unknown bit to get the minimum non-zero denominator.
+
+TEST(KnownBitsTest, NonZeroDenomSDiv) {
+
+  KnownBits Num(4);
+  KnownBits Denom(4);
+  // setting the masks for Ones and Zeros Num = -8.
+  Num.One.setBit(3);
+  Num.Zero.setBit(2);
+  Num.Zero.setBit(1);
+  Num.Zero.setBit(0);
+  // comment to test each edge cases. Denom = 0b0?00.
+  Denom.Zero.setBit(3);
+  // Denom.Zero.setBit(2);
+  Denom.Zero.setBit(1);
+  Denom.Zero.setBit(0);
+  KnownBits Result = KnownBits::sdiv(Num, Denom);
+  KnownBits Answer(4);
+  Answer.One.setHighBits(3);
+
+  EXPECT_EQ(Result, Answer);
+}
 
 TEST(KnownBitsTest, FunnelShiftExhaustive) {
   unsigned Bits = 4;



More information about the llvm-commits mailing list