[llvm] [SCEV] Avoid overflow in howManyGreaterThans. (PR #217744)

Florian Hahn via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 20 11:43:06 PDT 2026


================
@@ -13860,12 +13863,21 @@ ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
       return End;
   }
 
-  // Compute ((Start - End) + (Stride - 1)) / Stride.
-  // FIXME: This can overflow. Holding off on fixing this for now;
-  // howManyGreaterThans will hopefully be gone soon.
-  const SCEV *One = getOne(Stride->getType());
-  const SCEV *BECount = getUDivExpr(
-      getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
+  const SCEV *Delta = getMinusSCEV(Start, End);
+  const SCEV *BECount;
+  if (MayAddOverflow) {
+    // The ceiling division instead needs Start >= End, so that (Start - End) is
+    // the exact unsigned distance between them.
+    if (!isLoopEntryGuardedByCond(
+            L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
+      return getCouldNotCompute();
----------------
fhahn wrote:

I put up https://github.com/llvm/llvm-project/pull/224952. We already do this kind of clamping earlier, extended the code path there

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


More information about the llvm-commits mailing list