16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/TypeSwitch.h"
29 if (
auto boolValue = dyn_cast<BoolAttr>(value)) {
32 return BoolConstantOp::create(
b, loc, type, boolValue);
36 if (
auto indexValue = dyn_cast<IntegerAttr>(value)) {
37 if (!llvm::isa<IndexType>(indexValue.getType()) ||
38 !llvm::isa<IndexType>(type))
40 assert(indexValue.getValue().getBitWidth() ==
41 IndexType::kInternalStorageBitWidth);
42 return ConstantOp::create(
b, loc, indexValue);
63 function_ref<std::optional<APInt>(
const APInt &,
const APInt &)>
65 assert(operands.size() == 2 &&
"binary operation expected 2 operands");
66 auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
67 auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
71 std::optional<APInt>
result = calculate(lhs.getValue(), rhs.getValue());
74 assert(
result->trunc(32) ==
75 calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32)));
76 return IntegerAttr::get(IndexType::get(lhs.getContext()), *
result);
89 function_ref<std::optional<APInt>(
const APInt &,
const APInt &lhs)>
91 assert(operands.size() == 2 &&
"binary operation expected 2 operands");
92 auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
93 auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
99 std::optional<APInt> result64 = calculate(lhs.getValue(), rhs.getValue());
102 std::optional<APInt> result32 =
103 calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32));
107 if (result64->trunc(32) != *result32)
110 return IntegerAttr::get(IndexType::get(lhs.getContext()), *result64);
116template <
typename BinaryOp>
123 auto lhsOp = op.getLhs().template getDefiningOp<BinaryOp>();
145 adaptor.getOperands(),
146 [](
const APInt &lhs,
const APInt &rhs) { return lhs + rhs; }))
149 if (
auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
151 if (rhs.getValue().isZero())
158LogicalResult AddOp::canonicalize(AddOp op,
PatternRewriter &rewriter) {
168 adaptor.getOperands(),
169 [](
const APInt &lhs,
const APInt &rhs) { return lhs - rhs; }))
172 if (
auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
174 if (rhs.getValue().isZero())
187 adaptor.getOperands(),
188 [](
const APInt &lhs,
const APInt &rhs) { return lhs * rhs; }))
191 if (
auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
193 if (rhs.getValue().isOne())
196 if (rhs.getValue().isZero())
203LogicalResult MulOp::canonicalize(MulOp op,
PatternRewriter &rewriter) {
213 adaptor.getOperands(),
214 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
218 return lhs.sdiv(rhs);
228 adaptor.getOperands(),
229 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
233 return lhs.udiv(rhs);
251 bool mGtZ = m.sgt(0);
252 if (n.sgt(0) != mGtZ) {
256 return -(-n).sdiv(m);
261 return (n + x).sdiv(m) + 1;
275 adaptor.getOperands(),
276 [](
const APInt &n,
const APInt &m) -> std::optional<APInt> {
284 return (n - 1).udiv(m) + 1;
302 bool mLtZ = m.slt(0);
303 if (n.slt(0) == mLtZ) {
311 return -1 - (x - n).sdiv(m);
324 adaptor.getOperands(),
325 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
329 return lhs.srem(rhs);
339 adaptor.getOperands(),
340 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
344 return lhs.urem(rhs);
354 [](
const APInt &lhs,
const APInt &rhs) {
355 return lhs.sgt(rhs) ? lhs : rhs;
359LogicalResult MaxSOp::canonicalize(MaxSOp op,
PatternRewriter &rewriter) {
369 [](
const APInt &lhs,
const APInt &rhs) {
370 return lhs.ugt(rhs) ? lhs : rhs;
374LogicalResult MaxUOp::canonicalize(MaxUOp op,
PatternRewriter &rewriter) {
384 [](
const APInt &lhs,
const APInt &rhs) {
385 return lhs.slt(rhs) ? lhs : rhs;
389LogicalResult MinSOp::canonicalize(MinSOp op,
PatternRewriter &rewriter) {
399 [](
const APInt &lhs,
const APInt &rhs) {
400 return lhs.ult(rhs) ? lhs : rhs;
404LogicalResult MinUOp::canonicalize(MinUOp op,
PatternRewriter &rewriter) {
414 adaptor.getOperands(),
415 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
431 adaptor.getOperands(),
432 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
436 return lhs.ashr(rhs);
446 adaptor.getOperands(),
447 [](
const APInt &lhs,
const APInt &rhs) -> std::optional<APInt> {
451 return lhs.lshr(rhs);
461 adaptor.getOperands(),
462 [](
const APInt &lhs,
const APInt &rhs) { return lhs & rhs; });
465LogicalResult AndOp::canonicalize(AndOp op,
PatternRewriter &rewriter) {
475 adaptor.getOperands(),
476 [](
const APInt &lhs,
const APInt &rhs) { return lhs | rhs; });
489 adaptor.getOperands(),
490 [](
const APInt &lhs,
const APInt &rhs) { return lhs ^ rhs; });
493LogicalResult XOrOp::canonicalize(XOrOp op,
PatternRewriter &rewriter) {
504 function_ref<APInt(
const APInt &,
unsigned)> extOrTruncFn) {
505 auto attr = dyn_cast_if_present<IntegerAttr>(input);
508 const APInt &value = attr.getValue();
510 if (isa<IndexType>(type)) {
514 APInt
result = extOrTruncFn(value, 64);
515 return IntegerAttr::get(type,
result);
520 auto intType = cast<IntegerType>(type);
521 unsigned width = intType.getWidth();
526 APInt
result = value.trunc(width);
527 return IntegerAttr::get(type,
result);
533 if (extFn(value.trunc(32), 64) != value)
535 APInt
result = extFn(value, width);
536 return IntegerAttr::get(type,
result);
540 APInt
result = value.trunc(width);
541 if (
result != extFn(value.trunc(32), width))
543 return IntegerAttr::get(type,
result);
547 return llvm::isa<IndexType>(lhsTypes.front()) !=
548 llvm::isa<IndexType>(rhsTypes.front());
554 [](
const APInt &x,
unsigned width) {
return x.sext(width); },
555 [](
const APInt &x,
unsigned width) {
return x.sextOrTrunc(width); });
563 return llvm::isa<IndexType>(lhsTypes.front()) !=
564 llvm::isa<IndexType>(rhsTypes.front());
570 [](
const APInt &x,
unsigned width) {
return x.zext(width); },
571 [](
const APInt &x,
unsigned width) {
return x.zextOrTrunc(width); });
580 IndexCmpPredicate pred) {
582 case IndexCmpPredicate::EQ:
584 case IndexCmpPredicate::NE:
586 case IndexCmpPredicate::SGE:
588 case IndexCmpPredicate::SGT:
590 case IndexCmpPredicate::SLE:
592 case IndexCmpPredicate::SLT:
594 case IndexCmpPredicate::UGE:
596 case IndexCmpPredicate::UGT:
598 case IndexCmpPredicate::ULE:
600 case IndexCmpPredicate::ULT:
603 llvm_unreachable(
"unhandled IndexCmpPredicate predicate");
612 const APInt &cstB,
unsigned width,
613 IndexCmpPredicate pred) {
615 .Case([&](MinSOp op) {
617 APInt::getSignedMinValue(width), cstA);
619 .Case([&](MinUOp op) {
621 APInt::getMinValue(width), cstA);
623 .Case([&](MaxSOp op) {
625 cstA, APInt::getSignedMaxValue(width));
627 .Case([&](MaxUOp op) {
629 cstA, APInt::getMaxValue(width));
638 case IndexCmpPredicate::EQ:
639 case IndexCmpPredicate::SGE:
640 case IndexCmpPredicate::SLE:
641 case IndexCmpPredicate::UGE:
642 case IndexCmpPredicate::ULE:
644 case IndexCmpPredicate::NE:
645 case IndexCmpPredicate::SGT:
646 case IndexCmpPredicate::SLT:
647 case IndexCmpPredicate::UGT:
648 case IndexCmpPredicate::ULT:
651 llvm_unreachable(
"unknown predicate in compareSameArgs");
656 auto lhs = dyn_cast_if_present<IntegerAttr>(adaptor.getLhs());
657 auto rhs = dyn_cast_if_present<IntegerAttr>(adaptor.getRhs());
660 bool result64 =
compareIndices(lhs.getValue(), rhs.getValue(), getPred());
662 rhs.getValue().trunc(32), getPred());
663 if (result64 == result32)
668 Operation *lhsOp = getLhs().getDefiningOp();
670 if (isa_and_nonnull<MinSOp, MinUOp, MaxSOp, MaxUOp>(lhsOp) &&
673 lhsOp, cstA.getValue(), rhs.getValue(), 64, getPred());
674 std::optional<bool> result32 =
676 rhs.getValue().trunc(32), 32, getPred());
678 if (result64 && result32 && *result64 == *result32)
683 if (getLhs() == getRhs())
694LogicalResult CmpOp::canonicalize(CmpOp op,
PatternRewriter &rewriter) {
699 cmpRhs.getValue().isZero();
701 cmpLhs.getValue().isZero();
702 if (!rhsIsZero && !lhsIsZero)
704 "cmp is not comparing something with 0");
706 SubOp subOp = rhsIsZero ? op.getLhs().getDefiningOp<index::SubOp>()
707 : op.getRhs().getDefiningOp<
index::SubOp>();
710 op.getLoc(),
"non-zero operand is not a result of subtraction");
712 if (op.getPred() != IndexCmpPredicate::EQ &&
713 op.getPred() != IndexCmpPredicate::NE)
716 "only eq and ne comparisons can be canonicalized through subtraction");
720 newCmp = index::CmpOp::create(rewriter, op.getLoc(), op.getPred(),
721 subOp.getLhs(), subOp.getRhs());
723 newCmp = index::CmpOp::create(rewriter, op.getLoc(), op.getPred(),
724 subOp.getRhs(), subOp.getLhs());
734void ConstantOp::getAsmResultNames(
737 llvm::raw_svector_ostream specialName(specialNameBuffer);
738 specialName <<
"idx" << getValueAttr().getValue();
739 setNameFn(getResult(), specialName.str());
742OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
return getValueAttr(); }
745 build(
b, state,
b.getIndexType(),
b.getIndexAttr(value));
753 return getValueAttr();
756void BoolConstantOp::getAsmResultNames(
758 setNameFn(getResult(), getValue() ?
"true" :
"false");
765#define GET_OP_CLASSES
766#include "mlir/Dialect/Index/IR/IndexOps.cpp.inc"
static OpFoldResult foldBinaryOpUnchecked(ArrayRef< Attribute > operands, function_ref< std::optional< APInt >(const APInt &, const APInt &)> calculate)
Fold an index operation irrespective of the target bitwidth.
static std::optional< APInt > calculateFloorDivS(const APInt &n, const APInt &m)
Compute floordivs(n, m) as x = m < 0 ?
static std::optional< APInt > calculateCeilDivS(const APInt &n, const APInt &m)
Compute ceildivs(n, m) as x = m > 0 ?
static std::optional< bool > foldCmpOfMaxOrMin(Operation *lhsOp, const APInt &cstA, const APInt &cstB, unsigned width, IndexCmpPredicate pred)
cmp(max/min(x, cstA), cstB) can be folded to a constant depending on the values of cstA and cstB,...
static LogicalResult canonicalizeAssociativeCommutativeBinaryOp(BinaryOp op, PatternRewriter &rewriter)
Helper for associative and commutative binary ops that can be transformed: x = op(v,...
static bool compareIndices(const APInt &lhs, const APInt &rhs, IndexCmpPredicate pred)
Compare two integers according to the comparison predicate.
static OpFoldResult foldBinaryOpChecked(ArrayRef< Attribute > operands, function_ref< std::optional< APInt >(const APInt &, const APInt &lhs)> calculate)
Fold an index operation only if the truncated 64-bit result matches the 32-bit result for operations ...
static OpFoldResult foldCastOp(Attribute input, Type type, function_ref< APInt(const APInt &, unsigned)> extFn, function_ref< APInt(const APInt &, unsigned)> extOrTruncFn)
static bool compareSameArgs(IndexCmpPredicate pred)
Return the result of cmp(pred, x, x)
Attributes are known-constant values of operations.
static BoolAttr get(MLIRContext *context, bool value)
A set of arbitrary-precision integers representing bounds on a given integer value.
static ConstantIntRanges constant(const APInt &value)
Create a ConstantIntRanges with a constant value - that is, with the bounds [value,...
static ConstantIntRanges fromUnsigned(const APInt &umin, const APInt &umax)
Create an ConstantIntRanges with the unsigned minimum and maximum equal to umin and umax and the sign...
static ConstantIntRanges fromSigned(const APInt &smin, const APInt &smax)
Create an ConstantIntRanges with the signed minimum and maximum equal to smin and smax,...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
std::optional< bool > evaluatePred(CmpPredicate pred, const ConstantIntRanges &lhs, const ConstantIntRanges &rhs)
Returns a boolean value if pred is statically true or false for anypossible inputs falling within lhs...
CmpPredicate
Copy of the enum from arith and index to allow the common integer range infrastructure to not depend ...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::TypeSwitch< T, ResultT > TypeSwitch
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
llvm::function_ref< Fn > function_ref
This represents an operation in an abstracted form, suitable for use with the builder APIs.