[Mlir-commits] [mlir] [mlir][scf] Interpret trip counts as unsigned integers (PR #178060)

Matthias Springer llvmlistbot at llvm.org
Wed Jan 28 00:09:54 PST 2026


================
@@ -336,7 +336,10 @@ std::optional<APInt> constantTripCount(
       // case applies, so the static trip count is unknown.
       return std::nullopt;
     }
-    if (stepCst.isNegative())
+    // For unsigned values, negative step is impossible; for signed, check the
+    // sign bit properly using APSInt.
+    APSInt stepSInt(stepCst, /*isUnsigned=*/!isSigned);
+    if (stepSInt.isNegative())
       return APInt(bitwidth, 0);
----------------
matthias-springer wrote:

Your conclusion is correct, but the implementation is not correct yet. This should be:
```
    // For signed loops, a negative step size could indicate an
    // infinite number of iterations.
    if (isSigned && stepCst.isSignBitSet())
      return std::nullopt;
```

For cases such as: `for (i = lb; i < ub; i += (-5))`

Also, let's move this check right after these lines:
```
  if (!maybeStepCst) {
    LDBG()
        << "constantTripCount can't be computed because step is not a constant";
    return std::nullopt;
  }
  auto &stepCst = maybeStepCst->first;
```

This is to ensure that we return "0" if LB > UB.


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


More information about the Mlir-commits mailing list