[libc-commits] [libc] [libc][stdfix] Fix lrdivi saturation for huge quotients (PR #241213)

Robin Bisht via libc-commits libc-commits at lists.llvm.org
Wed Nov 11 17:01:15 PST 2026


https://github.com/robinbishtt updated https://github.com/llvm/llvm-project/pull/241213

>From 861142383f3f1cb7e8a048e754158ff53629c00d Mon Sep 17 00:00:00 2001
From: robinbishtt <robinbisht49 at gmail.com>
Date: Thu, 12 Nov 2026 00:57:58 +0000
Subject: [PATCH] [libc][stdfix] Fix lrdivi saturation for huge quotients

Fixes #241209
---
 libc/src/__support/fixed_point/fx_bits.h | 11 ++++-------
 libc/test/src/stdfix/FxDiviTest.h        | 12 ++++++++++++
 2 files changed, 16 insertions(+), 7 deletions(-)

diff --git a/libc/src/__support/fixed_point/fx_bits.h b/libc/src/__support/fixed_point/fx_bits.h
index ac1bb3c9aa260..bce04d623d95f 100644
--- a/libc/src/__support/fixed_point/fx_bits.h
+++ b/libc/src/__support/fixed_point/fx_bits.h
@@ -273,14 +273,11 @@ fxdivi(IntType n, IntType d) {
     d_mag = d;
   }
 
-  if constexpr (OutRep::INTEGRAL_LEN > 0) {
-    constexpr UInt128 MAX_UNITS = static_cast<UInt128>(1)
-                                  << OutRep::INTEGRAL_LEN;
+  constexpr UInt128 MAX_UNITS = static_cast<UInt128>(1) << OutRep::INTEGRAL_LEN;
 
-    if (LIBC_UNLIKELY(static_cast<UInt128>(n_mag) >=
-                      MAX_UNITS * static_cast<UInt128>(d_mag)))
-      return result_is_negative ? OutRep::MIN() : OutRep::MAX();
-  }
+  if (LIBC_UNLIKELY(static_cast<UInt128>(n_mag) >=
+                    MAX_UNITS * static_cast<UInt128>(d_mag)))
+    return result_is_negative ? OutRep::MIN() : OutRep::MAX();
 
   WideFXType res;
 
diff --git a/libc/test/src/stdfix/FxDiviTest.h b/libc/test/src/stdfix/FxDiviTest.h
index b263b2e45173c..9fd919625614e 100644
--- a/libc/test/src/stdfix/FxDiviTest.h
+++ b/libc/test/src/stdfix/FxDiviTest.h
@@ -222,6 +222,18 @@ class FxDiviTest : public LIBC_NAMESPACE::testing::Test {
       constexpr IntType big_non_pow2 = big_pow2 + 7;
       EXPECT_TRUE(abs_diff(func(3, big_non_pow2), fx_zero) <= epsilon);
       EXPECT_EQ(func(big_non_pow2, big_non_pow2 << 1), one_half);
+
+      // Regression test for #241209: without an early saturation check,
+      // lrdivi(1L << 62, 3) truncates the 128-bit quotient to 64 bits before
+      // clamping, which flips the sign bit and saturates to MIN instead of MAX.
+      constexpr int digits = cpp::numeric_limits<IntType>::digits;
+      constexpr IntType huge = static_cast<IntType>(1) << (digits - 1);
+      EXPECT_EQ(func(huge, 3), fx_max);
+      if constexpr (is_signed) {
+        EXPECT_EQ(func(huge, -3), fx_min);
+        EXPECT_EQ(func(-huge, 3), fx_min);
+        EXPECT_EQ(func(-huge, -3), fx_max);
+      }
     }
   }
 



More information about the libc-commits mailing list