[Mlir-commits] [mlir] [mlir][Interfaces] Track and infer no-overflow flags in integer ranges (PR #191777)
Hocky Yudhiono
llvmlistbot at llvm.org
Mon Apr 13 20:07:02 PDT 2026
https://github.com/hockyy updated https://github.com/llvm/llvm-project/pull/191777
>From bc8d2d58e079aa9619bc51874f1c60498eca5cb6 Mon Sep 17 00:00:00 2001
From: Hocky Yudhiono <hocky.yudhiono at gmail.com>
Date: Mon, 13 Apr 2026 17:08:01 +0800
Subject: [PATCH 1/4] [mlir][Interfaces] Track and infer no-overflow flags in
integer ranges
---
.../mlir/Interfaces/InferIntRangeInterface.h | 25 +++-
.../Interfaces/Utils/InferIntRangeCommon.h | 8 +-
.../Arith/IR/InferIntRangeInterfaceImpls.cpp | 132 +++++++++++++++++-
.../lib/Interfaces/InferIntRangeInterface.cpp | 31 +++-
.../Interfaces/InferIntRangeInterfaceTest.cpp | 59 ++++++++
5 files changed, 236 insertions(+), 19 deletions(-)
diff --git a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
index a6de3d1885eec..9870cf1cbb6fa 100644
--- a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
+++ b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
@@ -15,9 +15,18 @@
#define MLIR_INTERFACES_INFERINTRANGEINTERFACE_H
#include "mlir/IR/OpDefinition.h"
+#include "llvm/ADT/BitmaskEnum.h"
#include <optional>
namespace mlir {
+enum class OverflowFlags : uint32_t {
+ None = 0,
+ Nsw = 1,
+ Nuw = 2,
+ LLVM_MARK_AS_BITMASK_ENUM(Nuw)
+};
+LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
+
/// A set of arbitrary-precision integers representing bounds on a given integer
/// value. These bounds are inclusive on both ends, so
/// bounds of [4, 5] mean 4 <= x <= 5. Separate bounds are tracked for
@@ -29,8 +38,10 @@ class ConstantIntRanges {
/// Bound umin <= (unsigned)x <= umax and smin <= signed(x) <= smax.
/// Non-integer values should be bounded by APInts of bitwidth 0.
ConstantIntRanges(const APInt &umin, const APInt &umax, const APInt &smin,
- const APInt &smax)
- : uminVal(umin), umaxVal(umax), sminVal(smin), smaxVal(smax) {
+ const APInt &smax,
+ OverflowFlags overflowFlags = OverflowFlags::None)
+ : uminVal(umin), umaxVal(umax), sminVal(smin), smaxVal(smax),
+ overflowFlags(overflowFlags) {
assert(uminVal.getBitWidth() == umaxVal.getBitWidth() &&
umaxVal.getBitWidth() == sminVal.getBitWidth() &&
sminVal.getBitWidth() == smaxVal.getBitWidth() &&
@@ -96,11 +107,21 @@ class ConstantIntRanges {
/// value.
std::optional<APInt> getConstantValue() const;
+ /// Return overflow properties proven for the operation computing the bounded
+ /// value.
+ OverflowFlags getOverflowFlags() const { return overflowFlags; }
+
+ /// Return this range with updated overflow properties.
+ ConstantIntRanges withOverflowFlags(OverflowFlags flags) const {
+ return {uminVal, umaxVal, sminVal, smaxVal, flags};
+ }
+
friend raw_ostream &operator<<(raw_ostream &os,
const ConstantIntRanges &range);
private:
APInt uminVal, umaxVal, sminVal, smaxVal;
+ OverflowFlags overflowFlags = OverflowFlags::None;
};
raw_ostream &operator<<(raw_ostream &, const ConstantIntRanges &);
diff --git a/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h b/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
index e369c80a26ea9..8c0784a4513bb 100644
--- a/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
+++ b/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
@@ -16,7 +16,6 @@
#include "mlir/Interfaces/InferIntRangeInterface.h"
#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/BitmaskEnum.h"
#include <optional>
namespace mlir {
@@ -39,12 +38,7 @@ static constexpr unsigned indexMaxWidth = 64;
enum class CmpMode : uint32_t { Both, Signed, Unsigned };
-enum class OverflowFlags : uint32_t {
- None = 0,
- Nsw = 1,
- Nuw = 2,
- LLVM_MARK_AS_BITMASK_ENUM(Nuw)
-};
+using OverflowFlags = mlir::OverflowFlags;
/// Function that performs inference on an array of `ConstantIntRanges` while
/// taking special overflow behavior into account.
diff --git a/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp b/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
index 49f89e1bd17f3..2624448b5f7b4 100644
--- a/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
+++ b/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
@@ -11,6 +11,7 @@
#include "mlir/Interfaces/Utils/InferIntRangeCommon.h"
#include <optional>
+#include <utility>
#define DEBUG_TYPE "int-range-analysis"
@@ -28,6 +29,116 @@ convertArithOverflowFlags(arith::IntegerOverflowFlags flags) {
return retFlags;
}
+template <typename Op>
+static bool proveNoOverflow(const APInt &lhs, const APInt &rhs, Op op) {
+ bool overflow = false;
+ (void)op(lhs, rhs, overflow);
+ return !overflow;
+}
+
+template <typename Op>
+static bool
+proveNoOverflowForPairs(ArrayRef<std::pair<const APInt *, const APInt *>> pairs,
+ Op op) {
+ for (const auto &[lhs, rhs] : pairs) {
+ if (!proveNoOverflow(*lhs, *rhs, op))
+ return false;
+ }
+ return true;
+}
+
+static OverflowFlags proveNoOverflowFlags(
+ ArrayRef<ConstantIntRanges> args,
+ function_ref<bool(ArrayRef<ConstantIntRanges>)> proveSigned,
+ function_ref<bool(ArrayRef<ConstantIntRanges>)> proveUnsigned) {
+ OverflowFlags flags = OverflowFlags::None;
+ if (proveSigned(args))
+ flags |= OverflowFlags::Nsw;
+ if (proveUnsigned(args))
+ flags |= OverflowFlags::Nuw;
+ return flags;
+}
+
+static bool proveNoSignedAddOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ const APInt &lhsMin = argRanges[0].smin();
+ const APInt &lhsMax = argRanges[0].smax();
+ const APInt &rhsMin = argRanges[1].smin();
+ const APInt &rhsMax = argRanges[1].smax();
+ // Signed add is monotone in both operands, so it is enough to check
+ // the interval endpoints to prove no signed wrap for the whole range.
+ return proveNoOverflowForPairs(
+ {{&lhsMin, &rhsMin}, {&lhsMax, &rhsMax}},
+ [](const APInt &lhs, const APInt &rhs, bool &overflow) {
+ return lhs.sadd_ov(rhs, overflow);
+ });
+}
+
+static bool proveNoUnsignedAddOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ return proveNoOverflow(
+ argRanges[0].umax(), argRanges[1].umax(),
+ [](const APInt &lhs, const APInt &rhs, bool &overflow) {
+ return lhs.uadd_ov(rhs, overflow);
+ });
+}
+
+static bool proveNoSignedSubOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ const APInt &lhsMin = argRanges[0].smin();
+ const APInt &lhsMax = argRanges[0].smax();
+ const APInt &rhsMin = argRanges[1].smin();
+ const APInt &rhsMax = argRanges[1].smax();
+ // For lhs - rhs, the extrema occur at (lhsMin - rhsMax) and
+ // (lhsMax - rhsMin). If both are no-wrap, the full interval is no-wrap.
+ return proveNoOverflowForPairs(
+ {{&lhsMin, &rhsMax}, {&lhsMax, &rhsMin}},
+ [](const APInt &lhs, const APInt &rhs, bool &overflow) {
+ return lhs.ssub_ov(rhs, overflow);
+ });
+}
+
+static bool proveNoUnsignedSubOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ return argRanges[0].umin().uge(argRanges[1].umax());
+}
+
+static bool proveNoSignedMulOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ const APInt &lhsMin = argRanges[0].smin();
+ const APInt &lhsMax = argRanges[0].smax();
+ const APInt &rhsMin = argRanges[1].smin();
+ const APInt &rhsMax = argRanges[1].smax();
+ // Signed multiply is not monotone across sign changes, so conservatively
+ // require all four corner products to be no-wrap.
+ return proveNoOverflowForPairs(
+ {{&lhsMin, &rhsMin},
+ {&lhsMin, &rhsMax},
+ {&lhsMax, &rhsMin},
+ {&lhsMax, &rhsMax}},
+ [](const APInt &lhs, const APInt &rhs, bool &overflow) {
+ return lhs.smul_ov(rhs, overflow);
+ });
+}
+
+static bool proveNoUnsignedMulOverflow(ArrayRef<ConstantIntRanges> argRanges) {
+ return proveNoOverflow(
+ argRanges[0].umax(), argRanges[1].umax(),
+ [](const APInt &lhs, const APInt &rhs, bool &overflow) {
+ return lhs.umul_ov(rhs, overflow);
+ });
+}
+
+static OverflowFlags proveNoOverflowForAdd(ArrayRef<ConstantIntRanges> args) {
+ return proveNoOverflowFlags(args, proveNoSignedAddOverflow,
+ proveNoUnsignedAddOverflow);
+}
+
+static OverflowFlags proveNoOverflowForSub(ArrayRef<ConstantIntRanges> args) {
+ return proveNoOverflowFlags(args, proveNoSignedSubOverflow,
+ proveNoUnsignedSubOverflow);
+}
+
+static OverflowFlags proveNoOverflowForMul(ArrayRef<ConstantIntRanges> args) {
+ return proveNoOverflowFlags(args, proveNoSignedMulOverflow,
+ proveNoUnsignedMulOverflow);
+}
+
//===----------------------------------------------------------------------===//
// ConstantOp
//===----------------------------------------------------------------------===//
@@ -65,8 +176,11 @@ void arith::ConstantOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
void arith::AddIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
SetIntRangeFn setResultRange) {
- setResultRange(getResult(), inferAdd(argRanges, convertArithOverflowFlags(
- getOverflowFlags())));
+ OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
+ ConstantIntRanges range = inferAdd(argRanges, declaredFlags);
+ OverflowFlags overflowFlags =
+ proveNoOverflowForAdd(argRanges) | declaredFlags;
+ setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
//===----------------------------------------------------------------------===//
@@ -75,8 +189,11 @@ void arith::AddIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
void arith::SubIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
SetIntRangeFn setResultRange) {
- setResultRange(getResult(), inferSub(argRanges, convertArithOverflowFlags(
- getOverflowFlags())));
+ OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
+ ConstantIntRanges range = inferSub(argRanges, declaredFlags);
+ OverflowFlags overflowFlags =
+ proveNoOverflowForSub(argRanges) | declaredFlags;
+ setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
//===----------------------------------------------------------------------===//
@@ -85,8 +202,11 @@ void arith::SubIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
void arith::MulIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
SetIntRangeFn setResultRange) {
- setResultRange(getResult(), inferMul(argRanges, convertArithOverflowFlags(
- getOverflowFlags())));
+ OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
+ ConstantIntRanges range = inferMul(argRanges, declaredFlags);
+ OverflowFlags overflowFlags =
+ proveNoOverflowForMul(argRanges) | declaredFlags;
+ setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
//===----------------------------------------------------------------------===//
diff --git a/mlir/lib/Interfaces/InferIntRangeInterface.cpp b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
index 9d8e5f50a725b..0d3e06dc4d995 100644
--- a/mlir/lib/Interfaces/InferIntRangeInterface.cpp
+++ b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
@@ -17,7 +17,8 @@ using namespace mlir;
bool ConstantIntRanges::operator==(const ConstantIntRanges &other) const {
return umin().getBitWidth() == other.umin().getBitWidth() &&
umin() == other.umin() && umax() == other.umax() &&
- smin() == other.smin() && smax() == other.smax();
+ smin() == other.smin() && smax() == other.smax() &&
+ getOverflowFlags() == other.getOverflowFlags();
}
const APInt &ConstantIntRanges::umin() const { return uminVal; }
@@ -94,8 +95,10 @@ ConstantIntRanges::rangeUnion(const ConstantIntRanges &other) const {
const APInt &umaxUnion = umax().ugt(other.umax()) ? umax() : other.umax();
const APInt &sminUnion = smin().slt(other.smin()) ? smin() : other.smin();
const APInt &smaxUnion = smax().sgt(other.smax()) ? smax() : other.smax();
+ // For a union, keep only guarantees proven on both inputs.
+ OverflowFlags overflowUnion = getOverflowFlags() & other.getOverflowFlags();
- return {uminUnion, umaxUnion, sminUnion, smaxUnion};
+ return {uminUnion, umaxUnion, sminUnion, smaxUnion, overflowUnion};
}
ConstantIntRanges
@@ -111,8 +114,12 @@ ConstantIntRanges::intersection(const ConstantIntRanges &other) const {
const APInt &umaxIntersect = umax().ult(other.umax()) ? umax() : other.umax();
const APInt &sminIntersect = smin().sgt(other.smin()) ? smin() : other.smin();
const APInt &smaxIntersect = smax().slt(other.smax()) ? smax() : other.smax();
+ // For an intersection, guarantees from either input remain valid.
+ OverflowFlags overflowIntersect =
+ getOverflowFlags() | other.getOverflowFlags();
- return {uminIntersect, umaxIntersect, sminIntersect, smaxIntersect};
+ return {uminIntersect, umaxIntersect, sminIntersect, smaxIntersect,
+ overflowIntersect};
}
std::optional<APInt> ConstantIntRanges::getConstantValue() const {
@@ -129,7 +136,23 @@ raw_ostream &mlir::operator<<(raw_ostream &os, const ConstantIntRanges &range) {
range.umin().print(os, /*isSigned*/ false);
os << ", ";
range.umax().print(os, /*isSigned*/ false);
- return os << "] signed : [" << range.smin() << ", " << range.smax() << "]";
+ os << "] signed : [" << range.smin() << ", " << range.smax() << "]";
+ OverflowFlags overflowFlags = range.getOverflowFlags();
+ if (overflowFlags == OverflowFlags::None)
+ return os;
+
+ os << " overflow<";
+ bool emitted = false;
+ if ((overflowFlags & OverflowFlags::Nsw) != OverflowFlags::None) {
+ os << "nsw";
+ emitted = true;
+ }
+ if ((overflowFlags & OverflowFlags::Nuw) != OverflowFlags::None) {
+ if (emitted)
+ os << ", ";
+ os << "nuw";
+ }
+ return os << ">";
}
IntegerValueRange IntegerValueRange::getMaxRange(Value value) {
diff --git a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
index 97c75b3680567..1b88a3f7a74aa 100644
--- a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
+++ b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
@@ -8,6 +8,7 @@
#include "mlir/Interfaces/InferIntRangeInterface.h"
#include "llvm/ADT/APInt.h"
+#include "llvm/Support/raw_ostream.h"
#include <limits>
#include <gtest/gtest.h>
@@ -97,3 +98,61 @@ TEST(IntRangeAttrs, Join) {
ConstantIntRanges zeroOneSignedOnly(zero, uintMax, zero, one);
EXPECT_EQ(zeroOneUnsignedOnly.rangeUnion(zeroOneSignedOnly), maximal);
}
+
+TEST(IntRangeAttrs, OverflowFlags) {
+ APInt zero = APInt::getZero(64);
+ APInt one = zero + 1;
+ APInt two = zero + 2;
+
+ ConstantIntRanges nswOnly(zero, one, zero, one, OverflowFlags::Nsw);
+ ConstantIntRanges nuwOnly(one, two, one, two, OverflowFlags::Nuw);
+
+ EXPECT_NE(nswOnly.getOverflowFlags() & OverflowFlags::Nsw,
+ OverflowFlags::None);
+ EXPECT_EQ(nswOnly.getOverflowFlags() & OverflowFlags::Nuw,
+ OverflowFlags::None);
+
+ ConstantIntRanges both =
+ nswOnly.withOverflowFlags(OverflowFlags::Nsw | OverflowFlags::Nuw);
+ EXPECT_NE(both.getOverflowFlags() & OverflowFlags::Nsw, OverflowFlags::None);
+ EXPECT_NE(both.getOverflowFlags() & OverflowFlags::Nuw, OverflowFlags::None);
+
+ // rangeUnion conservatively preserves only proofs present in both inputs.
+ EXPECT_EQ(nswOnly.rangeUnion(nuwOnly).getOverflowFlags(),
+ OverflowFlags::None);
+ EXPECT_EQ(both.rangeUnion(nswOnly).getOverflowFlags(), OverflowFlags::Nsw);
+
+ // intersection preserves proofs from either input.
+ EXPECT_EQ(nswOnly.intersection(nuwOnly).getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+ EXPECT_EQ(both.intersection(nswOnly).getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+ ConstantIntRanges none(zero, two, zero, two, OverflowFlags::None);
+ EXPECT_EQ(nswOnly.intersection(none).getOverflowFlags(), OverflowFlags::Nsw);
+}
+
+TEST(IntRangeAttrs, OverflowFlagsPrinting) {
+ APInt zero = APInt::getZero(64);
+ APInt one = zero + 1;
+
+ auto toString = [](const ConstantIntRanges &r) {
+ std::string buf;
+ llvm::raw_string_ostream os(buf);
+ os << r;
+ return buf;
+ };
+
+ ConstantIntRanges noFlags(zero, one, zero, one);
+ EXPECT_EQ(toString(noFlags), "unsigned : [0, 1] signed : [0, 1]");
+
+ ConstantIntRanges nsw(zero, one, zero, one, OverflowFlags::Nsw);
+ EXPECT_EQ(toString(nsw), "unsigned : [0, 1] signed : [0, 1] overflow<nsw>");
+
+ ConstantIntRanges nuw(zero, one, zero, one, OverflowFlags::Nuw);
+ EXPECT_EQ(toString(nuw), "unsigned : [0, 1] signed : [0, 1] overflow<nuw>");
+
+ ConstantIntRanges both(zero, one, zero, one,
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+ EXPECT_EQ(toString(both),
+ "unsigned : [0, 1] signed : [0, 1] overflow<nsw, nuw>");
+}
>From ec713c606a81132c1547c5153047c3fdc7804e79 Mon Sep 17 00:00:00 2001
From: Hocky Yudhiono <hocky.yudhiono at gmail.com>
Date: Mon, 13 Apr 2026 17:58:56 +0800
Subject: [PATCH 2/4] [mlir][interfaces] Add testcases
---
.../mlir/Interfaces/InferIntRangeInterface.h | 4 +
.../DataFlow/StridedMetadataRangeAnalysis.cpp | 8 +-
.../lib/Interfaces/InferIntRangeInterface.cpp | 7 +-
.../Interfaces/Utils/InferIntRangeCommon.cpp | 4 +-
.../Interfaces/InferIntRangeInterfaceTest.cpp | 181 ++++++++++++++++++
5 files changed, 197 insertions(+), 7 deletions(-)
diff --git a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
index 9870cf1cbb6fa..58682967df9b1 100644
--- a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
+++ b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
@@ -50,6 +50,10 @@ class ConstantIntRanges {
bool operator==(const ConstantIntRanges &other) const;
+ /// Returns true if all signed and unsigned bounds match, ignoring
+ /// overflow flags.
+ bool hasSameBounds(const ConstantIntRanges &other) const;
+
/// The minimum value of an integer when it is interpreted as unsigned.
const APInt &umin() const;
diff --git a/mlir/lib/Analysis/DataFlow/StridedMetadataRangeAnalysis.cpp b/mlir/lib/Analysis/DataFlow/StridedMetadataRangeAnalysis.cpp
index 01c9dafaddf10..cb7305195de7a 100644
--- a/mlir/lib/Analysis/DataFlow/StridedMetadataRangeAnalysis.cpp
+++ b/mlir/lib/Analysis/DataFlow/StridedMetadataRangeAnalysis.cpp
@@ -104,10 +104,10 @@ LogicalResult StridedMetadataRangeAnalysis::visitOperation(
};
// Convert the arguments lattices to a vector.
- SmallVector<StridedMetadataRange> argRanges = llvm::map_to_vector(
- operands, [](const StridedMetadataRangeLattice *lattice) {
- return lattice->getValue();
- });
+ SmallVector<StridedMetadataRange, 2> argRanges;
+ argRanges.reserve(operands.size());
+ for (const StridedMetadataRangeLattice *lattice : operands)
+ argRanges.push_back(lattice->getValue());
// Callback to set metadata on a result.
auto joinCallback = [&](Value v, const StridedMetadataRange &md) {
diff --git a/mlir/lib/Interfaces/InferIntRangeInterface.cpp b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
index 0d3e06dc4d995..090c13cea4599 100644
--- a/mlir/lib/Interfaces/InferIntRangeInterface.cpp
+++ b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
@@ -15,10 +15,13 @@
using namespace mlir;
bool ConstantIntRanges::operator==(const ConstantIntRanges &other) const {
+ return hasSameBounds(other) && getOverflowFlags() == other.getOverflowFlags();
+}
+
+bool ConstantIntRanges::hasSameBounds(const ConstantIntRanges &other) const {
return umin().getBitWidth() == other.umin().getBitWidth() &&
umin() == other.umin() && umax() == other.umax() &&
- smin() == other.smin() && smax() == other.smax() &&
- getOverflowFlags() == other.getOverflowFlags();
+ smin() == other.smin() && smax() == other.smax();
}
const APInt &ConstantIntRanges::umin() const { return uminVal; }
diff --git a/mlir/lib/Interfaces/Utils/InferIntRangeCommon.cpp b/mlir/lib/Interfaces/Utils/InferIntRangeCommon.cpp
index c9f49fda726e7..ffb407a650599 100644
--- a/mlir/lib/Interfaces/Utils/InferIntRangeCommon.cpp
+++ b/mlir/lib/Interfaces/Utils/InferIntRangeCommon.cpp
@@ -100,7 +100,9 @@ mlir::intrange::inferIndexOp(const InferRangeFn &inferFn,
bool truncEqual = false;
switch (mode) {
case intrange::CmpMode::Both:
- truncEqual = (thirtyTwo == sixtyFourAsThirtyTwo);
+ // Overflow flags are auxiliary guarantees and should not decide whether
+ // the 64-bit result is a truncation-compatible match.
+ truncEqual = thirtyTwo.hasSameBounds(sixtyFourAsThirtyTwo);
break;
case intrange::CmpMode::Signed:
truncEqual = (thirtyTwo.smin() == sixtyFourAsThirtyTwo.smin() &&
diff --git a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
index 1b88a3f7a74aa..9affdeac1fb6f 100644
--- a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
+++ b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
@@ -7,6 +7,9 @@
//===----------------------------------------------------------------------===//
#include "mlir/Interfaces/InferIntRangeInterface.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/Interfaces/Utils/InferIntRangeCommon.h"
#include "llvm/ADT/APInt.h"
#include "llvm/Support/raw_ostream.h"
#include <limits>
@@ -15,6 +18,22 @@
using namespace mlir;
+namespace {
+
+template <typename OpTy>
+ConstantIntRanges inferBinaryOpResult(OpTy op,
+ ArrayRef<ConstantIntRanges> argRanges) {
+ std::optional<ConstantIntRanges> inferred;
+ op.inferResultRanges(argRanges, [&](Value v, const ConstantIntRanges &range) {
+ if (v == op.getResult())
+ inferred = range;
+ });
+ assert(inferred.has_value() && "binary op did not produce a result range");
+ return *inferred;
+}
+
+} // namespace
+
TEST(IntRangeAttrs, BasicConstructors) {
APInt zero = APInt::getZero(64);
APInt two(64, 2);
@@ -129,6 +148,12 @@ TEST(IntRangeAttrs, OverflowFlags) {
OverflowFlags::Nsw | OverflowFlags::Nuw);
ConstantIntRanges none(zero, two, zero, two, OverflowFlags::None);
EXPECT_EQ(nswOnly.intersection(none).getOverflowFlags(), OverflowFlags::Nsw);
+
+ // Full equality tracks both bounds and overflow proofs.
+ EXPECT_FALSE(nswOnly == nswOnly.withOverflowFlags(OverflowFlags::None));
+ // Bounds-only equality intentionally ignores overflow proofs.
+ EXPECT_TRUE(nswOnly.hasSameBounds(
+ nswOnly.withOverflowFlags(OverflowFlags::Nsw | OverflowFlags::Nuw)));
}
TEST(IntRangeAttrs, OverflowFlagsPrinting) {
@@ -156,3 +181,159 @@ TEST(IntRangeAttrs, OverflowFlagsPrinting) {
EXPECT_EQ(toString(both),
"unsigned : [0, 1] signed : [0, 1] overflow<nsw, nuw>");
}
+
+TEST(IntRangeAttrs, InferIndexOpCmpBothIgnoresOverflowFlags) {
+ intrange::InferRangeFn inferFn = [](ArrayRef<ConstantIntRanges> args) {
+ unsigned width = args.front().umin().getBitWidth();
+ APInt zero = APInt::getZero(width);
+ APInt one(width, 1);
+ return ConstantIntRanges(zero, one, zero, one, OverflowFlags::Nsw);
+ };
+
+ APInt zero64 = APInt::getZero(64);
+ APInt one64(64, 1);
+ ConstantIntRanges arg(zero64, one64, zero64, one64);
+ ConstantIntRanges result =
+ intrange::inferIndexOp(inferFn, {arg}, intrange::CmpMode::Both);
+
+ EXPECT_EQ(result.umin(), zero64);
+ EXPECT_EQ(result.umax(), one64);
+ EXPECT_EQ(result.smin(), zero64);
+ EXPECT_EQ(result.smax(), one64);
+ EXPECT_EQ(result.getOverflowFlags(), OverflowFlags::Nsw);
+}
+
+TEST(IntRangeAttrs, ArithAddIOpInfersOverflowFlags) {
+ MLIRContext context;
+ context.loadDialect<arith::ArithDialect>();
+
+ OpBuilder builder(&context);
+ Location loc = builder.getUnknownLoc();
+ ModuleOp module = ModuleOp::create(loc);
+ builder.setInsertionPointToStart(module.getBody());
+
+ Value zero = arith::ConstantIntOp::create(builder, loc, 0, 8);
+ Value one = arith::ConstantIntOp::create(builder, loc, 1, 8);
+
+ arith::AddIOp add = arith::AddIOp::create(builder, loc, zero, one);
+ arith::AddIOp addWithDeclaredNsw = arith::AddIOp::create(
+ builder, loc, zero, one, arith::IntegerOverflowFlags::nsw);
+
+ APInt c0(8, 0), c1(8, 1), c2(8, 2), c10(8, 10), c20(8, 20), c120(8, 120),
+ c127(8, 127), c255(8, 255);
+
+ // Both signed and unsigned proofs succeed.
+ ConstantIntRanges addLhs(c0, c10, c0, c10);
+ ConstantIntRanges addRhs(c0, c20, c0, c20);
+ ConstantIntRanges addResult = inferBinaryOpResult(add, {addLhs, addRhs});
+ EXPECT_EQ(addResult.getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+
+ // Signed may overflow, but unsigned remains provably no-wrap.
+ ConstantIntRanges mayOverflowLhs(c120, c127, c120, c127);
+ ConstantIntRanges mayOverflowRhs(c1, c2, c1, c2);
+ ConstantIntRanges addMayOverflowResult =
+ inferBinaryOpResult(add, {mayOverflowLhs, mayOverflowRhs});
+ EXPECT_EQ(addMayOverflowResult.getOverflowFlags(), OverflowFlags::Nuw);
+
+ // Declared op flags are preserved and merged with inferred ones.
+ ConstantIntRanges addDeclaredNswResult =
+ inferBinaryOpResult(addWithDeclaredNsw, {mayOverflowLhs, mayOverflowRhs});
+ EXPECT_EQ(addDeclaredNswResult.getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+
+ // Both signed and unsigned proofs fail.
+ ConstantIntRanges fullUnsigned = ConstantIntRanges::fromUnsigned(c0, c255);
+ ConstantIntRanges addFullyOverflowingResult =
+ inferBinaryOpResult(add, {fullUnsigned, fullUnsigned});
+ EXPECT_EQ(addFullyOverflowingResult.getOverflowFlags(), OverflowFlags::None);
+}
+
+TEST(IntRangeAttrs, ArithSubIOpInfersOverflowFlags) {
+ MLIRContext context;
+ context.loadDialect<arith::ArithDialect>();
+
+ OpBuilder builder(&context);
+ Location loc = builder.getUnknownLoc();
+ ModuleOp module = ModuleOp::create(loc);
+ builder.setInsertionPointToStart(module.getBody());
+
+ Value zero = arith::ConstantIntOp::create(builder, loc, 0, 8);
+ Value one = arith::ConstantIntOp::create(builder, loc, 1, 8);
+
+ arith::SubIOp sub = arith::SubIOp::create(builder, loc, zero, one);
+ arith::SubIOp subWithDeclaredNuw = arith::SubIOp::create(
+ builder, loc, zero, one, arith::IntegerOverflowFlags::nuw);
+
+ APInt c0(8, 0), c5(8, 5), c10(8, 10), c20(8, 20);
+ APInt sMin = APInt::getSignedMinValue(8);
+ APInt sNeg120(8, -120, true);
+
+ // Both signed and unsigned proofs succeed.
+ ConstantIntRanges subLhs(c10, c20, c10, c20);
+ ConstantIntRanges subRhs(c0, c5, c0, c5);
+ ConstantIntRanges subResult = inferBinaryOpResult(sub, {subLhs, subRhs});
+ EXPECT_EQ(subResult.getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+
+ // Signed may overflow, but unsigned remains provably no-wrap.
+ ConstantIntRanges subMayOverflowLhs =
+ ConstantIntRanges::fromSigned(sMin, sNeg120);
+ ConstantIntRanges subMayOverflowRhs(c10, c20, c10, c20);
+ ConstantIntRanges subMayOverflowResult =
+ inferBinaryOpResult(sub, {subMayOverflowLhs, subMayOverflowRhs});
+ EXPECT_EQ(subMayOverflowResult.getOverflowFlags(), OverflowFlags::Nuw);
+
+ // Declared op flags are preserved.
+ ConstantIntRanges subDeclaredNuwResult = inferBinaryOpResult(
+ subWithDeclaredNuw, {subMayOverflowLhs, subMayOverflowRhs});
+ EXPECT_EQ(subDeclaredNuwResult.getOverflowFlags(), OverflowFlags::Nuw);
+}
+
+TEST(IntRangeAttrs, ArithMulIOpInfersOverflowFlags) {
+ MLIRContext context;
+ context.loadDialect<arith::ArithDialect>();
+
+ OpBuilder builder(&context);
+ Location loc = builder.getUnknownLoc();
+ ModuleOp module = ModuleOp::create(loc);
+ builder.setInsertionPointToStart(module.getBody());
+
+ Value zero = arith::ConstantIntOp::create(builder, loc, 0, 8);
+ Value one = arith::ConstantIntOp::create(builder, loc, 1, 8);
+
+ arith::MulIOp mul = arith::MulIOp::create(builder, loc, zero, one);
+ arith::MulIOp mulWithDeclaredFlags = arith::MulIOp::create(
+ builder, loc, zero, one,
+ arith::IntegerOverflowFlags::nsw | arith::IntegerOverflowFlags::nuw);
+
+ APInt c2(8, 2), c3(8, 3), c4(8, 4), c5(8, 5), c8(8, 8), c16(8, 16),
+ c20(8, 20);
+
+ // Both signed and unsigned proofs succeed.
+ ConstantIntRanges mulLhs(c2, c3, c2, c3);
+ ConstantIntRanges mulRhs(c4, c5, c4, c5);
+ ConstantIntRanges mulResult = inferBinaryOpResult(mul, {mulLhs, mulRhs});
+ EXPECT_EQ(mulResult.getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+
+ // Unsigned proof succeeds, but signed proof fails (16 * 8 = 128 in i8).
+ ConstantIntRanges mulNuwOnlyLhs(c16, c16, c16, c16);
+ ConstantIntRanges mulNuwOnlyRhs(c8, c8, c8, c8);
+ ConstantIntRanges mulNuwOnlyResult =
+ inferBinaryOpResult(mul, {mulNuwOnlyLhs, mulNuwOnlyRhs});
+ EXPECT_EQ(mulNuwOnlyResult.getOverflowFlags(), OverflowFlags::Nuw);
+
+ // Both signed and unsigned proofs fail.
+ ConstantIntRanges mulMayOverflowLhs(c16, c20, c16, c20);
+ ConstantIntRanges mulMayOverflowRhs(c16, c20, c16, c20);
+ ConstantIntRanges mulMayOverflowResult =
+ inferBinaryOpResult(mul, {mulMayOverflowLhs, mulMayOverflowRhs});
+ EXPECT_EQ(mulMayOverflowResult.getOverflowFlags(), OverflowFlags::None);
+
+ // Declared op flags are preserved.
+ ConstantIntRanges mulDeclaredResult = inferBinaryOpResult(
+ mulWithDeclaredFlags, {mulMayOverflowLhs, mulMayOverflowRhs});
+ EXPECT_EQ(mulDeclaredResult.getOverflowFlags(),
+ OverflowFlags::Nsw | OverflowFlags::Nuw);
+}
>From d77dd54c8c1da0ad2a27103d1d196175b88e6e4b Mon Sep 17 00:00:00 2001
From: Hocky Yudhiono <hocky.yudhiono at gmail.com>
Date: Tue, 14 Apr 2026 11:00:16 +0800
Subject: [PATCH 3/4] [mlir][interface] Refactor ConstantIntRanges
---
.../mlir/Interfaces/InferIntRangeInterface.h | 5 +++
.../Interfaces/Utils/InferIntRangeCommon.h | 2 -
.../Arith/IR/InferIntRangeInterfaceImpls.cpp | 37 ++++++++++---------
.../lib/Interfaces/InferIntRangeInterface.cpp | 6 +--
.../Interfaces/InferIntRangeInterfaceTest.cpp | 2 +
5 files changed, 30 insertions(+), 22 deletions(-)
diff --git a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
index 58682967df9b1..e2391e37ebaae 100644
--- a/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
+++ b/mlir/include/mlir/Interfaces/InferIntRangeInterface.h
@@ -19,6 +19,8 @@
#include <optional>
namespace mlir {
+
+namespace intrange {
enum class OverflowFlags : uint32_t {
None = 0,
Nsw = 1,
@@ -26,6 +28,7 @@ enum class OverflowFlags : uint32_t {
LLVM_MARK_AS_BITMASK_ENUM(Nuw)
};
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
+} // end namespace intrange
/// A set of arbitrary-precision integers representing bounds on a given integer
/// value. These bounds are inclusive on both ends, so
@@ -35,6 +38,8 @@ LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
/// unsigned semantics.
class ConstantIntRanges {
public:
+ using OverflowFlags = intrange::OverflowFlags;
+
/// Bound umin <= (unsigned)x <= umax and smin <= signed(x) <= smax.
/// Non-integer values should be bounded by APInts of bitwidth 0.
ConstantIntRanges(const APInt &umin, const APInt &umax, const APInt &smin,
diff --git a/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h b/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
index 8c0784a4513bb..393b058796b9a 100644
--- a/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
+++ b/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h
@@ -38,8 +38,6 @@ static constexpr unsigned indexMaxWidth = 64;
enum class CmpMode : uint32_t { Both, Signed, Unsigned };
-using OverflowFlags = mlir::OverflowFlags;
-
/// Function that performs inference on an array of `ConstantIntRanges` while
/// taking special overflow behavior into account.
using InferRangeWithOvfFlagsFn =
diff --git a/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp b/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
index 2624448b5f7b4..d8b78fde0c135 100644
--- a/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
+++ b/mlir/lib/Dialect/Arith/IR/InferIntRangeInterfaceImpls.cpp
@@ -47,14 +47,14 @@ proveNoOverflowForPairs(ArrayRef<std::pair<const APInt *, const APInt *>> pairs,
return true;
}
-static OverflowFlags proveNoOverflowFlags(
- ArrayRef<ConstantIntRanges> args,
+static OverflowFlags updateOverflowFlags(
+ ArrayRef<ConstantIntRanges> args, OverflowFlags declaredFlags,
function_ref<bool(ArrayRef<ConstantIntRanges>)> proveSigned,
function_ref<bool(ArrayRef<ConstantIntRanges>)> proveUnsigned) {
- OverflowFlags flags = OverflowFlags::None;
- if (proveSigned(args))
+ OverflowFlags flags = declaredFlags;
+ if (!any(flags & OverflowFlags::Nsw) && proveSigned(args))
flags |= OverflowFlags::Nsw;
- if (proveUnsigned(args))
+ if (!any(flags & OverflowFlags::Nuw) && proveUnsigned(args))
flags |= OverflowFlags::Nuw;
return flags;
}
@@ -124,19 +124,22 @@ static bool proveNoUnsignedMulOverflow(ArrayRef<ConstantIntRanges> argRanges) {
});
}
-static OverflowFlags proveNoOverflowForAdd(ArrayRef<ConstantIntRanges> args) {
- return proveNoOverflowFlags(args, proveNoSignedAddOverflow,
- proveNoUnsignedAddOverflow);
+static OverflowFlags updateOverflowFlagsForAdd(ArrayRef<ConstantIntRanges> args,
+ OverflowFlags declaredFlags) {
+ return updateOverflowFlags(args, declaredFlags, proveNoSignedAddOverflow,
+ proveNoUnsignedAddOverflow);
}
-static OverflowFlags proveNoOverflowForSub(ArrayRef<ConstantIntRanges> args) {
- return proveNoOverflowFlags(args, proveNoSignedSubOverflow,
- proveNoUnsignedSubOverflow);
+static OverflowFlags updateOverflowFlagsForSub(ArrayRef<ConstantIntRanges> args,
+ OverflowFlags declaredFlags) {
+ return updateOverflowFlags(args, declaredFlags, proveNoSignedSubOverflow,
+ proveNoUnsignedSubOverflow);
}
-static OverflowFlags proveNoOverflowForMul(ArrayRef<ConstantIntRanges> args) {
- return proveNoOverflowFlags(args, proveNoSignedMulOverflow,
- proveNoUnsignedMulOverflow);
+static OverflowFlags updateOverflowFlagsForMul(ArrayRef<ConstantIntRanges> args,
+ OverflowFlags declaredFlags) {
+ return updateOverflowFlags(args, declaredFlags, proveNoSignedMulOverflow,
+ proveNoUnsignedMulOverflow);
}
//===----------------------------------------------------------------------===//
@@ -179,7 +182,7 @@ void arith::AddIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
ConstantIntRanges range = inferAdd(argRanges, declaredFlags);
OverflowFlags overflowFlags =
- proveNoOverflowForAdd(argRanges) | declaredFlags;
+ updateOverflowFlagsForAdd(argRanges, declaredFlags);
setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
@@ -192,7 +195,7 @@ void arith::SubIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
ConstantIntRanges range = inferSub(argRanges, declaredFlags);
OverflowFlags overflowFlags =
- proveNoOverflowForSub(argRanges) | declaredFlags;
+ updateOverflowFlagsForSub(argRanges, declaredFlags);
setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
@@ -205,7 +208,7 @@ void arith::MulIOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
OverflowFlags declaredFlags = convertArithOverflowFlags(getOverflowFlags());
ConstantIntRanges range = inferMul(argRanges, declaredFlags);
OverflowFlags overflowFlags =
- proveNoOverflowForMul(argRanges) | declaredFlags;
+ updateOverflowFlagsForMul(argRanges, declaredFlags);
setResultRange(getResult(), range.withOverflowFlags(overflowFlags));
}
diff --git a/mlir/lib/Interfaces/InferIntRangeInterface.cpp b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
index 090c13cea4599..13edaeb91057d 100644
--- a/mlir/lib/Interfaces/InferIntRangeInterface.cpp
+++ b/mlir/lib/Interfaces/InferIntRangeInterface.cpp
@@ -13,6 +13,7 @@
#include <optional>
using namespace mlir;
+using mlir::intrange::OverflowFlags;
bool ConstantIntRanges::operator==(const ConstantIntRanges &other) const {
return hasSameBounds(other) && getOverflowFlags() == other.getOverflowFlags();
@@ -118,8 +119,7 @@ ConstantIntRanges::intersection(const ConstantIntRanges &other) const {
const APInt &sminIntersect = smin().sgt(other.smin()) ? smin() : other.smin();
const APInt &smaxIntersect = smax().slt(other.smax()) ? smax() : other.smax();
// For an intersection, guarantees from either input remain valid.
- OverflowFlags overflowIntersect =
- getOverflowFlags() | other.getOverflowFlags();
+ auto overflowIntersect = getOverflowFlags() | other.getOverflowFlags();
return {uminIntersect, umaxIntersect, sminIntersect, smaxIntersect,
overflowIntersect};
@@ -140,7 +140,7 @@ raw_ostream &mlir::operator<<(raw_ostream &os, const ConstantIntRanges &range) {
os << ", ";
range.umax().print(os, /*isSigned*/ false);
os << "] signed : [" << range.smin() << ", " << range.smax() << "]";
- OverflowFlags overflowFlags = range.getOverflowFlags();
+ auto overflowFlags = range.getOverflowFlags();
if (overflowFlags == OverflowFlags::None)
return os;
diff --git a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
index 9affdeac1fb6f..daff80ffa4f76 100644
--- a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
+++ b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
@@ -20,6 +20,8 @@ using namespace mlir;
namespace {
+using mlir::intrange::OverflowFlags;
+
template <typename OpTy>
ConstantIntRanges inferBinaryOpResult(OpTy op,
ArrayRef<ConstantIntRanges> argRanges) {
>From 87ff5d4cf2f2e9b1a2756429967a248283f453f7 Mon Sep 17 00:00:00 2001
From: Hocky Yudhiono <hocky.yudhiono at gmail.com>
Date: Tue, 14 Apr 2026 11:00:30 +0800
Subject: [PATCH 4/4] [mlir][interfaces] Add testcases
---
.../Dialect/Arith/int-range-interface.mlir | 66 ++++++++++++++++
.../Dialect/Index/int-range-inference.mlir | 49 ++++++++++++
.../Dialect/Tensor/int-range-inference.mlir | 77 +++++++++++++++++++
3 files changed, 192 insertions(+)
diff --git a/mlir/test/Dialect/Arith/int-range-interface.mlir b/mlir/test/Dialect/Arith/int-range-interface.mlir
index dd8240299ef7e..95232c80d3b53 100644
--- a/mlir/test/Dialect/Arith/int-range-interface.mlir
+++ b/mlir/test/Dialect/Arith/int-range-interface.mlir
@@ -885,6 +885,72 @@ func.func @test_add_1() -> i8 {
// Tests below check inference with overflow flags.
+// CHECK-LABEL: func @test_add_i8_inferred_nowrap
+// CHECK: test.reflect_bounds {smax = 127 : si8, smin = 1 : si8, umax = 127 : ui8, umin = 1 : ui8}
+func.func @test_add_i8_inferred_nowrap() -> i8 {
+ %cst1 = arith.constant 1 : i8
+ %0 = test.with_bounds { umin = 0 : i8, umax = 126 : i8, smin = 0 : i8, smax = 126 : i8 } : i8
+ // No declared flags; inference can prove both nsw and nuw.
+ %1 = arith.addi %0, %cst1 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
+// CHECK-LABEL: func @test_sub_i8_inferred_nowrap
+// CHECK: test.reflect_bounds {smax = 5 : si8, smin = 0 : si8, umax = 5 : ui8, umin = 0 : ui8}
+func.func @test_sub_i8_inferred_nowrap() -> i8 {
+ %cst10 = arith.constant 10 : i8
+ %0 = test.with_bounds { umin = 10 : i8, umax = 15 : i8, smin = 10 : i8, smax = 15 : i8 } : i8
+ // No declared flags; inference can prove both nsw and nuw.
+ %1 = arith.subi %0, %cst10 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
+// CHECK-LABEL: func @test_mul_i8_inferred_nowrap
+// CHECK: test.reflect_bounds {smax = 120 : si8, smin = 100 : si8, umax = 120 : ui8, umin = 100 : ui8}
+func.func @test_mul_i8_inferred_nowrap() -> i8 {
+ %cst10 = arith.constant 10 : i8
+ %0 = test.with_bounds { umin = 10 : i8, umax = 12 : i8, smin = 10 : i8, smax = 12 : i8 } : i8
+ // No declared flags; inference can prove both nsw and nuw.
+ %1 = arith.muli %0, %cst10 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
+// CHECK-LABEL: func @test_add_i8_inferred_nuw_only
+// CHECK: test.reflect_bounds {smax = 127 : si8, smin = -128 : si8, umax = 128 : ui8, umin = 121 : ui8}
+func.func @test_add_i8_inferred_nuw_only() -> i8 {
+ %cst1 = arith.constant 1 : i8
+ %0 = test.with_bounds { umin = 120 : i8, umax = 127 : i8, smin = 120 : i8, smax = 127 : i8 } : i8
+ // No declared flags; signed overflow is possible, unsigned overflow is not.
+ %1 = arith.addi %0, %cst1 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
+// CHECK-LABEL: func @test_sub_i8_inferred_nsw_only
+// CHECK: test.reflect_bounds {smax = 2 : si8, smin = -5 : si8, umax = 255 : ui8, umin = 0 : ui8}
+func.func @test_sub_i8_inferred_nsw_only() -> i8 {
+ %cst5 = arith.constant 5 : i8
+ %0 = test.with_bounds { umin = 0 : i8, umax = 7 : i8, smin = 0 : i8, smax = 7 : i8 } : i8
+ // No declared flags; unsigned underflow is possible, signed overflow is not.
+ %1 = arith.subi %0, %cst5 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
+// CHECK-LABEL: func @test_mul_i8_inferred_none
+// CHECK: test.reflect_bounds {smax = 127 : si8, smin = -128 : si8, umax = 255 : ui8, umin = 0 : ui8}
+func.func @test_mul_i8_inferred_none() -> i8 {
+ %cst20 = arith.constant 20 : i8
+ %0 = test.with_bounds { umin = 16 : i8, umax = 20 : i8, smin = 16 : i8, smax = 20 : i8 } : i8
+ // No declared flags; both signed and unsigned overflow are possible.
+ %1 = arith.muli %0, %cst20 : i8
+ %2 = test.reflect_bounds %1 : i8
+ return %2 : i8
+}
+
// CHECK-LABEL: func @test_add_i8_wrap1
// CHECK: test.reflect_bounds {smax = 127 : si8, smin = -128 : si8, umax = 128 : ui8, umin = 1 : ui8}
func.func @test_add_i8_wrap1() -> i8 {
diff --git a/mlir/test/Dialect/Index/int-range-inference.mlir b/mlir/test/Dialect/Index/int-range-inference.mlir
index 951624d573a64..5c671c057cac4 100644
--- a/mlir/test/Dialect/Index/int-range-inference.mlir
+++ b/mlir/test/Dialect/Index/int-range-inference.mlir
@@ -64,3 +64,52 @@ func.func @add_big(%arg0 : index) -> i1 {
%3 = index.cmp uge(%1, %cmin)
func.return %3 : i1
}
+
+// CHECK-LABEL: func @sub_same_for_both
+// CHECK: test.reflect_bounds {smax = 4294967293 : index, smin = -2147483649 : index, umax = -1 : index, umin = 0 : index}
+func.func @sub_same_for_both(%arg0 : index) -> index {
+ %c1 = index.constant 1
+ %calmostBig = index.constant 0xfffffffe
+ %0 = index.maxu %arg0, %c1
+ %1 = index.minu %0, %calmostBig
+ %2 = index.sub %1, %c1
+ %3 = test.reflect_bounds %2 : index
+ func.return %3 : index
+}
+
+// CHECK-LABEL: func @mul_same_for_both
+// CHECK: test.reflect_bounds {smax = 6 : index, smin = 0 : index, umax = 6 : index, umin = 0 : index}
+func.func @mul_same_for_both(%arg0 : index) -> index {
+ %c2 = index.constant 2
+ %c3 = index.constant 3
+ %0 = index.maxu %arg0, %c2
+ %1 = index.minu %0, %c3
+ %2 = index.mul %1, %c2
+ %3 = test.reflect_bounds %2 : index
+ func.return %3 : index
+}
+
+// CHECK-LABEL: func @sub_tight_no_wrap
+// CHECK: test.reflect_bounds {smax = 5 : index, smin = -4 : index, umax = -1 : index, umin = 0 : index}
+func.func @sub_tight_no_wrap(%arg0 : index) -> index {
+ %c4 = index.constant 4
+ %c9 = index.constant 9
+ %0 = index.maxu %arg0, %c4
+ %1 = index.minu %0, %c9
+ %2 = index.sub %1, %c4
+ %3 = test.reflect_bounds %2 : index
+ func.return %3 : index
+}
+
+// CHECK-LABEL: func @mul_tight_no_wrap
+// CHECK: test.reflect_bounds {smax = 12 : index, smin = 0 : index, umax = 12 : index, umin = 0 : index}
+func.func @mul_tight_no_wrap(%arg0 : index) -> index {
+ %c2 = index.constant 2
+ %c3 = index.constant 3
+ %c4 = index.constant 4
+ %0 = index.maxu %arg0, %c2
+ %1 = index.minu %0, %c4
+ %2 = index.mul %1, %c3
+ %3 = test.reflect_bounds %2 : index
+ func.return %3 : index
+}
diff --git a/mlir/test/Dialect/Tensor/int-range-inference.mlir b/mlir/test/Dialect/Tensor/int-range-inference.mlir
index e90ebf5fccb8e..4ca5b3a29d1ee 100644
--- a/mlir/test/Dialect/Tensor/int-range-inference.mlir
+++ b/mlir/test/Dialect/Tensor/int-range-inference.mlir
@@ -72,3 +72,80 @@ func.func @dim_unranked(%t: tensor<*xi32>) -> index {
%1 = test.reflect_bounds %0 : index
return %1 : index
}
+
+// -----
+
+// CHECK-LABEL: @dim_single_static_from_range
+// CHECK: test.reflect_bounds {smax = 11 : index, smin = 11 : index, umax = 11 : index, umin = 11 : index}
+// CHECK: return
+func.func @dim_single_static_from_range(%t: tensor<7x11x13xi32>, %x: index) -> index {
+ %c1 = arith.constant 1 : index
+ %0 = arith.maxsi %x, %c1 : index
+ %1 = arith.minsi %0, %c1 : index
+ %2 = tensor.dim %t, %1 : tensor<7x11x13xi32>
+ %3 = test.reflect_bounds %2 : index
+ return %3 : index
+}
+
+// -----
+
+// CHECK-LABEL: @dim_static_subset
+// CHECK: %[[op:.+]] = tensor.dim
+// CHECK: %[[ret:.+]] = test.reflect_bounds {smax = 11 : index, smin = 7 : index, umax = 11 : index, umin = 7 : index} %[[op]]
+// CHECK: return %[[ret]]
+func.func @dim_static_subset(%t: tensor<3x7x11x13xi32>, %x: index) -> index {
+ %c1 = arith.constant 1 : index
+ %c2 = arith.constant 2 : index
+ %0 = arith.maxsi %x, %c1 : index
+ %1 = arith.minsi %0, %c2 : index
+ %2 = tensor.dim %t, %1 : tensor<3x7x11x13xi32>
+ %3 = test.reflect_bounds %2 : index
+ return %3 : index
+}
+
+// -----
+
+// CHECK-LABEL: @dim_mixed_subset_includes_dynamic
+// CHECK: %[[op:.+]] = tensor.dim
+// CHECK: %[[ret:.+]] = test.reflect_bounds {smax = 9223372036854775807 : index, smin = 0 : index, umax = 9223372036854775807 : index, umin = 0 : index} %[[op]]
+// CHECK: return %[[ret]]
+func.func @dim_mixed_subset_includes_dynamic(%t: tensor<3x?x11xi32>, %x: index) -> index {
+ %c1 = arith.constant 1 : index
+ %c2 = arith.constant 2 : index
+ %0 = arith.maxsi %x, %c1 : index
+ %1 = arith.minsi %0, %c2 : index
+ %2 = tensor.dim %t, %1 : tensor<3x?x11xi32>
+ %3 = test.reflect_bounds %2 : index
+ return %3 : index
+}
+
+// -----
+
+// CHECK-LABEL: @dim_negative_index_range_clamped
+// CHECK: test.reflect_bounds {smax = 3 : index, smin = 3 : index, umax = 3 : index, umin = 3 : index}
+// CHECK: return
+func.func @dim_negative_index_range_clamped(%t: tensor<3x5xi32>, %x: index) -> index {
+ %cneg7 = arith.constant -7 : index
+ %c0 = arith.constant 0 : index
+ %0 = arith.maxsi %x, %cneg7 : index
+ %1 = arith.minsi %0, %c0 : index
+ %2 = tensor.dim %t, %1 : tensor<3x5xi32>
+ %3 = test.reflect_bounds %2 : index
+ return %3 : index
+}
+
+// -----
+
+// CHECK-LABEL: @dim_out_of_bounds_only
+// CHECK: %[[op:.+]] = tensor.dim
+// CHECK: %[[ret:.+]] = test.reflect_bounds {smax = 9223372036854775807 : index, smin = 0 : index, umax = 9223372036854775807 : index, umin = 0 : index} %[[op]]
+// CHECK: return %[[ret]]
+func.func @dim_out_of_bounds_only(%t: tensor<3x5xi32>, %x: index) -> index {
+ %c2 = arith.constant 2 : index
+ %c4 = arith.constant 4 : index
+ %0 = arith.maxsi %x, %c2 : index
+ %1 = arith.minsi %0, %c4 : index
+ %2 = tensor.dim %t, %1 : tensor<3x5xi32>
+ %3 = test.reflect_bounds %2 : index
+ return %3 : index
+}
More information about the Mlir-commits
mailing list