[clang] [analyzer] Fix truncation of ranges wider than 64 bits (PR #239147)

via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 5 00:50:54 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-static-analyzer-1

Author: Callan (relaxcn)

<details>
<summary>Changes</summary>

`RangeSet::Factory::truncateTo()` compared the source span and the target cardinality minus one through `getZExtValue()`.

Both can need more than 64 bits:

1. A 128-bit interval such as `[0, 2^64]` already has a 65-bit span.
2. A target wider than 64 bits has a threshold that does not fit in `uint64_t` at all.

With assertions enabled this aborts in `APInt::getZExtValue()`; without assertions the comparison silently uses the low 64 bits and can produce a range that is much smaller than the truncated source interval.

So this patch keeps both quantities as `APInt` at the source width. The threshold is `getLowBitsSet(W, N)`, i.e. `2^N - 1` in `W` bits, the span is the existing `W`-bit subtraction, and `uge()` makes the distance comparison unsigned. The endpoint conversion and the split after a wrap are unchanged.

FIXME: The only current caller of `castTo()`, `SymbolicRangeInferrer::VisitBinaryOperator<BO_NE>`, always casts to the wider of the two operand types and never truncates so this bug would never occur. We found this problem in our new feature implementing of downstream.

---
Full diff: https://github.com/llvm/llvm-project/pull/239147.diff


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (+22-12) 
- (modified) clang/unittests/StaticAnalyzer/RangeSetTest.cpp (+49) 


``````````diff
diff --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index 888f3ae9e159a6..c87e29af05476b 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -715,25 +715,35 @@ RangeSet::ContainerType RangeSet::Factory::truncateTo(RangeSet What,
   using llvm::APSInt;
   ContainerType Result;
   ContainerType Dummy;
-  // CastRangeSize is an amount of all possible values of cast type.
-  // Example: `char` has 256 values; `short` has 65536 values.
-  // But in fact we use `amount of values` - 1, because
-  // we can't keep `amount of values of UINT64` inside uint64_t.
-  // E.g. 256 is an amount of all possible values of `char` and we can't keep
-  // it inside `char`.
-  // And it's OK, it's enough to do correct calculations.
-  uint64_t CastRangeSize = APInt::getMaxValue(Ty.getBitWidth()).getZExtValue();
+  // Compare cardinalities minus one at source width to avoid overflow.
+  //
+  // Both comparison operands can need more than 64 bits:
+  // - A source span can be as large as `2^W - 1`.
+  // - A target wider than 64 bits has a threshold that does not fit in
+  // `uint64_t`.
+  //
+  // Keep them in `APInt` so the comparison below uses the same width on both
+  // sides.
+  const APInt CastRangeSize =
+      APInt::getLowBitsSet(What.getBitWidth(), Ty.getBitWidth());
   for (const Range &R : What) {
     // Get bounds of the given range.
     APSInt FromInt = R.From();
     APSInt ToInt = R.To();
-    // CurrentRangeSize is an amount of all possible values of the current
+    // `CurrentRangeSize` is an amount of all possible values of the current
     // range minus one.
-    uint64_t CurrentRangeSize = (ToInt - FromInt).getZExtValue();
-    // This is an optimization for a specific case when this Range covers
+    //
+    // This is a `W`-bit subtraction.
+    // For a valid range, the unsigned value of the result is the mathematical
+    // distance between the endpoints even when they are signed.
+    //
+    // Assigning to `APInt` drops the sign so that `uge()` below does not
+    // interpret an all-ones span as -1.
+    const APInt CurrentRangeSize = ToInt - FromInt;
+    // This is an optimization for a specific case when this `Range` covers
     // the whole range of the target type.
     Dummy.clear();
-    if (CurrentRangeSize >= CastRangeSize) {
+    if (CurrentRangeSize.uge(CastRangeSize)) {
       Dummy.emplace_back(ValueFactory.getMinValue(Ty),
                          ValueFactory.getMaxValue(Ty));
       Result = std::move(Dummy);
diff --git a/clang/unittests/StaticAnalyzer/RangeSetTest.cpp b/clang/unittests/StaticAnalyzer/RangeSetTest.cpp
index a8c7626dec6f29..59879202da9288 100644
--- a/clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ b/clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -281,6 +281,55 @@ using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
                                   uint32_t, int64_t, uint64_t>;
 TYPED_TEST_SUITE(RangeSetTest, IntTypes, );
 
+using RangeSetWideCastTest = RangeSetTest<uint64_t>;
+
+TEST_F(RangeSetWideCastTest, TruncateWideIntervals) {
+  using llvm::APInt;
+  using llvm::APSInt;
+  // Build endpoints explicitly: the fixture's `uint64_t` parameter must not
+  // limit the source width.
+  auto Interval = [&](APInt From, APInt To, bool Unsigned = true) {
+    return F.add(F.getEmptySet(), Range(BVF.getValue(APSInt(From, Unsigned)),
+                                        BVF.getValue(APSInt(To, Unsigned))));
+  };
+  const APSIntType U64(64, true), S64(64, false), U128(128, true);
+  const APInt Zero128(128, 0);
+  const APInt Two64 = APInt::getOneBitSet(128, 64);
+  const APInt Max64 = APInt::getMaxValue(64);
+  const RangeSet Full64 = Interval(APInt(64, 0), Max64);
+
+  // A span wider than 64 bits covers the entire target range.
+  checkCastToImpl(Interval(Zero128, Two64), U64, Full64);
+  checkCastToImpl(Interval(APInt::getSignedMinValue(128),
+                           APInt::getSignedMaxValue(128), false),
+                  U64, Full64);
+  checkCastToImpl(Interval(-APInt(128, 1), Two64 - 1, false), U64, Full64);
+
+  // Check the boundary at exactly 2^64 consecutive values.
+  checkCastToImpl(Interval(Zero128, Two64 - 1), U64, Full64);
+  checkCastToImpl(Interval(Zero128, Two64 - 2), U64,
+                  Interval(APInt(64, 0), Max64 - 1));
+
+  // Wide endpoints alone do not imply a full target range.
+  const APInt High = APInt::getOneBitSet(128, 96);
+  checkCastToImpl(Interval(High + 3, High + 5), U64,
+                  Interval(APInt(64, 3), APInt(64, 5)));
+  checkCastToImpl(Interval(Two64 - 2, Two64 + 1), U64,
+                  F.unite(Interval(APInt(64, 0), APInt(64, 1)),
+                          Interval(Max64 - 1, Max64)));
+
+  const APInt Two63 = APInt::getOneBitSet(128, 63);
+  const APInt MinSigned = APInt::getSignedMinValue(64);
+  const APInt MaxSigned = APInt::getSignedMaxValue(64);
+  checkCastToImpl(Interval(Two63 - 2, Two63 + 1), S64,
+                  F.unite(Interval(MinSigned, MinSigned + 1, false),
+                          Interval(MaxSigned - 1, MaxSigned, false)));
+
+  // The destination can also be wider than 64 bits.
+  checkCastToImpl(Interval(APInt(256, 0), APInt::getOneBitSet(256, 128)), U128,
+                  Interval(Zero128, APInt::getMaxValue(128)));
+}
+
 TYPED_TEST(RangeSetTest, RangeSetNegateTest) {
   using TV = TestValues<TypeParam>;
   constexpr auto MIN = TV::MIN;

``````````

</details>


https://github.com/llvm/llvm-project/pull/239147


More information about the cfe-commits mailing list