MLIR 24.0.0git
ArithOps.cpp
Go to the documentation of this file.
1//===- ArithOps.cpp - MLIR Arith dialect ops implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <cassert>
10#include <cstdint>
11#include <functional>
12#include <type_traits>
13#include <utility>
14
18#include "mlir/IR/Builders.h"
21#include "mlir/IR/Matchers.h"
27
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/FloatingPointMode.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/TypeSwitch.h"
36
37using namespace mlir;
38using namespace mlir::arith;
39
40/// Default rounding mode according to default LLVM floating-point environment.
41static constexpr llvm::RoundingMode kDefaultRoundingMode =
42 llvm::RoundingMode::NearestTiesToEven;
43
44//===----------------------------------------------------------------------===//
45// Pattern helpers
46//===----------------------------------------------------------------------===//
47
48static IntegerAttr
50 Attribute rhs,
51 function_ref<APInt(const APInt &, const APInt &)> binFn) {
52 const APInt &lhsVal = llvm::cast<IntegerAttr>(lhs).getValue();
53 const APInt &rhsVal = llvm::cast<IntegerAttr>(rhs).getValue();
54 APInt value = binFn(lhsVal, rhsVal);
55 return IntegerAttr::get(res.getType(), value);
56}
57
58static IntegerAttr addIntegerAttrs(PatternRewriter &builder, Value res,
59 Attribute lhs, Attribute rhs) {
60 return applyToIntegerAttrs(builder, res, lhs, rhs, std::plus<APInt>());
61}
62
63static IntegerAttr subIntegerAttrs(PatternRewriter &builder, Value res,
64 Attribute lhs, Attribute rhs) {
65 return applyToIntegerAttrs(builder, res, lhs, rhs, std::minus<APInt>());
66}
67
68static IntegerAttr mulIntegerAttrs(PatternRewriter &builder, Value res,
69 Attribute lhs, Attribute rhs) {
70 return applyToIntegerAttrs(builder, res, lhs, rhs, std::multiplies<APInt>());
71}
72
73static IntegerAttr andIntegerAttrs(PatternRewriter &builder, Value res,
74 Attribute lhs, Attribute rhs) {
75 return applyToIntegerAttrs(builder, res, lhs, rhs, std::bit_and<APInt>());
76}
77
78static IntegerAttr orIntegerAttrs(PatternRewriter &builder, Value res,
79 Attribute lhs, Attribute rhs) {
80 return applyToIntegerAttrs(builder, res, lhs, rhs, std::bit_or<APInt>());
81}
82
83static IntegerAttr xorIntegerAttrs(PatternRewriter &builder, Value res,
84 Attribute lhs, Attribute rhs) {
85 return applyToIntegerAttrs(builder, res, lhs, rhs, std::bit_xor<APInt>());
86}
87
88// Intersect overflow flags. Callers must ensure the common flags remain valid
89// after rewriting.
90static IntegerOverflowFlagsAttr
91mergeOverflowFlags(IntegerOverflowFlagsAttr val1,
92 IntegerOverflowFlagsAttr val2) {
93 return IntegerOverflowFlagsAttr::get(val1.getContext(),
94 val1.getValue() & val2.getValue());
95}
96
97using OverflowCheckedBinaryOp = APInt (APInt::*)(const APInt &, bool &) const;
98
99// For fixed-width integers, if combining the constants does not overflow, the
100// reassociated expression has the same mathematical result as the original
101// expression. Common source flags then rule out overflow in the new operation.
102static IntegerOverflowFlagsAttr mergeOverflowFlagsForReassociation(
103 IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2, Attribute lhs,
105 OverflowCheckedBinaryOp unsignedOp) {
106 IntegerOverflowFlags flags = val1.getValue() & val2.getValue();
107 if (flags == IntegerOverflowFlags::none)
108 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
109
110 auto lhsAttr = llvm::cast<IntegerAttr>(lhs);
111 auto rhsAttr = llvm::cast<IntegerAttr>(rhs);
112 // TODO: Handle index separately; its storage width is not its target width.
113 if (isa<IndexType>(lhsAttr.getType()))
114 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
115
116 const APInt &lhsValue = lhsAttr.getValue();
117 const APInt &rhsValue = rhsAttr.getValue();
118 bool overflow;
119 if (bitEnumContainsAny(flags, IntegerOverflowFlags::nsw)) {
120 (void)(lhsValue.*signedOp)(rhsValue, overflow);
121 if (overflow)
122 flags = bitEnumClear(flags, IntegerOverflowFlags::nsw);
123 }
124 if (bitEnumContainsAny(flags, IntegerOverflowFlags::nuw)) {
125 (void)(lhsValue.*unsignedOp)(rhsValue, overflow);
126 if (overflow)
127 flags = bitEnumClear(flags, IntegerOverflowFlags::nuw);
128 }
129 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
130}
131
132/// Invert an integer comparison predicate.
133arith::CmpIPredicate arith::invertPredicate(arith::CmpIPredicate pred) {
134 switch (pred) {
135 case arith::CmpIPredicate::eq:
136 return arith::CmpIPredicate::ne;
137 case arith::CmpIPredicate::ne:
138 return arith::CmpIPredicate::eq;
139 case arith::CmpIPredicate::slt:
140 return arith::CmpIPredicate::sge;
141 case arith::CmpIPredicate::sle:
142 return arith::CmpIPredicate::sgt;
143 case arith::CmpIPredicate::sgt:
144 return arith::CmpIPredicate::sle;
145 case arith::CmpIPredicate::sge:
146 return arith::CmpIPredicate::slt;
147 case arith::CmpIPredicate::ult:
148 return arith::CmpIPredicate::uge;
149 case arith::CmpIPredicate::ule:
150 return arith::CmpIPredicate::ugt;
151 case arith::CmpIPredicate::ugt:
152 return arith::CmpIPredicate::ule;
153 case arith::CmpIPredicate::uge:
154 return arith::CmpIPredicate::ult;
155 }
156 llvm_unreachable("unknown cmpi predicate kind");
157}
158
159/// Equivalent to
160/// convertRoundingModeToLLVM(convertArithRoundingModeToLLVM(roundingMode)).
161///
162/// Not possible to implement as chain of calls as this would introduce a
163/// circular dependency with MLIRArithAttrToLLVMConversion and make arith depend
164/// on the LLVM dialect and on translation to LLVM.
165static llvm::RoundingMode
166convertArithRoundingModeToLLVMIR(std::optional<RoundingMode> roundingMode) {
167 if (!roundingMode)
169 switch (*roundingMode) {
170 case RoundingMode::downward:
171 return llvm::RoundingMode::TowardNegative;
172 case RoundingMode::to_nearest_away:
173 return llvm::RoundingMode::NearestTiesToAway;
174 case RoundingMode::to_nearest_even:
175 return llvm::RoundingMode::NearestTiesToEven;
176 case RoundingMode::toward_zero:
177 return llvm::RoundingMode::TowardZero;
178 case RoundingMode::upward:
179 return llvm::RoundingMode::TowardPositive;
180 }
181 llvm_unreachable("Unhandled rounding mode");
182}
183
184static arith::CmpIPredicateAttr invertPredicate(arith::CmpIPredicateAttr pred) {
185 return arith::CmpIPredicateAttr::get(pred.getContext(),
186 invertPredicate(pred.getValue()));
187}
188
190 Type elemTy = getElementTypeOrSelf(type);
191 if (elemTy.isIntOrFloat())
192 return elemTy.getIntOrFloatBitWidth();
193
194 return -1;
195}
196
198 return getScalarOrElementWidth(value.getType());
199}
200
201/// Returns true if every value of `intValue`'s integer type converts exactly.
202static bool isExactIntToFPCast(Value intValue, Value fpValue, bool isSigned) {
203 auto fpTy = dyn_cast<FloatType>(getElementTypeOrSelf(fpValue.getType()));
204 int64_t intWidth = getScalarOrElementWidth(intValue);
205 if (!fpTy || intWidth <= 0)
206 return false;
207 const llvm::fltSemantics &semantics = fpTy.getFloatSemantics();
208 // Zero and, for signed integers, negative values must be representable.
209 if (!APFloat::semanticsHasZero(semantics) ||
210 (isSigned && !APFloat::semanticsHasSignedRepr(semantics)))
211 return false;
212 // The magnitude bits must fit the mantissa and the exponent range.
213 int64_t magnitudeBits = intWidth - (isSigned ? 1 : 0);
214 return magnitudeBits <= fpTy.getFPMantissaWidth() &&
215 intWidth - 1 <= APFloat::semanticsMaxExponent(semantics);
216}
217
218static FailureOr<APInt> getIntOrSplatIntValue(Attribute attr) {
219 APInt value;
220 if (matchPattern(attr, m_ConstantInt(&value)))
221 return value;
222
223 return failure();
224}
225
226static Attribute getBoolAttribute(Type type, bool value) {
227 auto boolAttr = BoolAttr::get(type.getContext(), value);
228 ShapedType shapedType = dyn_cast_or_null<ShapedType>(type);
229 if (!shapedType)
230 return boolAttr;
231 // DenseElementsAttr requires a static shape.
232 if (!shapedType.hasStaticShape())
233 return {};
234 return DenseElementsAttr::get(shapedType, boolAttr);
235}
236
237/// Return a scalar or splat integer attribute of `type` (an integer/index type
238/// or a shaped type thereof) holding `value`. Returns a null attribute for
239/// shaped types with a dynamic shape, so callers can bail out of folding.
241 auto scalarAttr = IntegerAttr::get(getElementTypeOrSelf(type), value);
242 ShapedType shapedType = dyn_cast<ShapedType>(type);
243 if (!shapedType)
244 return scalarAttr;
245 if (!shapedType.hasStaticShape())
246 return {};
247 return DenseElementsAttr::get(shapedType, scalarAttr);
248}
249
250//===----------------------------------------------------------------------===//
251// TableGen'd canonicalization patterns
252//===----------------------------------------------------------------------===//
253
254namespace {
255#include "ArithCanonicalization.inc"
256} // namespace
257
258//===----------------------------------------------------------------------===//
259// Common helpers
260//===----------------------------------------------------------------------===//
261
262/// Return the type of the same shape (scalar, vector or tensor) containing i1.
264 auto i1Type = IntegerType::get(type.getContext(), 1);
265 if (auto shapedType = dyn_cast<ShapedType>(type))
266 return shapedType.cloneWith(std::nullopt, i1Type);
267 if (llvm::isa<UnrankedTensorType>(type))
268 return UnrankedTensorType::get(i1Type);
269 return i1Type;
270}
271
272//===----------------------------------------------------------------------===//
273// ConstantOp
274//===----------------------------------------------------------------------===//
275
276void arith::ConstantOp::getAsmResultNames(
277 function_ref<void(Value, StringRef)> setNameFn) {
278 auto type = getType();
279 if (auto intCst = dyn_cast<IntegerAttr>(getValue())) {
280 auto intType = dyn_cast<IntegerType>(type);
281
282 // Sugar i1 constants with 'true' and 'false'.
283 if (intType && intType.getWidth() == 1)
284 return setNameFn(getResult(), (intCst.getInt() ? "true" : "false"));
285
286 // Otherwise, build a complex name with the value and type.
287 SmallString<32> specialNameBuffer;
288 llvm::raw_svector_ostream specialName(specialNameBuffer);
289 specialName << 'c' << intCst.getValue();
290 if (intType)
291 specialName << '_' << type;
292 setNameFn(getResult(), specialName.str());
293 } else {
294 setNameFn(getResult(), "cst");
295 }
296}
297
298/// TODO: disallow arith.constant to return anything other than signless integer
299/// or float like.
300LogicalResult arith::ConstantOp::verify() {
301 auto type = getType();
302 // Integer values must be signless.
303 if (auto intType = dyn_cast<IntegerType>(getElementTypeOrSelf(type));
304 intType && !intType.isSignless())
305 return emitOpError("integer return type must be signless");
306 // Any float or elements attribute are acceptable.
307 if (!llvm::isa<IntegerAttr, FloatAttr, ElementsAttr>(getValue())) {
308 return emitOpError(
309 "value must be an integer, float, or elements attribute");
310 }
311
312 // Note, we could relax this for vectors with 1 scalable dim, e.g.:
313 // * arith.constant dense<[[3, 3], [1, 1]]> : vector<2 x [2] x i32>
314 // However, this would most likely require updating the lowerings to LLVM.
315 if (isa<ScalableVectorType>(type) && !isa<SplatElementsAttr>(getValue()))
316 return emitOpError(
317 "initializing scalable vectors with elements attribute is not supported"
318 " unless it's a vector splat");
319 return success();
320}
321
322bool arith::ConstantOp::isBuildableWith(Attribute value, Type type) {
323 // The value's type must be the same as the provided type.
324 auto typedAttr = dyn_cast<TypedAttr>(value);
325 if (!typedAttr || typedAttr.getType() != type)
326 return false;
327 // Integer values must be signless.
328 if (auto intType = dyn_cast<IntegerType>(getElementTypeOrSelf(type))) {
329 if (!intType.isSignless())
330 return false;
331 }
332 // Integer, float, and element attributes are buildable.
333 return llvm::isa<IntegerAttr, FloatAttr, ElementsAttr>(value);
334}
335
336ConstantOp arith::ConstantOp::materialize(OpBuilder &builder, Attribute value,
337 Type type, Location loc) {
338 if (isBuildableWith(value, type))
339 return arith::ConstantOp::create(builder, loc, cast<TypedAttr>(value));
340 return nullptr;
341}
342
343OpFoldResult arith::ConstantOp::fold(FoldAdaptor adaptor) { return getValue(); }
344
346 int64_t value, unsigned width) {
347 auto type = builder.getIntegerType(width);
348 arith::ConstantOp::build(builder, result, type,
349 builder.getIntegerAttr(type, value));
350}
351
353 Location location,
355 unsigned width) {
356 mlir::OperationState state(location, getOperationName());
357 build(builder, state, value, width);
358 auto result = dyn_cast<ConstantIntOp>(builder.create(state));
359 assert(result && "builder didn't return the right type");
360 return result;
361}
362
365 unsigned width) {
366 return create(builder, builder.getLoc(), value, width);
367}
368
370 Type type, int64_t value) {
371 arith::ConstantOp::build(builder, result, type,
372 builder.getIntegerAttr(type, value));
373}
374
376 Location location, Type type,
377 int64_t value) {
378 mlir::OperationState state(location, getOperationName());
379 build(builder, state, type, value);
380 auto result = dyn_cast<ConstantIntOp>(builder.create(state));
381 assert(result && "builder didn't return the right type");
382 return result;
383}
384
386 Type type, int64_t value) {
387 return create(builder, builder.getLoc(), type, value);
388}
389
391 Type type, const APInt &value) {
392 arith::ConstantOp::build(builder, result, type,
393 builder.getIntegerAttr(type, value));
394}
395
397 Location location, Type type,
398 const APInt &value) {
399 mlir::OperationState state(location, getOperationName());
400 build(builder, state, type, value);
401 auto result = dyn_cast<ConstantIntOp>(builder.create(state));
402 assert(result && "builder didn't return the right type");
403 return result;
404}
405
407 Type type,
408 const APInt &value) {
409 return create(builder, builder.getLoc(), type, value);
410}
411
413 if (auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
414 return constOp.getType().isSignlessInteger();
415 return false;
416}
417
419 FloatType type, const APFloat &value) {
420 arith::ConstantOp::build(builder, result, type,
421 builder.getFloatAttr(type, value));
422}
423
425 Location location,
426 FloatType type,
427 const APFloat &value) {
428 mlir::OperationState state(location, getOperationName());
429 build(builder, state, type, value);
430 auto result = dyn_cast<ConstantFloatOp>(builder.create(state));
431 assert(result && "builder didn't return the right type");
432 return result;
433}
434
437 const APFloat &value) {
438 return create(builder, builder.getLoc(), type, value);
439}
440
442 if (auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
443 return llvm::isa<FloatType>(constOp.getType());
444 return false;
445}
446
448 int64_t value) {
449 arith::ConstantOp::build(builder, result, builder.getIndexType(),
450 builder.getIndexAttr(value));
451}
452
454 Location location,
455 int64_t value) {
456 mlir::OperationState state(location, getOperationName());
457 build(builder, state, value);
458 auto result = dyn_cast<ConstantIndexOp>(builder.create(state));
459 assert(result && "builder didn't return the right type");
460 return result;
461}
462
465 return create(builder, builder.getLoc(), value);
466}
467
469 if (auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
470 return constOp.getType().isIndex();
471 return false;
472}
473
475 Type type) {
476 // TODO: Incorporate this check to `FloatAttr::get*`.
477 assert(!isa<Float8E8M0FNUType>(getElementTypeOrSelf(type)) &&
478 "type doesn't have a zero representation");
479 TypedAttr zeroAttr = builder.getZeroAttr(type);
480 assert(zeroAttr && "unsupported type for zero attribute");
481 return arith::ConstantOp::create(builder, loc, zeroAttr);
482}
483
484//===----------------------------------------------------------------------===//
485// AddIOp
486//===----------------------------------------------------------------------===//
487
488OpFoldResult arith::AddIOp::fold(FoldAdaptor adaptor) {
489 // addi(x, 0) -> x
490 if (matchPattern(adaptor.getRhs(), m_Zero()))
491 return getLhs();
492
493 // addi(subi(a, b), b) -> a
494 if (auto sub = getLhs().getDefiningOp<SubIOp>())
495 if (getRhs() == sub.getRhs())
496 return sub.getLhs();
497
498 // addi(b, subi(a, b)) -> a
499 if (auto sub = getRhs().getDefiningOp<SubIOp>())
500 if (getLhs() == sub.getRhs())
501 return sub.getLhs();
502
504 adaptor.getOperands(),
505 [](APInt a, const APInt &b) { return std::move(a) + b; });
506}
507
508void arith::AddIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
509 MLIRContext *context) {
510 patterns.add<AddIAddConstant, AddISubConstantRHS, AddISubConstantLHS,
511 AddIMulNegativeOneRhs, AddIMulNegativeOneLhs>(context);
512}
513
514//===----------------------------------------------------------------------===//
515// AddUIExtendedOp
516//===----------------------------------------------------------------------===//
517
518std::optional<SmallVector<int64_t, 4>>
519arith::AddUIExtendedOp::getIterationShapeToUnroll() {
520 if (auto vt = dyn_cast<VectorType>(getType(0)))
521 return llvm::to_vector<4>(vt.getShape());
522 return std::nullopt;
523}
524
525// Returns the overflow bit, assuming that `sum` is the result of unsigned
526// addition of `operand` and another number.
527static APInt calculateUnsignedOverflow(const APInt &sum, const APInt &operand) {
528 return sum.ult(operand) ? APInt::getAllOnes(1) : APInt::getZero(1);
529}
530
531LogicalResult
532arith::AddUIExtendedOp::fold(FoldAdaptor adaptor,
533 SmallVectorImpl<OpFoldResult> &results) {
534 Type overflowTy = getOverflow().getType();
535 // addui_extended(x, 0) -> x, false
536 if (matchPattern(getRhs(), m_Zero())) {
537 Builder builder(getContext());
538 auto falseValue = builder.getZeroAttr(overflowTy);
539
540 results.push_back(getLhs());
541 results.push_back(falseValue);
542 return success();
543 }
544
545 // addui_extended(constant_a, constant_b) -> constant_sum, constant_carry
546 // Let the `constFoldBinaryOp` utility attempt to fold the sum of both
547 // operands. If that succeeds, calculate the overflow bit based on the sum
548 // and the first (constant) operand, `lhs`.
549 if (Attribute sumAttr = constFoldBinaryOp<IntegerAttr>(
550 adaptor.getOperands(),
551 [](APInt a, const APInt &b) { return std::move(a) + b; })) {
552 // If any operand is poison, propagate poison to both results.
553 if (matchPattern(sumAttr, ub::m_Poison())) {
554 results.push_back(sumAttr);
555 results.push_back(sumAttr);
556 return success();
557 }
558 Attribute overflowAttr = constFoldBinaryOp<IntegerAttr>(
559 ArrayRef({sumAttr, adaptor.getLhs()}),
560 getI1SameShape(llvm::cast<TypedAttr>(sumAttr).getType()),
562 if (!overflowAttr)
563 return failure();
564
565 results.push_back(sumAttr);
566 results.push_back(overflowAttr);
567 return success();
568 }
569
570 return failure();
571}
572
573void arith::AddUIExtendedOp::getCanonicalizationPatterns(
574 RewritePatternSet &patterns, MLIRContext *context) {
575 patterns.add<AddUIExtendedToAddI>(context);
576}
577
578//===----------------------------------------------------------------------===//
579// SubUIExtendedOp
580//===----------------------------------------------------------------------===//
581
582std::optional<SmallVector<int64_t, 4>>
583arith::SubUIExtendedOp::getIterationShapeToUnroll() {
584 if (auto vt = dyn_cast<VectorType>(getType(0)))
585 return llvm::to_vector<4>(vt.getShape());
586 return std::nullopt;
587}
588
589// Returns the borrow bit, assuming `lhs` and `rhs` are operands of an unsigned
590// subtraction whose mathematical result underflows iff `lhs < rhs`.
591static APInt calculateUnsignedBorrow(const APInt &lhs, const APInt &rhs) {
592 return lhs.ult(rhs) ? APInt::getAllOnes(1) : APInt::getZero(1);
593}
594
595LogicalResult
596arith::SubUIExtendedOp::fold(FoldAdaptor adaptor,
597 SmallVectorImpl<OpFoldResult> &results) {
598 Type borrowTy = getBorrow().getType();
599 // subui_extended(x, 0) -> x, false
600 if (matchPattern(getRhs(), m_Zero())) {
601 Builder builder(getContext());
602 auto falseValue = builder.getZeroAttr(borrowTy);
603
604 results.push_back(getLhs());
605 results.push_back(falseValue);
606 return success();
607 }
608
609 // subui_extended(x, x) -> 0, false
610 if (getLhs() == getRhs()) {
611 // A dynamically-shaped result cannot be a constant; bail before
612 // getZeroAttr, which would assert on a non-static shape.
613 auto shapedType = dyn_cast<ShapedType>(getDiff().getType());
614 if (shapedType && !shapedType.hasStaticShape())
615 return failure();
616 Builder builder(getContext());
617 auto zeroDiff = builder.getZeroAttr(getDiff().getType());
618 auto falseValue = builder.getZeroAttr(borrowTy);
619 if (!zeroDiff)
620 return failure();
621
622 results.push_back(zeroDiff);
623 results.push_back(falseValue);
624 return success();
625 }
626
627 // subui_extended(constant_a, constant_b) -> constant_diff, constant_borrow
628 if (Attribute diffAttr = constFoldBinaryOp<IntegerAttr>(
629 adaptor.getOperands(),
630 [](APInt a, const APInt &b) { return std::move(a) - b; })) {
631 // If any operand is poison, propagate poison to both results.
632 if (matchPattern(diffAttr, ub::m_Poison())) {
633 results.push_back(diffAttr);
634 results.push_back(diffAttr);
635 return success();
636 }
637 Attribute borrowAttr = constFoldBinaryOp<IntegerAttr>(
638 adaptor.getOperands(),
639 getI1SameShape(llvm::cast<TypedAttr>(diffAttr).getType()),
641 if (!borrowAttr)
642 return failure();
643
644 results.push_back(diffAttr);
645 results.push_back(borrowAttr);
646 return success();
647 }
648
649 return failure();
650}
651
652void arith::SubUIExtendedOp::getCanonicalizationPatterns(
653 RewritePatternSet &patterns, MLIRContext *context) {
654 patterns.add<SubUIExtendedToSubI>(context);
655}
656
657//===----------------------------------------------------------------------===//
658// SubIOp
659//===----------------------------------------------------------------------===//
660
661OpFoldResult arith::SubIOp::fold(FoldAdaptor adaptor) {
662 // subi(x,x) -> 0
663 if (getOperand(0) == getOperand(1)) {
664 auto shapedType = dyn_cast<ShapedType>(getType());
665 // We can't generate a constant with a dynamic shaped tensor.
666 if (!shapedType || shapedType.hasStaticShape())
667 return Builder(getContext()).getZeroAttr(getType());
668 }
669 // subi(x,0) -> x
670 if (matchPattern(adaptor.getRhs(), m_Zero()))
671 return getLhs();
672
673 if (auto add = getLhs().getDefiningOp<AddIOp>()) {
674 // subi(addi(a, b), b) -> a
675 if (getRhs() == add.getRhs())
676 return add.getLhs();
677 // subi(addi(a, b), a) -> b
678 if (getRhs() == add.getLhs())
679 return add.getRhs();
680 }
681
682 // subi(a, subi(a, b)) -> b
683 if (auto sub = getRhs().getDefiningOp<SubIOp>())
684 if (getLhs() == sub.getLhs())
685 return sub.getRhs();
686
688 adaptor.getOperands(),
689 [](APInt a, const APInt &b) { return std::move(a) - b; });
690}
691
692void arith::SubIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
693 MLIRContext *context) {
694 patterns.add<SubIRHSAddConstant, SubILHSAddConstant, SubIRHSSubConstantRHS,
695 SubIRHSSubConstantLHS, SubILHSSubConstantRHS,
696 SubILHSSubConstantLHS, SubISubILHSRHSLHS>(context);
697}
698
699//===----------------------------------------------------------------------===//
700// MulIOp
701//===----------------------------------------------------------------------===//
702
703OpFoldResult arith::MulIOp::fold(FoldAdaptor adaptor) {
704 // muli(x, 0) -> 0
705 if (matchPattern(adaptor.getRhs(), m_Zero()))
706 return getRhs();
707 // muli(x, 1) -> x
708 if (matchPattern(adaptor.getRhs(), m_One()))
709 return getLhs();
710 // TODO: Handle the overflow case.
711
712 // default folder
714 adaptor.getOperands(),
715 [](const APInt &a, const APInt &b) { return a * b; });
716}
717
718void arith::MulIOp::getAsmResultNames(
719 function_ref<void(Value, StringRef)> setNameFn) {
720 if (!isa<IndexType>(getType()))
721 return;
722
723 // Match vector.vscale by name to avoid depending on the vector dialect (which
724 // is a circular dependency).
725 auto isVscale = [](Operation *op) {
726 return op && op->getName().getStringRef() == "vector.vscale";
727 };
728
729 IntegerAttr baseValue;
730 auto isVscaleExpr = [&](Value a, Value b) {
731 return matchPattern(a, m_Constant(&baseValue)) &&
732 isVscale(b.getDefiningOp());
733 };
734
735 if (!isVscaleExpr(getLhs(), getRhs()) && !isVscaleExpr(getRhs(), getLhs()))
736 return;
737
738 // Name `base * vscale` or `vscale * base` as `c<base_value>_vscale`.
739 SmallString<32> specialNameBuffer;
740 llvm::raw_svector_ostream specialName(specialNameBuffer);
741 specialName << 'c' << baseValue.getInt() << "_vscale";
742 setNameFn(getResult(), specialName.str());
743}
744
745void arith::MulIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
746 MLIRContext *context) {
747 patterns.add<MulIMulIConstant>(context);
748}
749
750//===----------------------------------------------------------------------===//
751// MulSIExtendedOp
752//===----------------------------------------------------------------------===//
753
754std::optional<SmallVector<int64_t, 4>>
755arith::MulSIExtendedOp::getIterationShapeToUnroll() {
756 if (auto vt = dyn_cast<VectorType>(getType(0)))
757 return llvm::to_vector<4>(vt.getShape());
758 return std::nullopt;
759}
760
761LogicalResult
762arith::MulSIExtendedOp::fold(FoldAdaptor adaptor,
763 SmallVectorImpl<OpFoldResult> &results) {
764 // mulsi_extended(x, 0) -> 0, 0
765 if (matchPattern(adaptor.getRhs(), m_Zero())) {
766 Attribute zero = adaptor.getRhs();
767 results.push_back(zero);
768 results.push_back(zero);
769 return success();
770 }
771
772 // mulsi_extended(cst_a, cst_b) -> cst_low, cst_high
773 if (Attribute lowAttr = constFoldBinaryOp<IntegerAttr>(
774 adaptor.getOperands(),
775 [](const APInt &a, const APInt &b) { return a * b; })) {
776 // Invoke the constant fold helper again to calculate the 'high' result.
777 Attribute highAttr = constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
778 llvm::APIntOps::mulhs);
779 assert(highAttr && "Unexpected constant-folding failure");
780
781 results.push_back(lowAttr);
782 results.push_back(highAttr);
783 return success();
784 }
785
786 return failure();
787}
788
789void arith::MulSIExtendedOp::getCanonicalizationPatterns(
790 RewritePatternSet &patterns, MLIRContext *context) {
791 patterns.add<MulSIExtendedToMulI, MulSIExtendedRHSOne>(context);
792}
793
794//===----------------------------------------------------------------------===//
795// MulUIExtendedOp
796//===----------------------------------------------------------------------===//
797
798std::optional<SmallVector<int64_t, 4>>
799arith::MulUIExtendedOp::getIterationShapeToUnroll() {
800 if (auto vt = dyn_cast<VectorType>(getType(0)))
801 return llvm::to_vector<4>(vt.getShape());
802 return std::nullopt;
803}
804
805LogicalResult
806arith::MulUIExtendedOp::fold(FoldAdaptor adaptor,
807 SmallVectorImpl<OpFoldResult> &results) {
808 // mului_extended(x, 0) -> 0, 0
809 if (matchPattern(adaptor.getRhs(), m_Zero())) {
810 Attribute zero = adaptor.getRhs();
811 results.push_back(zero);
812 results.push_back(zero);
813 return success();
814 }
815
816 // mului_extended(x, 1) -> x, 0
817 if (matchPattern(adaptor.getRhs(), m_One())) {
818 Builder builder(getContext());
819 Attribute zero = builder.getZeroAttr(getLhs().getType());
820 results.push_back(getLhs());
821 results.push_back(zero);
822 return success();
823 }
824
825 // mului_extended(cst_a, cst_b) -> cst_low, cst_high
826 if (Attribute lowAttr = constFoldBinaryOp<IntegerAttr>(
827 adaptor.getOperands(),
828 [](const APInt &a, const APInt &b) { return a * b; })) {
829 // Invoke the constant fold helper again to calculate the 'high' result.
830 Attribute highAttr = constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
831 llvm::APIntOps::mulhu);
832 assert(highAttr && "Unexpected constant-folding failure");
833
834 results.push_back(lowAttr);
835 results.push_back(highAttr);
836 return success();
837 }
838
839 return failure();
840}
841
842void arith::MulUIExtendedOp::getCanonicalizationPatterns(
843 RewritePatternSet &patterns, MLIRContext *context) {
844 patterns.add<MulUIExtendedToMulI>(context);
845}
846
847//===----------------------------------------------------------------------===//
848// DivUIOp
849//===----------------------------------------------------------------------===//
850
851/// Fold `(a * b) / b -> a`
852static Value foldDivMul(Value lhs, Value rhs,
853 arith::IntegerOverflowFlags ovfFlags) {
854 auto mul = lhs.getDefiningOp<mlir::arith::MulIOp>();
855 if (!mul || !bitEnumContainsAll(mul.getOverflowFlags(), ovfFlags))
856 return {};
857
858 if (mul.getLhs() == rhs)
859 return mul.getRhs();
860
861 if (mul.getRhs() == rhs)
862 return mul.getLhs();
863
864 return {};
865}
866
867OpFoldResult arith::DivUIOp::fold(FoldAdaptor adaptor) {
868 // TODO: divui (x, 0) -> poison. Division by zero is undefined behaviour and
869 // could fold to poison, but that would make the arith dialect depend on the
870 // ub dialect to materialize ub.poison; left out for now.
871
872 // divui (x, 1) -> x.
873 if (matchPattern(adaptor.getRhs(), m_One()))
874 return getLhs();
875
876 // divui (0, x) -> 0. Division by zero is UB, so refining to 0 is valid.
877 if (matchPattern(adaptor.getLhs(), m_Zero()))
878 return getLhs();
879
880 // divui (x, x) -> 1.
881 if (getLhs() == getRhs())
882 return getIntegerAttrOfType(getType(), 1);
883
884 // (a * b) / b -> a
885 if (Value val = foldDivMul(getLhs(), getRhs(), IntegerOverflowFlags::nuw))
886 return val;
887
888 // Don't fold if it would require a division by zero.
889 bool div0 = false;
890 auto result = constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
891 [&](APInt a, const APInt &b) {
892 if (div0 || !b) {
893 div0 = true;
894 return a;
895 }
896 return a.udiv(b);
897 });
898
899 return div0 ? Attribute() : result;
900}
901
902/// Returns whether an unsigned division by `divisor` is speculatable.
904 // X / 0 => UB
905 if (matchPattern(divisor, m_IntRangeWithoutZeroU()))
907
909}
910
911Speculation::Speculatability arith::DivUIOp::getSpeculatability() {
912 return getDivUISpeculatability(getRhs());
913}
914
915//===----------------------------------------------------------------------===//
916// DivSIOp
917//===----------------------------------------------------------------------===//
918
919OpFoldResult arith::DivSIOp::fold(FoldAdaptor adaptor) {
920 // TODO: divsi (x, 0) -> poison. Division by zero is undefined behaviour and
921 // could fold to poison, but that would make the arith dialect depend on the
922 // ub dialect to materialize ub.poison; left out for now.
923
924 // divsi (x, 1) -> x.
925 if (matchPattern(adaptor.getRhs(), m_One()))
926 return getLhs();
927
928 // divsi (0, x) -> 0. Division by zero is UB, so refining to 0 is valid.
929 if (matchPattern(adaptor.getLhs(), m_Zero()))
930 return getLhs();
931
932 // divsi (x, x) -> 1.
933 if (getLhs() == getRhs())
934 return getIntegerAttrOfType(getType(), 1);
935
936 // (a * b) / b -> a
937 if (Value val = foldDivMul(getLhs(), getRhs(), IntegerOverflowFlags::nsw))
938 return val;
939
940 // Don't fold if it would overflow or if it requires a division by zero.
941 bool overflowOrDiv0 = false;
943 adaptor.getOperands(), [&](APInt a, const APInt &b) {
944 if (overflowOrDiv0 || !b) {
945 overflowOrDiv0 = true;
946 return a;
947 }
948 return a.sdiv_ov(b, overflowOrDiv0);
949 });
950
951 return overflowOrDiv0 ? Attribute() : result;
952}
953
954/// Returns whether a signed division by `divisor` is speculatable. This
955/// function conservatively assumes that all signed division by -1 are not
956/// speculatable.
958 // X / 0 => UB
959 // INT_MIN / -1 => UB
960 if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
963
965}
966
967Speculation::Speculatability arith::DivSIOp::getSpeculatability() {
968 return getDivSISpeculatability(getRhs());
969}
970
971//===----------------------------------------------------------------------===//
972// CeilDivUIOp
973//===----------------------------------------------------------------------===//
974
975OpFoldResult arith::CeilDivUIOp::fold(FoldAdaptor adaptor) {
976 // TODO: ceildivui (x, 0) -> poison. Division by zero is undefined behaviour
977 // and could fold to poison, but that would make the arith dialect depend on
978 // the ub dialect to materialize ub.poison; left out for now.
979
980 // ceildivui (x, 1) -> x.
981 if (matchPattern(adaptor.getRhs(), m_One()))
982 return getLhs();
983
984 // ceildivui (0, x) -> 0. Division by zero is UB, so refining to 0 is valid.
985 if (matchPattern(adaptor.getLhs(), m_Zero()))
986 return getLhs();
987
988 // ceildivui (x, x) -> 1.
989 if (getLhs() == getRhs())
990 return getIntegerAttrOfType(getType(), 1);
991
992 bool overflowOrDiv0 = false;
994 adaptor.getOperands(), [&](APInt a, const APInt &b) {
995 if (overflowOrDiv0 || !b) {
996 overflowOrDiv0 = true;
997 return a;
998 }
999 APInt quotient = a.udiv(b);
1000 if (!a.urem(b))
1001 return quotient;
1002 APInt one(a.getBitWidth(), 1, true);
1003 return quotient.uadd_ov(one, overflowOrDiv0);
1004 });
1005
1006 return overflowOrDiv0 ? Attribute() : result;
1007}
1008
1009Speculation::Speculatability arith::CeilDivUIOp::getSpeculatability() {
1010 return getDivUISpeculatability(getRhs());
1011}
1012
1013//===----------------------------------------------------------------------===//
1014// CeilDivSIOp
1015//===----------------------------------------------------------------------===//
1016
1017OpFoldResult arith::CeilDivSIOp::fold(FoldAdaptor adaptor) {
1018 // TODO: ceildivsi (x, 0) -> poison. Division by zero is undefined behaviour
1019 // and could fold to poison, but that would make the arith dialect depend on
1020 // the ub dialect to materialize ub.poison; left out for now.
1021
1022 // ceildivsi (x, 1) -> x.
1023 if (matchPattern(adaptor.getRhs(), m_One()))
1024 return getLhs();
1025
1026 // ceildivsi (0, x) -> 0. Division by zero is UB, so refining to 0 is valid.
1027 if (matchPattern(adaptor.getLhs(), m_Zero()))
1028 return getLhs();
1029
1030 // ceildivsi (x, x) -> 1.
1031 if (getLhs() == getRhs())
1032 return getIntegerAttrOfType(getType(), 1);
1033
1034 // Don't fold if it would overflow or if it requires a division by zero.
1035 bool overflowOrDiv0 = false;
1037 adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
1038 if (overflowOrDiv0 || !b) {
1039 overflowOrDiv0 = true;
1040 return a;
1041 }
1042 // Compute the ceiling without negating either operand, so that MININT
1043 // operands still fold whenever the result is representable.
1044 //
1045 // sdiv truncates towards zero, so it already rounds up whenever the
1046 // exact quotient is negative. When the exact quotient is positive, i.e.
1047 // when the operands have the same sign, an inexact division has to be
1048 // corrected by one. This mirrors the expansion in ExpandOps.cpp.
1049 bool overflowDiv = false;
1050 APInt quotient = a.sdiv_ov(b, overflowDiv);
1051 if (overflowDiv) {
1052 // MININT / -1. The exact result is -MININT, which is not
1053 // representable.
1054 overflowOrDiv0 = true;
1055 return a;
1056 }
1057 if (a.isNegative() != b.isNegative() || quotient * b == a)
1058 return quotient;
1059
1060 // The correction cannot overflow: it only applies when the exact
1061 // quotient is positive and the division is inexact, which bounds the
1062 // quotient well below the maximum. Check anyway, at no cost.
1063 APInt one(a.getBitWidth(), 1, /*isSigned=*/true);
1064 return quotient.sadd_ov(one, overflowOrDiv0);
1065 });
1066
1067 return overflowOrDiv0 ? Attribute() : result;
1068}
1069
1070Speculation::Speculatability arith::CeilDivSIOp::getSpeculatability() {
1071 return getDivSISpeculatability(getRhs());
1072}
1073
1074//===----------------------------------------------------------------------===//
1075// FloorDivSIOp
1076//===----------------------------------------------------------------------===//
1077
1078OpFoldResult arith::FloorDivSIOp::fold(FoldAdaptor adaptor) {
1079 // TODO: floordivsi (x, 0) -> poison. Division by zero is undefined behaviour
1080 // and could fold to poison, but that would make the arith dialect depend on
1081 // the ub dialect to materialize ub.poison; left out for now.
1082
1083 // floordivsi (x, 1) -> x.
1084 if (matchPattern(adaptor.getRhs(), m_One()))
1085 return getLhs();
1086
1087 // floordivsi (0, x) -> 0. Division by zero is UB, so refining to 0 is valid.
1088 if (matchPattern(adaptor.getLhs(), m_Zero()))
1089 return getLhs();
1090
1091 // floordivsi (x, x) -> 1.
1092 if (getLhs() == getRhs())
1093 return getIntegerAttrOfType(getType(), 1);
1094
1095 // Don't fold if it would overflow or if it requires a division by zero.
1096 bool overflowOrDiv = false;
1098 adaptor.getOperands(), [&](APInt a, const APInt &b) {
1099 if (b.isZero()) {
1100 overflowOrDiv = true;
1101 return a;
1102 }
1103 return a.sfloordiv_ov(b, overflowOrDiv);
1104 });
1105
1106 return overflowOrDiv ? Attribute() : result;
1107}
1108
1109Speculation::Speculatability FloorDivSIOp::getSpeculatability() {
1110 // Division by zero is UB.
1111 // Signed division overflow (INT_MIN / -1) is also UB.
1112 Value divisor = getRhs();
1113 if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
1116
1118}
1119
1120//===----------------------------------------------------------------------===//
1121// RemUIOp
1122//===----------------------------------------------------------------------===//
1123
1124OpFoldResult arith::RemUIOp::fold(FoldAdaptor adaptor) {
1125 // TODO: remui (x, 0) -> poison. Remainder by zero is undefined behaviour and
1126 // could fold to poison, but that would make the arith dialect depend on the
1127 // ub dialect to materialize ub.poison; left out for now.
1128
1129 // remui (x, 1) -> 0.
1130 if (matchPattern(adaptor.getRhs(), m_One()))
1131 return getIntegerAttrOfType(getType(), 0);
1132
1133 // remui (0, x) -> 0 and remui (x, x) -> 0. Division by zero is UB, so
1134 // refining to 0 is valid.
1135 if (matchPattern(adaptor.getLhs(), m_Zero()) || getLhs() == getRhs())
1136 return getIntegerAttrOfType(getType(), 0);
1137
1138 // Don't fold if it would require a division by zero.
1139 bool div0 = false;
1140 auto result = constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1141 [&](APInt a, const APInt &b) {
1142 if (div0 || b.isZero()) {
1143 div0 = true;
1144 return a;
1145 }
1146 return a.urem(b);
1147 });
1148
1149 return div0 ? Attribute() : result;
1150}
1151
1152Speculation::Speculatability arith::RemUIOp::getSpeculatability() {
1153 return getDivUISpeculatability(getRhs());
1154}
1155
1156//===----------------------------------------------------------------------===//
1157// RemSIOp
1158//===----------------------------------------------------------------------===//
1159
1160OpFoldResult arith::RemSIOp::fold(FoldAdaptor adaptor) {
1161 // TODO: remsi (x, 0) -> poison. Remainder by zero is undefined behaviour and
1162 // could fold to poison, but that would make the arith dialect depend on the
1163 // ub dialect to materialize ub.poison; left out for now.
1164
1165 // remsi (x, 1) -> 0.
1166 if (matchPattern(adaptor.getRhs(), m_One()))
1167 return getIntegerAttrOfType(getType(), 0);
1168
1169 // remsi (0, x) -> 0 and remsi (x, x) -> 0. Division by zero is UB, so
1170 // refining to 0 is valid.
1171 if (matchPattern(adaptor.getLhs(), m_Zero()) || getLhs() == getRhs())
1172 return getIntegerAttrOfType(getType(), 0);
1173
1174 // Don't fold if it would require a division by zero.
1175 bool div0 = false;
1176 auto result = constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1177 [&](APInt a, const APInt &b) {
1178 if (div0 || b.isZero()) {
1179 div0 = true;
1180 return a;
1181 }
1182 return a.srem(b);
1183 });
1184
1185 return div0 ? Attribute() : result;
1186}
1187
1188Speculation::Speculatability arith::RemSIOp::getSpeculatability() {
1189 // X % 0 => UB
1190 // X % -1 is well-defined (always 0), unlike X / -1 which can overflow.
1191 if (matchPattern(getRhs(), m_IntRangeWithoutZeroS()))
1193
1195}
1196
1197//===----------------------------------------------------------------------===//
1198// AndIOp
1199//===----------------------------------------------------------------------===//
1200
1201/// Fold `op(a, op(a, b))` to `op(a, b)` for an associative, commutative and
1202/// idempotent `op` (e.g. `and`, `or`).
1203template <typename OpTy>
1205 for (bool reversePrev : {false, true}) {
1206 auto prev = (reversePrev ? op.getRhs() : op.getLhs())
1207 .template getDefiningOp<OpTy>();
1208 if (!prev)
1209 continue;
1210
1211 Value other = (reversePrev ? op.getLhs() : op.getRhs());
1212 if (other != prev.getLhs() && other != prev.getRhs())
1213 continue;
1214
1215 return prev.getResult();
1216 }
1217 return {};
1218}
1219
1220OpFoldResult arith::AndIOp::fold(FoldAdaptor adaptor) {
1221 /// and(x, 0) -> 0
1222 if (matchPattern(adaptor.getRhs(), m_Zero()))
1223 return getRhs();
1224 /// and(x, allOnes) -> x
1225 APInt intValue;
1226 if (matchPattern(adaptor.getRhs(), m_ConstantInt(&intValue)) &&
1227 intValue.isAllOnes())
1228 return getLhs();
1229 /// and(x, not(x)) -> 0
1230 if (matchPattern(getRhs(), m_Op<XOrIOp>(matchers::m_Val(getLhs()),
1231 m_ConstantInt(&intValue))) &&
1232 intValue.isAllOnes())
1233 return Builder(getContext()).getZeroAttr(getType());
1234 /// and(not(x), x) -> 0
1235 if (matchPattern(getLhs(), m_Op<XOrIOp>(matchers::m_Val(getRhs()),
1236 m_ConstantInt(&intValue))) &&
1237 intValue.isAllOnes())
1238 return Builder(getContext()).getZeroAttr(getType());
1239
1240 /// and(a, and(a, b)) -> and(a, b)
1241 if (Value result = foldIdempotentOfSameOp(*this))
1242 return result;
1243
1245 adaptor.getOperands(),
1246 [](APInt a, const APInt &b) { return std::move(a) & b; });
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// OrIOp
1251//===----------------------------------------------------------------------===//
1252
1253OpFoldResult arith::OrIOp::fold(FoldAdaptor adaptor) {
1254 if (APInt rhsVal; matchPattern(adaptor.getRhs(), m_ConstantInt(&rhsVal))) {
1255 /// or(x, 0) -> x
1256 if (rhsVal.isZero())
1257 return getLhs();
1258 /// or(x, <all ones>) -> <all ones>
1259 if (rhsVal.isAllOnes())
1260 return adaptor.getRhs();
1261 }
1262
1263 APInt intValue;
1264 /// or(x, xor(x, 1)) -> 1
1265 if (matchPattern(getRhs(), m_Op<XOrIOp>(matchers::m_Val(getLhs()),
1266 m_ConstantInt(&intValue))) &&
1267 intValue.isAllOnes())
1268 return getRhs().getDefiningOp<XOrIOp>().getRhs();
1269 /// or(xor(x, 1), x) -> 1
1270 if (matchPattern(getLhs(), m_Op<XOrIOp>(matchers::m_Val(getRhs()),
1271 m_ConstantInt(&intValue))) &&
1272 intValue.isAllOnes())
1273 return getLhs().getDefiningOp<XOrIOp>().getRhs();
1274
1275 /// or(a, or(a, b)) -> or(a, b)
1276 if (Value result = foldIdempotentOfSameOp(*this))
1277 return result;
1278
1280 adaptor.getOperands(),
1281 [](APInt a, const APInt &b) { return std::move(a) | b; });
1282}
1283
1284//===----------------------------------------------------------------------===//
1285// XOrIOp
1286//===----------------------------------------------------------------------===//
1287
1288OpFoldResult arith::XOrIOp::fold(FoldAdaptor adaptor) {
1289 /// xor(x, 0) -> x
1290 if (matchPattern(adaptor.getRhs(), m_Zero()))
1291 return getLhs();
1292 /// xor(x, x) -> 0
1293 if (getLhs() == getRhs()) {
1294 // A dynamically-shaped result cannot be a constant; bail before
1295 // getZeroAttr, which would assert on a non-static shape.
1296 auto shapedType = dyn_cast<ShapedType>(getType());
1297 if (!shapedType || shapedType.hasStaticShape())
1298 return Builder(getContext()).getZeroAttr(getType());
1299 }
1300 /// xor(xor(x, a), a) -> x
1301 /// xor(xor(a, x), a) -> x
1302 if (arith::XOrIOp prev = getLhs().getDefiningOp<arith::XOrIOp>()) {
1303 if (prev.getRhs() == getRhs())
1304 return prev.getLhs();
1305 if (prev.getLhs() == getRhs())
1306 return prev.getRhs();
1307 }
1308 /// xor(a, xor(x, a)) -> x
1309 /// xor(a, xor(a, x)) -> x
1310 if (arith::XOrIOp prev = getRhs().getDefiningOp<arith::XOrIOp>()) {
1311 if (prev.getRhs() == getLhs())
1312 return prev.getLhs();
1313 if (prev.getLhs() == getLhs())
1314 return prev.getRhs();
1315 }
1316
1318 adaptor.getOperands(),
1319 [](APInt a, const APInt &b) { return std::move(a) ^ b; });
1320}
1321
1322void arith::XOrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1323 MLIRContext *context) {
1324 patterns.add<XOrIXOrIConstant, XOrINotCmpI, XOrIOfExtUI, XOrIOfExtSI>(
1325 context);
1326}
1327
1328//===----------------------------------------------------------------------===//
1329// NegFOp
1330//===----------------------------------------------------------------------===//
1331
1332OpFoldResult arith::NegFOp::fold(FoldAdaptor adaptor) {
1333 /// negf(negf(x)) -> x
1334 if (auto op = this->getOperand().getDefiningOp<arith::NegFOp>())
1335 return op.getOperand();
1337 adaptor.getOperands(), [](const APFloat &a) -> std::optional<APFloat> {
1338 if (!APFloat::semanticsHasSignedRepr(a.getSemantics()))
1339 return std::nullopt;
1340 return -a;
1341 });
1342}
1343
1344//===----------------------------------------------------------------------===//
1345// FlushDenormalsOp
1346//===----------------------------------------------------------------------===//
1347
1348OpFoldResult arith::FlushDenormalsOp::fold(FoldAdaptor adaptor) {
1349 // TODO: Fold flush_denormals if the floating-point type does not support
1350 // denormals. There is currently no API to query this information from
1351 // APFloat.
1352
1353 // flush_denormals(flush_denormals(x)) -> flush_denormals(x)
1354 if (auto op = this->getOperand().getDefiningOp<arith::FlushDenormalsOp>())
1355 return op.getResult();
1356
1357 // Constant-fold flush_denormals if the operand is a constant.
1359 adaptor.getOperands(), [](const APFloat &a) {
1360 if (a.isDenormal())
1361 return APFloat::getZero(a.getSemantics(), a.isNegative());
1362 return a;
1363 });
1364}
1365
1366//===----------------------------------------------------------------------===//
1367// AddFOp
1368//===----------------------------------------------------------------------===//
1369
1370OpFoldResult arith::AddFOp::fold(FoldAdaptor adaptor) {
1371 // addf(x, -0) -> x
1372 if (matchPattern(adaptor.getRhs(), m_NegZeroFloat()))
1373 return getLhs();
1374 if (matchPattern(adaptor.getRhs(), m_PosZeroFloat()) &&
1375 bitEnumContainsAll(adaptor.getFastmath(), FastMathFlags::nsz))
1376 return getLhs();
1377
1378 auto rm = getRoundingmode();
1380 adaptor.getOperands(), [rm](const APFloat &a, const APFloat &b) {
1381 APFloat result(a);
1382 result.add(b, convertArithRoundingModeToLLVMIR(rm));
1383 return result;
1384 });
1385}
1386
1387void arith::AddFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1388 MLIRContext *context) {
1389 patterns.add<AddFOfNegFLhs, AddFOfNegFRhs>(context);
1390}
1391
1392//===----------------------------------------------------------------------===//
1393// SubFOp
1394//===----------------------------------------------------------------------===//
1395
1396OpFoldResult arith::SubFOp::fold(FoldAdaptor adaptor) {
1397 // subf(x, +0) -> x
1398 if (matchPattern(adaptor.getRhs(), m_PosZeroFloat()))
1399 return getLhs();
1400 if (matchPattern(adaptor.getRhs(), m_NegZeroFloat()) &&
1401 bitEnumContainsAll(adaptor.getFastmath(), FastMathFlags::nsz))
1402 return getLhs();
1403
1404 auto rm = getRoundingmode();
1406 adaptor.getOperands(),
1407 [rm](const APFloat &a, const APFloat &b) -> std::optional<APFloat> {
1408 // A negative difference is not representable in types such as
1409 // f8E8M0FNU, and APFloat::subtract does not support computing it.
1410 if (!APFloat::semanticsHasSignedRepr(a.getSemantics()) &&
1411 a.compare(b) == APFloat::cmpLessThan)
1412 return std::nullopt;
1413 APFloat result(a);
1414 result.subtract(b, convertArithRoundingModeToLLVMIR(rm));
1415 return result;
1416 });
1417}
1418
1419void arith::SubFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1420 MLIRContext *context) {
1421 patterns.add<SubFOfNegZero>(context);
1422}
1423
1424namespace {
1425
1426/// Narrow an extremum whose operands were extended from the result type:
1427///
1428/// trunc(extremum(ext(lhs), ext(rhs))) -> extremum(lhs, rhs)
1429///
1430/// The concrete extension is part of the pattern so each extremum is only
1431/// registered with extensions that preserve its ordering.
1432/// For floating-point types, also require the extension to preserve every
1433/// source value relevant under the extremum's fast-math flags.
1434template <typename TruncOp, typename ExtOp, typename ExtremumOp>
1435struct NarrowExtremum final : OpRewritePattern<TruncOp> {
1436 using OpRewritePattern<TruncOp>::OpRewritePattern;
1437
1438 LogicalResult matchAndRewrite(TruncOp truncOp,
1439 PatternRewriter &rewriter) const override {
1440 auto extremumOp = truncOp.getIn().template getDefiningOp<ExtremumOp>();
1441 if (!extremumOp || !extremumOp->hasOneUse())
1442 return failure();
1443
1444 auto lhsExt = extremumOp.getLhs().template getDefiningOp<ExtOp>();
1445 auto rhsExt = extremumOp.getRhs().template getDefiningOp<ExtOp>();
1446 if (!lhsExt || !rhsExt)
1447 return failure();
1448
1449 Value lhs = lhsExt.getIn();
1450 Value rhs = rhsExt.getIn();
1451 Type narrowType = truncOp.getType();
1452 if (lhs.getType() != narrowType || rhs.getType() != narrowType)
1453 return failure();
1454
1455 // A floating-point extension is not necessarily lossless between arbitrary
1456 // floating-point semantics, even when the destination has a larger bit
1457 // width. In particular, it may lose the sign of zero or quiet a signaling
1458 // NaN, either of which can change an extremum's result. `nnan` lets us
1459 // disregard NaN representation differences, but all other relevant source
1460 // values must be preserved.
1461 if (auto narrowFloatType =
1462 dyn_cast<FloatType>(getElementTypeOrSelf(narrowType))) {
1463 auto wideFloatType =
1464 dyn_cast<FloatType>(getElementTypeOrSelf(extremumOp.getType()));
1465 if (!wideFloatType)
1466 return failure();
1467
1468 const llvm::fltSemantics &narrowSemantics =
1469 narrowFloatType.getFloatSemantics();
1470 const llvm::fltSemantics &wideSemantics =
1471 wideFloatType.getFloatSemantics();
1472 bool ignoreNaNs = false;
1473 if constexpr (std::is_same_v<TruncOp, TruncFOp>)
1474 ignoreNaNs =
1475 bitEnumContainsAll(extremumOp.getFastmath(), FastMathFlags::nnan);
1476 if (!llvm::APFloatBase::isLosslesslyConvertibleTo(
1477 narrowSemantics, wideSemantics, ignoreNaNs))
1478 return failure();
1479 }
1480
1481 rewriter.replaceOpWithNewOp<ExtremumOp>(
1482 truncOp, TypeRange{narrowType}, ValueRange{lhs, rhs},
1483 extremumOp.getProperties(),
1484 extremumOp->getDiscardableAttrDictionary().getValue());
1485 return success();
1486 }
1487};
1488
1489} // namespace
1490
1491//===----------------------------------------------------------------------===//
1492// MaximumFOp
1493//===----------------------------------------------------------------------===//
1494
1495OpFoldResult arith::MaximumFOp::fold(FoldAdaptor adaptor) {
1496 // maximumf(x,x) -> x
1497 if (getLhs() == getRhs())
1498 return getRhs();
1499
1500 // maximumf(x, -inf) -> x
1501 if (matchPattern(adaptor.getRhs(), m_NegInfFloat()))
1502 return getLhs();
1503
1504 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::maximum);
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// MaxNumFOp
1509//===----------------------------------------------------------------------===//
1510
1511OpFoldResult arith::MaxNumFOp::fold(FoldAdaptor adaptor) {
1512 // maxnumf(x,x) -> x
1513 if (getLhs() == getRhs())
1514 return getRhs();
1515
1516 // maxnumf(x, NaN) -> x
1517 if (matchPattern(adaptor.getRhs(), m_NaNFloat()))
1518 return getLhs();
1519
1520 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::maxnum);
1521}
1522
1523//===----------------------------------------------------------------------===//
1524// MaximumNumFOp
1525//===----------------------------------------------------------------------===//
1526
1527OpFoldResult arith::MaximumNumFOp::fold(FoldAdaptor adaptor) {
1528 // maximumnumf(x,x) -> x
1529 if (getLhs() == getRhs())
1530 return getRhs();
1531
1532 // maximumnumf(x, NaN) -> x
1533 if (matchPattern(adaptor.getRhs(), m_NaNFloat()))
1534 return getLhs();
1535
1536 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::maximumnum);
1537}
1538
1539//===----------------------------------------------------------------------===//
1540// MaxSIOp
1541//===----------------------------------------------------------------------===//
1542
1543OpFoldResult MaxSIOp::fold(FoldAdaptor adaptor) {
1544 // maxsi(x,x) -> x
1545 if (getLhs() == getRhs())
1546 return getRhs();
1547
1548 if (APInt intValue;
1549 matchPattern(adaptor.getRhs(), m_ConstantInt(&intValue))) {
1550 // maxsi(x,MAX_INT) -> MAX_INT
1551 if (intValue.isMaxSignedValue())
1552 return getRhs();
1553 // maxsi(x, MIN_INT) -> x
1554 if (intValue.isMinSignedValue())
1555 return getLhs();
1556 }
1557
1558 return constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1559 llvm::APIntOps::smax);
1560}
1561
1562//===----------------------------------------------------------------------===//
1563// MaxUIOp
1564//===----------------------------------------------------------------------===//
1565
1566OpFoldResult MaxUIOp::fold(FoldAdaptor adaptor) {
1567 // maxui(x,x) -> x
1568 if (getLhs() == getRhs())
1569 return getRhs();
1570
1571 if (APInt intValue;
1572 matchPattern(adaptor.getRhs(), m_ConstantInt(&intValue))) {
1573 // maxui(x,MAX_INT) -> MAX_INT
1574 if (intValue.isMaxValue())
1575 return getRhs();
1576 // maxui(x, MIN_INT) -> x
1577 if (intValue.isMinValue())
1578 return getLhs();
1579 }
1580
1581 return constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1582 llvm::APIntOps::umax);
1583}
1584
1585//===----------------------------------------------------------------------===//
1586// MinimumFOp
1587//===----------------------------------------------------------------------===//
1588
1589OpFoldResult arith::MinimumFOp::fold(FoldAdaptor adaptor) {
1590 // minimumf(x,x) -> x
1591 if (getLhs() == getRhs())
1592 return getRhs();
1593
1594 // minimumf(x, +inf) -> x
1595 if (matchPattern(adaptor.getRhs(), m_PosInfFloat()))
1596 return getLhs();
1597
1598 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::minimum);
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// MinNumFOp
1603//===----------------------------------------------------------------------===//
1604
1605OpFoldResult arith::MinNumFOp::fold(FoldAdaptor adaptor) {
1606 // minnumf(x,x) -> x
1607 if (getLhs() == getRhs())
1608 return getRhs();
1609
1610 // minnumf(x, NaN) -> x
1611 if (matchPattern(adaptor.getRhs(), m_NaNFloat()))
1612 return getLhs();
1613
1614 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::minnum);
1615}
1616
1617//===----------------------------------------------------------------------===//
1618// MinimumNumFOp
1619//===----------------------------------------------------------------------===//
1620
1621OpFoldResult arith::MinimumNumFOp::fold(FoldAdaptor adaptor) {
1622 // minimumnumf(x,x) -> x
1623 if (getLhs() == getRhs())
1624 return getRhs();
1625
1626 // minimumnumf(x, NaN) -> x
1627 if (matchPattern(adaptor.getRhs(), m_NaNFloat()))
1628 return getLhs();
1629
1630 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(), llvm::minimumnum);
1631}
1632
1633//===----------------------------------------------------------------------===//
1634// MinSIOp
1635//===----------------------------------------------------------------------===//
1636
1637OpFoldResult MinSIOp::fold(FoldAdaptor adaptor) {
1638 // minsi(x,x) -> x
1639 if (getLhs() == getRhs())
1640 return getRhs();
1641
1642 if (APInt intValue;
1643 matchPattern(adaptor.getRhs(), m_ConstantInt(&intValue))) {
1644 // minsi(x,MIN_INT) -> MIN_INT
1645 if (intValue.isMinSignedValue())
1646 return getRhs();
1647 // minsi(x, MAX_INT) -> x
1648 if (intValue.isMaxSignedValue())
1649 return getLhs();
1650 }
1651
1652 return constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1653 llvm::APIntOps::smin);
1654}
1655
1656//===----------------------------------------------------------------------===//
1657// MinUIOp
1658//===----------------------------------------------------------------------===//
1659
1660OpFoldResult MinUIOp::fold(FoldAdaptor adaptor) {
1661 // minui(x,x) -> x
1662 if (getLhs() == getRhs())
1663 return getRhs();
1664
1665 if (APInt intValue;
1666 matchPattern(adaptor.getRhs(), m_ConstantInt(&intValue))) {
1667 // minui(x,MIN_INT) -> MIN_INT
1668 if (intValue.isMinValue())
1669 return getRhs();
1670 // minui(x, MAX_INT) -> x
1671 if (intValue.isMaxValue())
1672 return getLhs();
1673 }
1674
1675 return constFoldBinaryOp<IntegerAttr>(adaptor.getOperands(),
1676 llvm::APIntOps::umin);
1677}
1678
1679//===----------------------------------------------------------------------===//
1680// MulFOp
1681//===----------------------------------------------------------------------===//
1682
1683OpFoldResult arith::MulFOp::fold(FoldAdaptor adaptor) {
1684 // mulf(x, 1) -> x
1685 if (matchPattern(adaptor.getRhs(), m_OneFloat()))
1686 return getLhs();
1687
1688 // Match LLVM InstSimplify: with nnan+nsz, X * 0 -> 0 for a non-constant X.
1689 // When both operands are constants, fall through to APFloat so IEEE signed
1690 // zeros are preserved (e.g. (-c) * +0.0 == -0.0).
1691 if (arith::bitEnumContainsAll(getFastmath(), arith::FastMathFlags::nnan |
1692 arith::FastMathFlags::nsz) &&
1693 !(adaptor.getLhs() && adaptor.getRhs())) {
1694 // mulf(x, 0) -> 0
1695 if (matchPattern(adaptor.getRhs(), m_AnyZeroFloat()))
1696 return getRhs();
1697 if (matchPattern(adaptor.getLhs(), m_AnyZeroFloat()))
1698 return getLhs();
1699 }
1700
1701 auto rm = getRoundingmode();
1703 adaptor.getOperands(), [rm](const APFloat &a, const APFloat &b) {
1704 APFloat result(a);
1705 result.multiply(b, convertArithRoundingModeToLLVMIR(rm));
1706 return result;
1707 });
1708}
1709
1710void arith::MulFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1711 MLIRContext *context) {
1712 patterns.add<MulFOfNegF>(context);
1713}
1714
1715//===----------------------------------------------------------------------===//
1716// DivFOp
1717//===----------------------------------------------------------------------===//
1718
1719OpFoldResult arith::DivFOp::fold(FoldAdaptor adaptor) {
1720 // divf(x, 1) -> x
1721 if (matchPattern(adaptor.getRhs(), m_OneFloat()))
1722 return getLhs();
1723
1724 auto rm = getRoundingmode();
1726 adaptor.getOperands(), [rm](const APFloat &a, const APFloat &b) {
1727 APFloat result(a);
1728 result.divide(b, convertArithRoundingModeToLLVMIR(rm));
1729 return result;
1730 });
1731}
1732
1733void arith::DivFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1734 MLIRContext *context) {
1735 patterns.add<DivFOfNegF>(context);
1736}
1737
1738//===----------------------------------------------------------------------===//
1739// RemFOp
1740//===----------------------------------------------------------------------===//
1741
1742OpFoldResult arith::RemFOp::fold(FoldAdaptor adaptor) {
1743 return constFoldBinaryOp<FloatAttr>(adaptor.getOperands(),
1744 [](const APFloat &a, const APFloat &b) {
1745 APFloat result(a);
1746 // APFloat::mod() offers the remainder
1747 // behavior we want, i.e. the result has
1748 // the sign of LHS operand.
1749 (void)result.mod(b);
1750 return result;
1751 });
1752}
1753
1754//===----------------------------------------------------------------------===//
1755// Utility functions for verifying cast ops
1756//===----------------------------------------------------------------------===//
1757
1758template <typename... Types>
1759using type_list = std::tuple<Types...> *;
1760
1761/// Returns a non-null type only if the provided type is one of the allowed
1762/// types or one of the allowed shaped types of the allowed types. Returns the
1763/// element type if a valid shaped type is provided.
1764template <typename... ShapedTypes, typename... ElementTypes>
1767 if (llvm::isa<ShapedType>(type) && !llvm::isa<ShapedTypes...>(type))
1768 return {};
1769
1770 auto underlyingType = getElementTypeOrSelf(type);
1771 if (!llvm::isa<ElementTypes...>(underlyingType))
1772 return {};
1773
1774 return underlyingType;
1775}
1776
1777/// Get allowed underlying types for vectors and tensors.
1778template <typename... ElementTypes>
1783
1784/// Get allowed underlying types for vectors, tensors, and memrefs.
1785template <typename... ElementTypes>
1791
1792/// Return false if both types are ranked tensor with mismatching encoding.
1793static bool hasSameEncoding(Type typeA, Type typeB) {
1794 auto rankedTensorA = dyn_cast<RankedTensorType>(typeA);
1795 auto rankedTensorB = dyn_cast<RankedTensorType>(typeB);
1796 if (!rankedTensorA || !rankedTensorB)
1797 return true;
1798 return rankedTensorA.getEncoding() == rankedTensorB.getEncoding();
1799}
1800
1802 if (inputs.size() != 1 || outputs.size() != 1)
1803 return false;
1804 if (!hasSameEncoding(inputs.front(), outputs.front()))
1805 return false;
1806 return succeeded(verifyCompatibleShapes(inputs.front(), outputs.front()));
1807}
1808
1809//===----------------------------------------------------------------------===//
1810// Verifiers for integer and floating point extension/truncation ops
1811//===----------------------------------------------------------------------===//
1812
1813// Extend ops can only extend to a wider type.
1814template <typename ValType, typename Op>
1815static LogicalResult verifyExtOp(Op op) {
1816 Type srcType = getElementTypeOrSelf(op.getIn().getType());
1817 Type dstType = getElementTypeOrSelf(op.getType());
1818
1819 if (llvm::cast<ValType>(srcType).getWidth() >=
1820 llvm::cast<ValType>(dstType).getWidth())
1821 return op.emitError("result type ")
1822 << dstType << " must be wider than operand type " << srcType;
1823
1824 return success();
1825}
1826
1827// Truncate ops can only truncate to a shorter type.
1828template <typename ValType, typename Op>
1829static LogicalResult verifyTruncateOp(Op op) {
1830 Type srcType = getElementTypeOrSelf(op.getIn().getType());
1831 Type dstType = getElementTypeOrSelf(op.getType());
1832
1833 if (llvm::cast<ValType>(srcType).getWidth() <=
1834 llvm::cast<ValType>(dstType).getWidth())
1835 return op.emitError("result type ")
1836 << dstType << " must be shorter than operand type " << srcType;
1837
1838 return success();
1839}
1840
1841/// Validate a cast that changes the width of a type.
1842template <template <typename> class WidthComparator, typename... ElementTypes>
1843static bool checkWidthChangeCast(TypeRange inputs, TypeRange outputs) {
1844 if (!areValidCastInputsAndOutputs(inputs, outputs))
1845 return false;
1846
1847 auto srcType = getTypeIfLike<ElementTypes...>(inputs.front());
1848 auto dstType = getTypeIfLike<ElementTypes...>(outputs.front());
1849 if (!srcType || !dstType)
1850 return false;
1851
1852 return WidthComparator<unsigned>()(dstType.getIntOrFloatBitWidth(),
1853 srcType.getIntOrFloatBitWidth());
1854}
1855
1856/// Attempts to convert `sourceValue` to an APFloat value with
1857/// `targetSemantics` and `roundingMode`, without any information loss.
1858static FailureOr<APFloat>
1859convertFloatValue(APFloat sourceValue,
1860 const llvm::fltSemantics &targetSemantics,
1861 llvm::RoundingMode roundingMode = kDefaultRoundingMode) {
1862 // Reject special values that are not representable in the target type before
1863 // calling APFloat::convert, which would llvm_unreachable on them.
1864 using fltNonfiniteBehavior = llvm::fltNonfiniteBehavior;
1865 if (sourceValue.isInfinity() &&
1866 (targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
1867 targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly))
1868 return failure();
1869 if (sourceValue.isNaN() &&
1870 targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
1871 return failure();
1872 // A format without a sign (e.g. f8E8M0FNU) has no negative values, and
1873 // APFloat::convert reaches llvm_unreachable on a negative NaN or overflow.
1874 if (sourceValue.isNegative() &&
1875 !APFloat::semanticsHasSignedRepr(targetSemantics))
1876 return failure();
1877
1878 bool losesInfo = false;
1879 auto status = sourceValue.convert(targetSemantics, roundingMode, &losesInfo);
1880 if (losesInfo || status != APFloat::opOK)
1881 return failure();
1882
1883 return sourceValue;
1884}
1885
1886//===----------------------------------------------------------------------===//
1887// ExtUIOp
1888//===----------------------------------------------------------------------===//
1889
1890OpFoldResult arith::ExtUIOp::fold(FoldAdaptor adaptor) {
1891 if (auto lhs = getIn().getDefiningOp<ExtUIOp>()) {
1892 // Only the inner extension's nneg speaks about the surviving source; the
1893 // outer flag described the already-extended value.
1894 setNonNeg(lhs.getNonNeg());
1895 getInMutable().assign(lhs.getIn());
1896 return getResult();
1897 }
1898
1899 Type resType = getElementTypeOrSelf(getType());
1900 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
1902 adaptor.getOperands(), getType(),
1903 [bitWidth](const APInt &a, bool &castStatus) {
1904 return a.zext(bitWidth);
1905 });
1906}
1907
1908bool arith::ExtUIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
1910}
1911
1912LogicalResult arith::ExtUIOp::verify() {
1913 return verifyExtOp<IntegerType>(*this);
1914}
1915
1916//===----------------------------------------------------------------------===//
1917// ExtSIOp
1918//===----------------------------------------------------------------------===//
1919
1920OpFoldResult arith::ExtSIOp::fold(FoldAdaptor adaptor) {
1921 if (auto lhs = getIn().getDefiningOp<ExtSIOp>()) {
1922 getInMutable().assign(lhs.getIn());
1923 return getResult();
1924 }
1925
1926 Type resType = getElementTypeOrSelf(getType());
1927 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
1929 adaptor.getOperands(), getType(),
1930 [bitWidth](const APInt &a, bool &castStatus) {
1931 return a.sext(bitWidth);
1932 });
1933}
1934
1935bool arith::ExtSIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
1937}
1938
1939void arith::ExtSIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1940 MLIRContext *context) {
1941 patterns.add<ExtSIOfExtUI>(context);
1942}
1943
1944LogicalResult arith::ExtSIOp::verify() {
1945 return verifyExtOp<IntegerType>(*this);
1946}
1947
1948//===----------------------------------------------------------------------===//
1949// ExtFOp
1950//===----------------------------------------------------------------------===//
1951
1952/// Fold extension of float constants when there is no information loss due the
1953/// difference in fp semantics.
1954OpFoldResult arith::ExtFOp::fold(FoldAdaptor adaptor) {
1955 if (auto truncFOp = getOperand().getDefiningOp<TruncFOp>()) {
1956 if (truncFOp.getOperand().getType() == getType()) {
1957 arith::FastMathFlags truncFMF =
1958 truncFOp.getFastmath().value_or(arith::FastMathFlags::none);
1959 bool isTruncContract =
1960 bitEnumContainsAll(truncFMF, arith::FastMathFlags::contract);
1961 arith::FastMathFlags extFMF =
1962 getFastmath().value_or(arith::FastMathFlags::none);
1963 bool isExtContract =
1964 bitEnumContainsAll(extFMF, arith::FastMathFlags::contract);
1965 if (isTruncContract && isExtContract) {
1966 return truncFOp.getOperand();
1967 }
1968 }
1969 }
1970
1971 auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
1972 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
1974 adaptor.getOperands(), getType(),
1975 [&targetSemantics](const APFloat &a, bool &castStatus) {
1976 FailureOr<APFloat> result = convertFloatValue(a, targetSemantics);
1977 if (failed(result)) {
1978 castStatus = false;
1979 return a;
1980 }
1981 return *result;
1982 });
1983}
1984
1985bool arith::ExtFOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
1986 return checkWidthChangeCast<std::greater, FloatType>(inputs, outputs);
1987}
1988
1989LogicalResult arith::ExtFOp::verify() { return verifyExtOp<FloatType>(*this); }
1990
1991//===----------------------------------------------------------------------===//
1992// ScalingExtFOp
1993//===----------------------------------------------------------------------===//
1994
1995/// Fold `calculate` element-wise over the operands of a scaling cast op. The
1996/// `constFoldBinaryOp` helpers cannot be used: they bail out unless both
1997/// operands have the same type, and `in` and `scale` never do.
1999 Attribute inAttr, Attribute scaleAttr, Type resultType,
2000 function_ref<std::optional<APFloat>(const APFloat &, const APFloat &)>
2001 calculate) {
2002 // Poison propagates, as it does in the generic constant folders.
2003 if (isa_and_nonnull<ub::PoisonAttr>(inAttr))
2004 return inAttr;
2005 if (isa_and_nonnull<ub::PoisonAttr>(scaleAttr))
2006 return scaleAttr;
2007
2008 if (!inAttr || !scaleAttr || !resultType)
2009 return {};
2010
2011 if (auto inFloat = dyn_cast<FloatAttr>(inAttr)) {
2012 auto scaleFloat = dyn_cast<FloatAttr>(scaleAttr);
2013 if (!scaleFloat)
2014 return {};
2015 std::optional<APFloat> result =
2016 calculate(inFloat.getValue(), scaleFloat.getValue());
2017 if (!result)
2018 return {};
2019 return FloatAttr::get(resultType, *result);
2020 }
2021
2022 auto inElements = dyn_cast<DenseFPElementsAttr>(inAttr);
2023 auto scaleElements = dyn_cast<DenseFPElementsAttr>(scaleAttr);
2024 auto shapedResultType = dyn_cast<ShapedType>(resultType);
2025 if (!inElements || !scaleElements || !shapedResultType ||
2026 !shapedResultType.hasStaticShape() ||
2027 inElements.getNumElements() != scaleElements.getNumElements())
2028 return {};
2029
2030 // Both operands are splats, so avoid expanding the elements out.
2031 if (inElements.isSplat() && scaleElements.isSplat()) {
2032 std::optional<APFloat> result =
2033 calculate(inElements.getSplatValue<APFloat>(),
2034 scaleElements.getSplatValue<APFloat>());
2035 if (!result)
2036 return {};
2037 return DenseElementsAttr::get(shapedResultType, *result);
2038 }
2039
2040 SmallVector<APFloat> results;
2041 results.reserve(inElements.getNumElements());
2042 for (const auto &[in, scale] : llvm::zip_equal(inElements, scaleElements)) {
2043 std::optional<APFloat> result = calculate(in, scale);
2044 if (!result)
2045 return {};
2046 results.push_back(*result);
2047 }
2048 return DenseElementsAttr::get(shapedResultType, results);
2049}
2050
2051/// Only scales that already are f8E8M0FNU fold. What a wider scale means is
2052/// unsettled -- the tree does not say whether truncating one to f8E8M0FNU
2053/// rounds or takes its exponent -- so a folder should not settle it, see
2054/// https://github.com/llvm/llvm-project/issues/215295.
2055static bool isFoldableScalingScale(Value scale) {
2056 return isa<Float8E8M0FNUType>(getElementTypeOrSelf(scale.getType()));
2057}
2058
2059OpFoldResult arith::ScalingExtFOp::fold(FoldAdaptor adaptor) {
2060 // scaling_extf(in, scale) -> mulf(extf(in), extf(scale)), matching the
2061 // expansion in ExpandOps.cpp. As in arith.extf, the widening steps only fold
2062 // when they are lossless.
2063 if (!isFoldableScalingScale(getScale()))
2064 return {};
2065
2066 auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
2067 const llvm::fltSemantics &resSemantics = resElemType.getFloatSemantics();
2068 return foldScalingCastOp(
2069 adaptor.getIn(), adaptor.getScale(), getType(),
2070 [&resSemantics](const APFloat &in,
2071 const APFloat &scale) -> std::optional<APFloat> {
2072 FailureOr<APFloat> inExt = convertFloatValue(in, resSemantics);
2073 FailureOr<APFloat> scaleExt = convertFloatValue(scale, resSemantics);
2074 if (failed(inExt) || failed(scaleExt))
2075 return std::nullopt;
2076 APFloat result(*inExt);
2077 result.multiply(*scaleExt, kDefaultRoundingMode);
2078 return result;
2079 });
2080}
2081
2082bool arith::ScalingExtFOp::areCastCompatible(TypeRange inputs,
2083 TypeRange outputs) {
2084 return checkWidthChangeCast<std::greater, FloatType>(inputs.front(), outputs);
2085}
2086
2087LogicalResult arith::ScalingExtFOp::verify() {
2088 return verifyExtOp<FloatType>(*this);
2089}
2090
2091//===----------------------------------------------------------------------===//
2092// TruncIOp
2093//===----------------------------------------------------------------------===//
2094
2095OpFoldResult arith::TruncIOp::fold(FoldAdaptor adaptor) {
2096 if (matchPattern(getOperand(), m_Op<arith::ExtUIOp>()) ||
2097 matchPattern(getOperand(), m_Op<arith::ExtSIOp>())) {
2098 Value src = getOperand().getDefiningOp()->getOperand(0);
2099 Type srcType = getElementTypeOrSelf(src.getType());
2100 Type dstType = getElementTypeOrSelf(getType());
2101 // trunci(zexti(a)) -> trunci(a)
2102 // trunci(sexti(a)) -> trunci(a)
2103 if (llvm::cast<IntegerType>(srcType).getWidth() >
2104 llvm::cast<IntegerType>(dstType).getWidth()) {
2105 setOperand(src);
2106 return getResult();
2107 }
2108
2109 // trunci(zexti(a)) -> a
2110 // trunci(sexti(a)) -> a
2111 if (srcType == dstType)
2112 return src;
2113 }
2114
2115 // trunci(trunci(a)) -> trunci(a)
2116 if (auto truncOp = getOperand().getDefiningOp<arith::TruncIOp>()) {
2117 // Preserve a flag only if both truncations are lossless in that signedness.
2118 setOverflowFlags(getOverflowFlags() & truncOp.getOverflowFlags());
2119 setOperand(truncOp.getIn());
2120 return getResult();
2121 }
2122
2123 Type resType = getElementTypeOrSelf(getType());
2124 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2126 adaptor.getOperands(), getType(),
2127 [bitWidth](const APInt &a, bool &castStatus) {
2128 return a.trunc(bitWidth);
2129 });
2130}
2131
2132bool arith::TruncIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2133 return checkWidthChangeCast<std::less, IntegerType>(inputs, outputs);
2134}
2135
2136void arith::TruncIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2137 MLIRContext *context) {
2138 patterns.add<NarrowExtremum<TruncIOp, ExtSIOp, MaxSIOp>,
2139 NarrowExtremum<TruncIOp, ExtSIOp, MinSIOp>,
2140 NarrowExtremum<TruncIOp, ExtUIOp, MaxUIOp>,
2141 NarrowExtremum<TruncIOp, ExtUIOp, MinUIOp>, TruncIExtSIToExtSI,
2142 TruncIExtUIToExtUI, TruncIShrSIToTrunciShrUI>(context);
2143}
2144
2145LogicalResult arith::TruncIOp::verify() {
2146 return verifyTruncateOp<IntegerType>(*this);
2147}
2148
2149//===----------------------------------------------------------------------===//
2150// TruncFOp
2151//===----------------------------------------------------------------------===//
2152
2153/// Perform safe const propagation for truncf, i.e., only propagate if FP value
2154/// can be represented without precision loss.
2155OpFoldResult arith::TruncFOp::fold(FoldAdaptor adaptor) {
2156 auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
2157 if (auto extOp = getOperand().getDefiningOp<arith::ExtFOp>()) {
2158 Value src = extOp.getIn();
2159 auto srcType = cast<FloatType>(getElementTypeOrSelf(src.getType()));
2160 auto intermediateType =
2161 cast<FloatType>(getElementTypeOrSelf(extOp.getType()));
2162 // Check whether every source value round-trips through the intermediate
2163 // type, including signaling NaNs and signed zero.
2164 if (llvm::APFloatBase::isLosslesslyConvertibleTo(
2165 srcType.getFloatSemantics(),
2166 intermediateType.getFloatSemantics())) {
2167 // truncf(extf(a)) -> truncf(a)
2168 if (srcType.getWidth() > resElemType.getWidth()) {
2169 setOperand(src);
2170 return getResult();
2171 }
2172
2173 // truncf(extf(a)) -> a
2174 if (srcType == resElemType)
2175 return src;
2176 }
2177 }
2178
2179 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
2181 adaptor.getOperands(), getType(),
2182 [this, &targetSemantics](const APFloat &a, bool &castStatus) {
2183 llvm::RoundingMode llvmRoundingMode =
2184 convertArithRoundingModeToLLVMIR(getRoundingmode());
2185 FailureOr<APFloat> result =
2186 convertFloatValue(a, targetSemantics, llvmRoundingMode);
2187 if (failed(result)) {
2188 castStatus = false;
2189 return a;
2190 }
2191 return *result;
2192 });
2193}
2194
2195void arith::TruncFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2196 MLIRContext *context) {
2197 patterns.add<NarrowExtremum<TruncFOp, ExtFOp, MaximumFOp>,
2198 NarrowExtremum<TruncFOp, ExtFOp, MaxNumFOp>,
2199 NarrowExtremum<TruncFOp, ExtFOp, MaximumNumFOp>,
2200 NarrowExtremum<TruncFOp, ExtFOp, MinimumFOp>,
2201 NarrowExtremum<TruncFOp, ExtFOp, MinNumFOp>,
2202 NarrowExtremum<TruncFOp, ExtFOp, MinimumNumFOp>,
2203 TruncFSIToFPToSIToFP, TruncFUIToFPToUIToFP>(context);
2204}
2205
2206bool arith::TruncFOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2207 return checkWidthChangeCast<std::less, FloatType>(inputs, outputs);
2208}
2209
2210LogicalResult arith::TruncFOp::verify() {
2211 return verifyTruncateOp<FloatType>(*this);
2212}
2213
2214//===----------------------------------------------------------------------===//
2215// ConvertFOp
2216//===----------------------------------------------------------------------===//
2217
2218OpFoldResult arith::ConvertFOp::fold(FoldAdaptor adaptor) {
2219 auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
2220 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
2222 adaptor.getOperands(), getType(),
2223 [this, &targetSemantics](const APFloat &a, bool &castStatus) {
2224 llvm::RoundingMode llvmRoundingMode =
2225 convertArithRoundingModeToLLVMIR(getRoundingmode());
2226 FailureOr<APFloat> result =
2227 convertFloatValue(a, targetSemantics, llvmRoundingMode);
2228 if (failed(result)) {
2229 castStatus = false;
2230 return a;
2231 }
2232 return *result;
2233 });
2234}
2235
2236bool arith::ConvertFOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2237 if (!areValidCastInputsAndOutputs(inputs, outputs))
2238 return false;
2239 auto srcType = getTypeIfLike<FloatType>(inputs.front());
2240 auto dstType = getTypeIfLike<FloatType>(outputs.front());
2241 if (!srcType || !dstType)
2242 return false;
2243 return srcType != dstType &&
2244 srcType.getIntOrFloatBitWidth() == dstType.getIntOrFloatBitWidth();
2245}
2246
2247LogicalResult arith::ConvertFOp::verify() {
2248 auto srcType = cast<FloatType>(getElementTypeOrSelf(getIn().getType()));
2249 auto dstType = cast<FloatType>(getElementTypeOrSelf(getType()));
2250 if (srcType == dstType)
2251 return emitError("result element type ")
2252 << dstType << " must be different from operand element type "
2253 << srcType;
2254 if (srcType.getWidth() != dstType.getWidth())
2255 return emitError("result element type ")
2256 << dstType << " must have the same bitwidth as operand element type "
2257 << srcType;
2258 return success();
2259}
2260
2261//===----------------------------------------------------------------------===//
2262// ScalingTruncFOp
2263//===----------------------------------------------------------------------===//
2264
2265OpFoldResult arith::ScalingTruncFOp::fold(FoldAdaptor adaptor) {
2266 // scaling_truncf(in, scale) -> truncf(in / extf(scale)), matching the
2267 // expansion in ExpandOps.cpp. Unlike scaling_extf, the scale is widened to
2268 // the type of `in` rather than to the result type.
2269 if (!isFoldableScalingScale(getScale()))
2270 return {};
2271
2272 auto inElemType = cast<FloatType>(getElementTypeOrSelf(getIn().getType()));
2273 auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
2274 const llvm::fltSemantics &inSemantics = inElemType.getFloatSemantics();
2275 const llvm::fltSemantics &resSemantics = resElemType.getFloatSemantics();
2276 llvm::RoundingMode roundingMode =
2277 convertArithRoundingModeToLLVMIR(getRoundingmode());
2278 return foldScalingCastOp(
2279 adaptor.getIn(), adaptor.getScale(), getType(),
2280 [&](const APFloat &in, const APFloat &scale) -> std::optional<APFloat> {
2281 FailureOr<APFloat> scaleExt = convertFloatValue(scale, inSemantics);
2282 if (failed(scaleExt))
2283 return std::nullopt;
2284 APFloat quotient(in);
2285 quotient.divide(*scaleExt, kDefaultRoundingMode);
2286 FailureOr<APFloat> result =
2287 convertFloatValue(quotient, resSemantics, roundingMode);
2288 if (failed(result))
2289 return std::nullopt;
2290 return *result;
2291 });
2292}
2293
2294bool arith::ScalingTruncFOp::areCastCompatible(TypeRange inputs,
2295 TypeRange outputs) {
2296 return checkWidthChangeCast<std::less, FloatType>(inputs.front(), outputs);
2297}
2298
2299LogicalResult arith::ScalingTruncFOp::verify() {
2300 return verifyTruncateOp<FloatType>(*this);
2301}
2302
2303//===----------------------------------------------------------------------===//
2304// AndIOp
2305//===----------------------------------------------------------------------===//
2306
2307void arith::AndIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2308 MLIRContext *context) {
2309 patterns.add<AndIAndIConstant, AndOfExtUI, AndOfExtSI>(context);
2310}
2311
2312//===----------------------------------------------------------------------===//
2313// OrIOp
2314//===----------------------------------------------------------------------===//
2315
2316void arith::OrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2317 MLIRContext *context) {
2318 patterns.add<OrIOrIConstant, OrOfExtUI, OrOfExtSI>(context);
2319}
2320
2321//===----------------------------------------------------------------------===//
2322// Verifiers for casts between integers and floats.
2323//===----------------------------------------------------------------------===//
2324
2325template <typename From, typename To>
2326static bool checkIntFloatCast(TypeRange inputs, TypeRange outputs) {
2327 if (!areValidCastInputsAndOutputs(inputs, outputs))
2328 return false;
2329
2330 auto srcType = getTypeIfLike<From>(inputs.front());
2331 auto dstType = getTypeIfLike<To>(outputs.back());
2332
2333 return srcType && dstType;
2334}
2335
2336//===----------------------------------------------------------------------===//
2337// UIToFPOp
2338//===----------------------------------------------------------------------===//
2339
2340bool arith::UIToFPOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2341 return checkIntFloatCast<IntegerType, FloatType>(inputs, outputs);
2342}
2343
2344OpFoldResult arith::UIToFPOp::fold(FoldAdaptor adaptor) {
2345 Type resEleType = getElementTypeOrSelf(getType());
2347 adaptor.getOperands(), getType(),
2348 [&resEleType](const APInt &a, bool &castStatus) {
2349 FloatType floatTy = llvm::cast<FloatType>(resEleType);
2350 APFloat apf(floatTy.getFloatSemantics(),
2351 APInt::getZero(floatTy.getWidth()));
2352 apf.convertFromAPInt(a, /*IsSigned=*/false,
2353 APFloat::rmNearestTiesToEven);
2354 return apf;
2355 });
2356}
2357
2358void arith::UIToFPOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2359 MLIRContext *context) {
2360 patterns.add<UIToFPOfExtUI>(context);
2361}
2362
2363//===----------------------------------------------------------------------===//
2364// SIToFPOp
2365//===----------------------------------------------------------------------===//
2366
2367bool arith::SIToFPOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2368 return checkIntFloatCast<IntegerType, FloatType>(inputs, outputs);
2369}
2370
2371OpFoldResult arith::SIToFPOp::fold(FoldAdaptor adaptor) {
2372 Type resEleType = getElementTypeOrSelf(getType());
2374 adaptor.getOperands(), getType(),
2375 [&resEleType](const APInt &a, bool &castStatus) {
2376 FloatType floatTy = llvm::cast<FloatType>(resEleType);
2377 APFloat apf(floatTy.getFloatSemantics(),
2378 APInt::getZero(floatTy.getWidth()));
2379 if (a.isNegative() &&
2380 !APFloat::semanticsHasSignedRepr(floatTy.getFloatSemantics())) {
2381 castStatus = false;
2382 return apf;
2383 }
2384 apf.convertFromAPInt(a, /*IsSigned=*/true,
2385 APFloat::rmNearestTiesToEven);
2386 return apf;
2387 });
2388}
2389
2390void arith::SIToFPOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2391 MLIRContext *context) {
2392 patterns.add<SIToFPOfExtSI, SIToFPOfExtUI>(context);
2393}
2394
2395//===----------------------------------------------------------------------===//
2396// FPToUIOp
2397//===----------------------------------------------------------------------===//
2398
2399bool arith::FPToUIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2400 return checkIntFloatCast<FloatType, IntegerType>(inputs, outputs);
2401}
2402
2403OpFoldResult arith::FPToUIOp::fold(FoldAdaptor adaptor) {
2404 Type resType = getElementTypeOrSelf(getType());
2405 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2407 adaptor.getOperands(), getType(),
2408 [&bitWidth](const APFloat &a, bool &castStatus) {
2409 bool ignored;
2410 APSInt api(bitWidth, /*isUnsigned=*/true);
2411 castStatus = APFloat::opInvalidOp !=
2412 a.convertToInteger(api, APFloat::rmTowardZero, &ignored);
2413 return api;
2414 });
2415}
2416
2417//===----------------------------------------------------------------------===//
2418// FPToSIOp
2419//===----------------------------------------------------------------------===//
2420
2421bool arith::FPToSIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2422 return checkIntFloatCast<FloatType, IntegerType>(inputs, outputs);
2423}
2424
2425OpFoldResult arith::FPToSIOp::fold(FoldAdaptor adaptor) {
2426 Type resType = getElementTypeOrSelf(getType());
2427 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2429 adaptor.getOperands(), getType(),
2430 [&bitWidth](const APFloat &a, bool &castStatus) {
2431 bool ignored;
2432 APSInt api(bitWidth, /*isUnsigned=*/false);
2433 castStatus = APFloat::opInvalidOp !=
2434 a.convertToInteger(api, APFloat::rmTowardZero, &ignored);
2435 return api;
2436 });
2437}
2438
2439//===----------------------------------------------------------------------===//
2440// IndexCastOp
2441//===----------------------------------------------------------------------===//
2442
2443/// Return the bit-width of \p t for the purpose of index_cast width checks.
2444/// For vector types use the element type; index maps to its internal storage
2445/// width (64 on all current targets).
2446static unsigned getIndexCastWidth(Type t) {
2447 if (auto intTy = dyn_cast<IntegerType>(getElementTypeOrSelf(t)))
2448 return intTy.getWidth();
2449 return IndexType::kInternalStorageBitWidth;
2450}
2451
2452static bool areIndexCastCompatible(TypeRange inputs, TypeRange outputs) {
2453 if (!areValidCastInputsAndOutputs(inputs, outputs))
2454 return false;
2455
2456 auto srcType = getTypeIfLikeOrMemRef<IntegerType, IndexType>(inputs.front());
2457 auto dstType = getTypeIfLikeOrMemRef<IntegerType, IndexType>(outputs.front());
2458 if (!srcType || !dstType)
2459 return false;
2460
2461 return (srcType.isIndex() && dstType.isSignlessInteger()) ||
2462 (srcType.isSignlessInteger() && dstType.isIndex());
2463}
2464
2465bool arith::IndexCastOp::areCastCompatible(TypeRange inputs,
2466 TypeRange outputs) {
2467 return areIndexCastCompatible(inputs, outputs);
2468}
2469
2470OpFoldResult arith::IndexCastOp::fold(FoldAdaptor adaptor) {
2471 // index_cast(constant) -> constant
2472 unsigned resultBitwidth = 64; // Default for index integer attributes.
2473 if (auto intTy = dyn_cast<IntegerType>(getElementTypeOrSelf(getType())))
2474 resultBitwidth = intTy.getWidth();
2475
2476 if (auto foldResult = constFoldCastOp<IntegerAttr, IntegerAttr>(
2477 adaptor.getOperands(), getType(),
2478 [resultBitwidth](const APInt &a, bool & /*castStatus*/) {
2479 return a.sextOrTrunc(resultBitwidth);
2480 }))
2481 return foldResult;
2482
2483 // index_cast(index_cast(x : A) : B) : A -> x, but only when B is at least
2484 // as wide as A. If B is narrower, the inner cast truncates and the outer
2485 // cast sign-extends, so the round-trip is lossy.
2486 if (auto inner = getOperand().getDefiningOp<arith::IndexCastOp>()) {
2487 Value x = inner.getOperand();
2488 if (x.getType() == getType()) {
2489 if (getIndexCastWidth(inner.getType()) >= getIndexCastWidth(x.getType()))
2490 return x;
2491 }
2492 }
2493 return {};
2494}
2495
2496void arith::IndexCastOp::getCanonicalizationPatterns(
2497 RewritePatternSet &patterns, MLIRContext *context) {
2498 patterns.add<IndexCastOfExtSI>(context);
2499}
2500
2501//===----------------------------------------------------------------------===//
2502// IndexCastUIOp
2503//===----------------------------------------------------------------------===//
2504
2505bool arith::IndexCastUIOp::areCastCompatible(TypeRange inputs,
2506 TypeRange outputs) {
2507 return areIndexCastCompatible(inputs, outputs);
2508}
2509
2510OpFoldResult arith::IndexCastUIOp::fold(FoldAdaptor adaptor) {
2511 // index_castui(constant) -> constant
2512 unsigned resultBitwidth = 64; // Default for index integer attributes.
2513 if (auto intTy = dyn_cast<IntegerType>(getElementTypeOrSelf(getType())))
2514 resultBitwidth = intTy.getWidth();
2515
2516 if (auto foldResult = constFoldCastOp<IntegerAttr, IntegerAttr>(
2517 adaptor.getOperands(), getType(),
2518 [resultBitwidth](const APInt &a, bool & /*castStatus*/) {
2519 return a.zextOrTrunc(resultBitwidth);
2520 }))
2521 return foldResult;
2522
2523 // index_castui(index_castui(x : A) : B) : A -> x, but only when B is at
2524 // least as wide as A. If B is narrower, the inner cast truncates and the
2525 // outer cast zero-extends, so the round-trip is lossy.
2526 if (auto inner = getOperand().getDefiningOp<arith::IndexCastUIOp>()) {
2527 Value x = inner.getOperand();
2528 if (x.getType() == getType()) {
2529 if (getIndexCastWidth(inner.getType()) >= getIndexCastWidth(x.getType()))
2530 return x;
2531 }
2532 }
2533 return {};
2534}
2535
2536void arith::IndexCastUIOp::getCanonicalizationPatterns(
2537 RewritePatternSet &patterns, MLIRContext *context) {
2538 patterns.add<IndexCastUIOfExtUI>(context);
2539}
2540
2541//===----------------------------------------------------------------------===//
2542// BitcastOp
2543//===----------------------------------------------------------------------===//
2544
2545bool arith::BitcastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
2546 if (!areValidCastInputsAndOutputs(inputs, outputs))
2547 return false;
2548
2549 auto srcType = getTypeIfLikeOrMemRef<IntegerType, FloatType>(inputs.front());
2550 auto dstType = getTypeIfLikeOrMemRef<IntegerType, FloatType>(outputs.front());
2551 if (!srcType || !dstType)
2552 return false;
2553
2554 return srcType.getIntOrFloatBitWidth() == dstType.getIntOrFloatBitWidth();
2555}
2556
2557OpFoldResult arith::BitcastOp::fold(FoldAdaptor adaptor) {
2558 auto resType = getType();
2559 auto operand = adaptor.getIn();
2560 if (!operand)
2561 return {};
2562
2563 /// Bitcast dense elements.
2564 if (auto denseAttr = dyn_cast_or_null<DenseElementsAttr>(operand))
2565 return denseAttr.bitcast(llvm::cast<ShapedType>(resType).getElementType());
2566 /// Other shaped types unhandled.
2567 if (llvm::isa<ShapedType>(resType))
2568 return {};
2569
2570 /// Bitcast poison.
2571 if (matchPattern(operand, ub::m_Poison()))
2572 return ub::PoisonAttr::get(getContext());
2573
2574 /// Bitcast integer or float to integer or float.
2575 if (!llvm::isa<FloatAttr, IntegerAttr>(operand))
2576 return {};
2577
2578 APInt bits = llvm::isa<FloatAttr>(operand)
2579 ? llvm::cast<FloatAttr>(operand).getValue().bitcastToAPInt()
2580 : llvm::cast<IntegerAttr>(operand).getValue();
2581 assert(resType.getIntOrFloatBitWidth() == bits.getBitWidth() &&
2582 "trying to fold on broken IR: operands have incompatible types");
2583
2584 if (auto resFloatType = dyn_cast<FloatType>(resType))
2585 return FloatAttr::get(resType,
2586 APFloat(resFloatType.getFloatSemantics(), bits));
2587 return IntegerAttr::get(resType, bits);
2588}
2589
2590void arith::BitcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2591 MLIRContext *context) {
2592 patterns.add<BitcastOfBitcast>(context);
2593}
2594
2595//===----------------------------------------------------------------------===//
2596// CmpIOp
2597//===----------------------------------------------------------------------===//
2598
2599/// Compute `lhs` `pred` `rhs`, where `pred` is one of the known integer
2600/// comparison predicates.
2601bool mlir::arith::applyCmpPredicate(arith::CmpIPredicate predicate,
2602 const APInt &lhs, const APInt &rhs) {
2603 switch (predicate) {
2604 case arith::CmpIPredicate::eq:
2605 return lhs.eq(rhs);
2606 case arith::CmpIPredicate::ne:
2607 return lhs.ne(rhs);
2608 case arith::CmpIPredicate::slt:
2609 return lhs.slt(rhs);
2610 case arith::CmpIPredicate::sle:
2611 return lhs.sle(rhs);
2612 case arith::CmpIPredicate::sgt:
2613 return lhs.sgt(rhs);
2614 case arith::CmpIPredicate::sge:
2615 return lhs.sge(rhs);
2616 case arith::CmpIPredicate::ult:
2617 return lhs.ult(rhs);
2618 case arith::CmpIPredicate::ule:
2619 return lhs.ule(rhs);
2620 case arith::CmpIPredicate::ugt:
2621 return lhs.ugt(rhs);
2622 case arith::CmpIPredicate::uge:
2623 return lhs.uge(rhs);
2624 }
2625 llvm_unreachable("unknown cmpi predicate kind");
2626}
2627
2628/// Returns true if the predicate is true for two equal operands.
2629static bool applyCmpPredicateToEqualOperands(arith::CmpIPredicate predicate) {
2630 switch (predicate) {
2631 case arith::CmpIPredicate::eq:
2632 case arith::CmpIPredicate::sle:
2633 case arith::CmpIPredicate::sge:
2634 case arith::CmpIPredicate::ule:
2635 case arith::CmpIPredicate::uge:
2636 return true;
2637 case arith::CmpIPredicate::ne:
2638 case arith::CmpIPredicate::slt:
2639 case arith::CmpIPredicate::sgt:
2640 case arith::CmpIPredicate::ult:
2641 case arith::CmpIPredicate::ugt:
2642 return false;
2643 }
2644 llvm_unreachable("unknown cmpi predicate kind");
2645}
2646
2647static std::optional<int64_t> getIntegerWidth(Type t) {
2648 if (auto intType = dyn_cast<IntegerType>(t)) {
2649 return intType.getWidth();
2650 }
2651 if (auto vectorIntType = dyn_cast<VectorType>(t)) {
2652 return llvm::cast<IntegerType>(vectorIntType.getElementType()).getWidth();
2653 }
2654 return std::nullopt;
2655}
2656
2657OpFoldResult arith::CmpIOp::fold(FoldAdaptor adaptor) {
2658 // cmpi(pred, x, x)
2659 if (getLhs() == getRhs()) {
2660 auto val = applyCmpPredicateToEqualOperands(getPredicate());
2661 return getBoolAttribute(getType(), val);
2662 }
2663
2664 if (matchPattern(adaptor.getRhs(), m_Zero())) {
2665 if (auto extOp = getLhs().getDefiningOp<ExtSIOp>()) {
2666 // extsi(%x : i1 -> iN) != 0 -> %x
2667 std::optional<int64_t> integerWidth =
2668 getIntegerWidth(extOp.getOperand().getType());
2669 if (integerWidth && integerWidth.value() == 1 &&
2670 getPredicate() == arith::CmpIPredicate::ne)
2671 return extOp.getOperand();
2672 }
2673 if (auto extOp = getLhs().getDefiningOp<ExtUIOp>()) {
2674 // extui(%x : i1 -> iN) != 0 -> %x
2675 std::optional<int64_t> integerWidth =
2676 getIntegerWidth(extOp.getOperand().getType());
2677 if (integerWidth && integerWidth.value() == 1 &&
2678 getPredicate() == arith::CmpIPredicate::ne)
2679 return extOp.getOperand();
2680 }
2681
2682 // arith.cmpi ne, %val, %zero : i1 -> %val
2683 if (getElementTypeOrSelf(getLhs().getType()).isInteger(1) &&
2684 getPredicate() == arith::CmpIPredicate::ne)
2685 return getLhs();
2686 }
2687
2688 if (matchPattern(adaptor.getRhs(), m_One())) {
2689 // arith.cmpi eq, %val, %one : i1 -> %val
2690 if (getElementTypeOrSelf(getLhs().getType()).isInteger(1) &&
2691 getPredicate() == arith::CmpIPredicate::eq)
2692 return getLhs();
2693 }
2694
2695 // Move constant to the right side.
2696 if (adaptor.getLhs() && !adaptor.getRhs()) {
2697 // Do not use invertPredicate, as it will change eq to ne and vice versa.
2698 using Pred = CmpIPredicate;
2699 const std::pair<Pred, Pred> invPreds[] = {
2700 {Pred::slt, Pred::sgt}, {Pred::sgt, Pred::slt}, {Pred::sle, Pred::sge},
2701 {Pred::sge, Pred::sle}, {Pred::ult, Pred::ugt}, {Pred::ugt, Pred::ult},
2702 {Pred::ule, Pred::uge}, {Pred::uge, Pred::ule}, {Pred::eq, Pred::eq},
2703 {Pred::ne, Pred::ne},
2704 };
2705 Pred origPred = getPredicate();
2706 for (auto pred : invPreds) {
2707 if (origPred == pred.first) {
2708 setPredicate(pred.second);
2709 Value lhs = getLhs();
2710 Value rhs = getRhs();
2711 getLhsMutable().assign(rhs);
2712 getRhsMutable().assign(lhs);
2713 return getResult();
2714 }
2715 }
2716 llvm_unreachable("unknown cmpi predicate kind");
2717 }
2718
2719 // We are moving constants to the right side; So if lhs is constant rhs is
2720 // guaranteed to be a constant.
2721 if (auto lhs = dyn_cast_if_present<TypedAttr>(adaptor.getLhs())) {
2723 adaptor.getOperands(), getI1SameShape(lhs.getType()),
2724 [pred = getPredicate()](const APInt &lhs, const APInt &rhs) {
2725 return APInt(1,
2726 static_cast<int64_t>(applyCmpPredicate(pred, lhs, rhs)));
2727 });
2728 }
2729
2730 return {};
2731}
2732
2733void arith::CmpIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2734 MLIRContext *context) {
2735 patterns.insert<CmpIExtSI, CmpIExtUI>(context);
2736}
2737
2738//===----------------------------------------------------------------------===//
2739// CmpFOp
2740//===----------------------------------------------------------------------===//
2741
2742/// Compute `lhs` `pred` `rhs`, where `pred` is one of the known floating point
2743/// comparison predicates.
2744bool mlir::arith::applyCmpPredicate(arith::CmpFPredicate predicate,
2745 const APFloat &lhs, const APFloat &rhs) {
2746 auto cmpResult = lhs.compare(rhs);
2747 switch (predicate) {
2748 case arith::CmpFPredicate::AlwaysFalse:
2749 return false;
2750 case arith::CmpFPredicate::OEQ:
2751 return cmpResult == APFloat::cmpEqual;
2752 case arith::CmpFPredicate::OGT:
2753 return cmpResult == APFloat::cmpGreaterThan;
2754 case arith::CmpFPredicate::OGE:
2755 return cmpResult == APFloat::cmpGreaterThan ||
2756 cmpResult == APFloat::cmpEqual;
2757 case arith::CmpFPredicate::OLT:
2758 return cmpResult == APFloat::cmpLessThan;
2759 case arith::CmpFPredicate::OLE:
2760 return cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual;
2761 case arith::CmpFPredicate::ONE:
2762 return cmpResult != APFloat::cmpUnordered && cmpResult != APFloat::cmpEqual;
2763 case arith::CmpFPredicate::ORD:
2764 return cmpResult != APFloat::cmpUnordered;
2765 case arith::CmpFPredicate::UEQ:
2766 return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpEqual;
2767 case arith::CmpFPredicate::UGT:
2768 return cmpResult == APFloat::cmpUnordered ||
2769 cmpResult == APFloat::cmpGreaterThan;
2770 case arith::CmpFPredicate::UGE:
2771 return cmpResult == APFloat::cmpUnordered ||
2772 cmpResult == APFloat::cmpGreaterThan ||
2773 cmpResult == APFloat::cmpEqual;
2774 case arith::CmpFPredicate::ULT:
2775 return cmpResult == APFloat::cmpUnordered ||
2776 cmpResult == APFloat::cmpLessThan;
2777 case arith::CmpFPredicate::ULE:
2778 return cmpResult == APFloat::cmpUnordered ||
2779 cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual;
2780 case arith::CmpFPredicate::UNE:
2781 return cmpResult != APFloat::cmpEqual;
2782 case arith::CmpFPredicate::UNO:
2783 return cmpResult == APFloat::cmpUnordered;
2784 case arith::CmpFPredicate::AlwaysTrue:
2785 return true;
2786 }
2787 llvm_unreachable("unknown cmpf predicate kind");
2788}
2789
2790OpFoldResult arith::CmpFOp::fold(FoldAdaptor adaptor) {
2791 auto lhs = dyn_cast_if_present<FloatAttr>(adaptor.getLhs());
2792 auto rhs = dyn_cast_if_present<FloatAttr>(adaptor.getRhs());
2793
2794 // If one operand is NaN, making them both NaN does not change the result.
2795 if (lhs && lhs.getValue().isNaN())
2796 rhs = lhs;
2797 if (rhs && rhs.getValue().isNaN())
2798 lhs = rhs;
2799
2800 if (!lhs || !rhs)
2801 return {};
2802
2803 auto val = applyCmpPredicate(getPredicate(), lhs.getValue(), rhs.getValue());
2804 return BoolAttr::get(getContext(), val);
2805}
2806
2807namespace {
2808class CmpFIntToFPConst final : public OpRewritePattern<CmpFOp> {
2809public:
2810 using Base::Base;
2811
2812 static CmpIPredicate convertToIntegerPredicate(CmpFPredicate pred,
2813 bool isUnsigned) {
2814 using namespace arith;
2815 switch (pred) {
2816 case CmpFPredicate::UEQ:
2817 case CmpFPredicate::OEQ:
2818 return CmpIPredicate::eq;
2819 case CmpFPredicate::UGT:
2820 case CmpFPredicate::OGT:
2821 return isUnsigned ? CmpIPredicate::ugt : CmpIPredicate::sgt;
2822 case CmpFPredicate::UGE:
2823 case CmpFPredicate::OGE:
2824 return isUnsigned ? CmpIPredicate::uge : CmpIPredicate::sge;
2825 case CmpFPredicate::ULT:
2826 case CmpFPredicate::OLT:
2827 return isUnsigned ? CmpIPredicate::ult : CmpIPredicate::slt;
2828 case CmpFPredicate::ULE:
2829 case CmpFPredicate::OLE:
2830 return isUnsigned ? CmpIPredicate::ule : CmpIPredicate::sle;
2831 case CmpFPredicate::UNE:
2832 case CmpFPredicate::ONE:
2833 return CmpIPredicate::ne;
2834 default:
2835 llvm_unreachable("Unexpected predicate!");
2836 }
2837 }
2838
2839 LogicalResult matchAndRewrite(CmpFOp op,
2840 PatternRewriter &rewriter) const override {
2841 FloatAttr flt;
2842 if (!matchPattern(op.getRhs(), m_Constant(&flt)))
2843 return failure();
2844
2845 const APFloat &rhs = flt.getValue();
2846
2847 // Don't attempt to fold a nan.
2848 if (rhs.isNaN())
2849 return failure();
2850
2851 // Get the width of the mantissa. We don't want to hack on conversions that
2852 // might lose information from the integer, e.g. "i64 -> float"
2853 FloatType floatTy = llvm::cast<FloatType>(op.getRhs().getType());
2854 int mantissaWidth = floatTy.getFPMantissaWidth();
2855 if (mantissaWidth <= 0)
2856 return failure();
2857
2858 bool isUnsigned;
2859 Value intVal;
2860
2861 if (auto si = op.getLhs().getDefiningOp<SIToFPOp>()) {
2862 isUnsigned = false;
2863 intVal = si.getIn();
2864 } else if (auto ui = op.getLhs().getDefiningOp<UIToFPOp>()) {
2865 isUnsigned = true;
2866 intVal = ui.getIn();
2867 } else {
2868 return failure();
2869 }
2870
2871 // Check to see that the input is converted from an integer type that is
2872 // small enough that preserves all bits.
2873 auto intTy = llvm::cast<IntegerType>(intVal.getType());
2874 auto intWidth = intTy.getWidth();
2875
2876 // Number of bits representing values, as opposed to the sign
2877 auto valueBits = isUnsigned ? intWidth : (intWidth - 1);
2878
2879 const llvm::fltSemantics &semantics = floatTy.getFloatSemantics();
2880
2881 // Conservatively require an exact representation of integer zero. For
2882 // example, f8E8M0FNU converts zero to its smallest positive value.
2883 if (!APFloat::semanticsHasZero(semantics))
2884 return failure();
2885
2886 // Signed inputs may be negative, which e.g. f8E5M3FNU cannot represent.
2887 // Do not try to convert the signed minimum below for such formats.
2888 if (!isUnsigned && !APFloat::semanticsHasSignedRepr(semantics))
2889 return failure();
2890
2891 if (!APFloat::semanticsHasInf(semantics)) {
2892 // Overflow can produce NaN or saturate to a finite value:
2893 // - sitofp(1000 : i32) to f8E4M3FN is NaN, so cmpf ogt against 0.0
2894 // is false, whereas cmpi sgt against integer zero would be true.
2895 // - uitofp(8 : i4) to f6E2M3FN saturates to 7.5. Equality against 7.5
2896 // is true, but the fractional-constant logic below would fold it to
2897 // false. Its four bits of precision do not prevent overflow.
2898 //
2899 // Conservatively require the enclosing 2^valueBits (and its negative
2900 // for signed inputs) to be representable, so rounding stays within
2901 // finite bounds. Equality at the exponent bound is safe.
2902 if (APFloat::semanticsMaxExponent(semantics) <
2903 static_cast<int>(valueBits))
2904 return failure();
2905 }
2906
2907 // Following test does NOT adjust intWidth downwards for signed inputs,
2908 // because the most negative value still requires all the mantissa bits
2909 // to distinguish it from one less than that value.
2910 if ((int)intWidth > mantissaWidth) {
2911 // Conversion would lose accuracy. Check if loss can impact comparison.
2912 int exponent = ilogb(rhs);
2913 if (exponent == APFloat::IEK_Inf) {
2914 int maxExponent = ilogb(APFloat::getLargest(rhs.getSemantics()));
2915 if (maxExponent < static_cast<int>(valueBits)) {
2916 // Conversion could create infinity. For example, sitofp(65536 : i32)
2917 // to f16 is +inf, so equality against +inf can be true.
2918 return failure();
2919 }
2920 } else {
2921 // Note that if rhs is zero or NaN, then Exp is negative
2922 // and first condition is trivially false.
2923 if (mantissaWidth <= exponent && exponent <= (int)valueBits) {
2924 // Conversion could affect comparison.
2925 return failure();
2926 }
2927 }
2928 }
2929
2930 // Convert to equivalent cmpi predicate
2931 CmpIPredicate pred;
2932 switch (op.getPredicate()) {
2933 case CmpFPredicate::AlwaysTrue:
2934 case CmpFPredicate::ORD:
2935 // Int to fp conversion doesn't create a nan (ord checks neither is a nan)
2936 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
2937 /*width=*/1);
2938 return success();
2939 case CmpFPredicate::AlwaysFalse:
2940 case CmpFPredicate::UNO:
2941 // Int to fp conversion doesn't create a nan (uno checks either is a nan)
2942 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
2943 /*width=*/1);
2944 return success();
2945 default:
2946 pred = convertToIntegerPredicate(op.getPredicate(), isUnsigned);
2947 break;
2948 }
2949
2950 if (!isUnsigned) {
2951 // If the rhs value is > SignedMax, fold the comparison. This handles
2952 // +INF and large values.
2953 APFloat signedMax(rhs.getSemantics());
2954 signedMax.convertFromAPInt(APInt::getSignedMaxValue(intWidth), true,
2955 APFloat::rmNearestTiesToEven);
2956 if (signedMax < rhs) { // smax < 13123.0
2957 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::slt ||
2958 pred == CmpIPredicate::sle)
2959 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
2960 /*width=*/1);
2961 else
2962 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
2963 /*width=*/1);
2964 return success();
2965 }
2966 } else {
2967 // If the rhs value is > UnsignedMax, fold the comparison. This handles
2968 // +INF and large values.
2969 APFloat unsignedMax(rhs.getSemantics());
2970 unsignedMax.convertFromAPInt(APInt::getMaxValue(intWidth), false,
2971 APFloat::rmNearestTiesToEven);
2972 if (unsignedMax < rhs) { // umax < 13123.0
2973 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::ult ||
2974 pred == CmpIPredicate::ule)
2975 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
2976 /*width=*/1);
2977 else
2978 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
2979 /*width=*/1);
2980 return success();
2981 }
2982 }
2983
2984 if (!isUnsigned) {
2985 // See if the rhs value is < SignedMin.
2986 APFloat signedMin(rhs.getSemantics());
2987 signedMin.convertFromAPInt(APInt::getSignedMinValue(intWidth), true,
2988 APFloat::rmNearestTiesToEven);
2989 if (signedMin > rhs) { // smin > 12312.0
2990 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::sgt ||
2991 pred == CmpIPredicate::sge)
2992 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
2993 /*width=*/1);
2994 else
2995 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
2996 /*width=*/1);
2997 return success();
2998 }
2999 } else {
3000 // See if the rhs value is < UnsignedMin.
3001 APFloat unsignedMin(rhs.getSemantics());
3002 unsignedMin.convertFromAPInt(APInt::getMinValue(intWidth), false,
3003 APFloat::rmNearestTiesToEven);
3004 if (unsignedMin > rhs) { // umin > 12312.0
3005 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::ugt ||
3006 pred == CmpIPredicate::uge)
3007 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
3008 /*width=*/1);
3009 else
3010 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
3011 /*width=*/1);
3012 return success();
3013 }
3014 }
3015
3016 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3017 // [0, UMAX], but it may still be fractional. See if it is fractional by
3018 // casting the FP value to the integer value and back, checking for
3019 // equality. Don't do this for zero, because -0.0 is not fractional.
3020 bool ignored;
3021 APSInt rhsInt(intWidth, isUnsigned);
3022 if (APFloat::opInvalidOp ==
3023 rhs.convertToInteger(rhsInt, APFloat::rmTowardZero, &ignored)) {
3024 // Undefined behavior invoked - the destination type can't represent
3025 // the input constant.
3026 return failure();
3027 }
3028
3029 if (!rhs.isZero()) {
3030 APFloat apf(floatTy.getFloatSemantics(),
3031 APInt::getZero(floatTy.getWidth()));
3032 apf.convertFromAPInt(rhsInt, !isUnsigned, APFloat::rmNearestTiesToEven);
3033
3034 bool equal = apf == rhs;
3035 if (!equal) {
3036 // If we had a comparison against a fractional value, we have to adjust
3037 // the compare predicate and sometimes the value. rhsInt is rounded
3038 // towards zero at this point.
3039 switch (pred) {
3040 case CmpIPredicate::ne: // (float)int != 4.4 --> true
3041 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
3042 /*width=*/1);
3043 return success();
3044 case CmpIPredicate::eq: // (float)int == 4.4 --> false
3045 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
3046 /*width=*/1);
3047 return success();
3048 case CmpIPredicate::ule:
3049 // (float)int <= 4.4 --> int <= 4
3050 // (float)int <= -4.4 --> false
3051 if (rhs.isNegative()) {
3052 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
3053 /*width=*/1);
3054 return success();
3055 }
3056 break;
3057 case CmpIPredicate::sle:
3058 // (float)int <= 4.4 --> int <= 4
3059 // (float)int <= -4.4 --> int < -4
3060 if (rhs.isNegative())
3061 pred = CmpIPredicate::slt;
3062 break;
3063 case CmpIPredicate::ult:
3064 // (float)int < -4.4 --> false
3065 // (float)int < 4.4 --> int <= 4
3066 if (rhs.isNegative()) {
3067 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/false,
3068 /*width=*/1);
3069 return success();
3070 }
3071 pred = CmpIPredicate::ule;
3072 break;
3073 case CmpIPredicate::slt:
3074 // (float)int < -4.4 --> int < -4
3075 // (float)int < 4.4 --> int <= 4
3076 if (!rhs.isNegative())
3077 pred = CmpIPredicate::sle;
3078 break;
3079 case CmpIPredicate::ugt:
3080 // (float)int > 4.4 --> int > 4
3081 // (float)int > -4.4 --> true
3082 if (rhs.isNegative()) {
3083 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
3084 /*width=*/1);
3085 return success();
3086 }
3087 break;
3088 case CmpIPredicate::sgt:
3089 // (float)int > 4.4 --> int > 4
3090 // (float)int > -4.4 --> int >= -4
3091 if (rhs.isNegative())
3092 pred = CmpIPredicate::sge;
3093 break;
3094 case CmpIPredicate::uge:
3095 // (float)int >= -4.4 --> true
3096 // (float)int >= 4.4 --> int > 4
3097 if (rhs.isNegative()) {
3098 rewriter.replaceOpWithNewOp<ConstantIntOp>(op, /*value=*/true,
3099 /*width=*/1);
3100 return success();
3101 }
3102 pred = CmpIPredicate::ugt;
3103 break;
3104 case CmpIPredicate::sge:
3105 // (float)int >= -4.4 --> int >= -4
3106 // (float)int >= 4.4 --> int > 4
3107 if (!rhs.isNegative())
3108 pred = CmpIPredicate::sgt;
3109 break;
3110 }
3111 }
3112 }
3113
3114 // Lower this FP comparison into an appropriate integer version of the
3115 // comparison.
3116 rewriter.replaceOpWithNewOp<CmpIOp>(
3117 op, pred, intVal,
3118 ConstantOp::create(rewriter, op.getLoc(), intVal.getType(),
3119 rewriter.getIntegerAttr(intVal.getType(), rhsInt)));
3120 return success();
3121 }
3122};
3123} // namespace
3124
3125void arith::CmpFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3126 MLIRContext *context) {
3127 patterns.insert<CmpFIntToFPConst>(context);
3128}
3129
3130//===----------------------------------------------------------------------===//
3131// SelectOp
3132//===----------------------------------------------------------------------===//
3133
3134namespace {
3135// select %arg, %c1, %c0 => extui %arg
3136struct SelectToExtUI : public OpRewritePattern<arith::SelectOp> {
3137 using Base::Base;
3138
3139 LogicalResult matchAndRewrite(arith::SelectOp op,
3140 PatternRewriter &rewriter) const override {
3141 // Cannot extui i1 to i1, or i1 to f32
3142 if (!llvm::isa<IntegerType>(op.getType()) || op.getType().isInteger(1))
3143 return failure();
3144
3145 // select %x, c1, %c0 => extui %arg
3146 if (matchPattern(op.getTrueValue(), m_One()) &&
3147 matchPattern(op.getFalseValue(), m_Zero())) {
3148 rewriter.replaceOpWithNewOp<arith::ExtUIOp>(op, op.getType(),
3149 op.getCondition());
3150 return success();
3151 }
3152
3153 // select %x, c0, %c1 => extui (xor %arg, true)
3154 if (matchPattern(op.getTrueValue(), m_Zero()) &&
3155 matchPattern(op.getFalseValue(), m_One())) {
3156 rewriter.replaceOpWithNewOp<arith::ExtUIOp>(
3157 op, op.getType(),
3158 arith::XOrIOp::create(
3159 rewriter, op.getLoc(), op.getCondition(),
3160 arith::ConstantIntOp::create(rewriter, op.getLoc(),
3161 op.getCondition().getType(), 1)));
3162 return success();
3163 }
3164
3165 return failure();
3166 }
3167};
3168} // namespace
3169
3170/// select(M, F(a0, a1, ..., a_n), F(b0, b1, ..., b_n))
3171/// -> F(select(M, a0, b0), select(M, a1, b1), ...) for pure and
3172/// elementwise F.
3173///
3174/// Correctness provement:
3175///
3176/// Let's discuss the cases ignoring poison first.
3177///
3178/// As F is elementwise, we have
3179///
3180/// F(a1, a2, ..., a_n)[p] = F(a1[p], a2[p], ..., a_n[p])
3181///
3182/// then for
3183///
3184/// L = select(M, F(a0, a1, ..., a_n), F(b0, b1, ..., b_n))
3185/// R = F(select(M, a0, b0), select(M, a1, b1), ....)
3186///
3187/// for any position p, we have:
3188///
3189/// if M[p] == true, then L[p] == F(a)[p] == F(a[p]) == F(select(true, a[p], b[p])) == R[p]
3190/// if M[p] == false, then L[p] == F(b)[p] == F(b[p]) == F(select(false, a[p], b[p])) == R[p]
3191///
3192/// And F is pure, so that we can move and reduce F.
3193/// So select(M, F(a0, a1, ..., a_n), F(b0, b1, ..., b_n)) is equal to
3194/// F(select(M, a0, b0), select(M, a1, b1), ...) ignoring poison.
3195///
3196/// Let's consider the poison value now. ArithBase.td says:
3197///
3198/// Unless otherwise stated, the operations within this dialect
3199/// propagate poison values, i.e., if any of its inputs are poison, then the
3200/// output is poison.
3201///
3202/// So most F, F(poison) = poison
3203///
3204/// Then for any position p, if a[p] is poison
3205///
3206/// if M[p] == true, L[p] == f(a[p]) == poison == F(select(true, a[p], b[p])) == R[p]
3207/// if M[p] == false, L[p] == f(b[p]) == F(select(false, a[p], b[p])) == R[p]
3208/// if M[p] == P, L[p] == poison == F(select(P, a, b)) == R[p]
3209///
3210/// Then the transformation doesn't change poison propagation.
3211///
3212/// For F which doesn't meet the assumption, this transformation may change the
3213/// poison propagation, but the language allows us to replace poison with a undef
3214/// or any value with the same type. So this is still valid transformation.
3215struct SelectCommonElementwiseOp : public OpRewritePattern<arith::SelectOp> {
3216 using Base::Base;
3217
3218 LogicalResult matchAndRewrite(arith::SelectOp op,
3219 PatternRewriter &rewriter) const override {
3220 Operation *lhs = op.getTrueValue().getDefiningOp();
3221 Operation *rhs = op.getFalseValue().getDefiningOp();
3222 if (!lhs || !rhs || lhs == rhs)
3223 return failure();
3224
3225 // Do not hoist a select through selects: rewriting
3226 // select(c, select(d, a, b), select(d, x, y)) into
3227 // select(d, select(c, a, x), select(c, b, y)) matches again with c and d
3228 // swapped, so the greedy rewriter never converges.
3229 if (isa<arith::SelectOp>(lhs))
3230 return failure();
3231
3232 for (Operation *producer : {lhs, rhs}) {
3233 // Avoid sinking loop invariant code into the loop.
3234 //
3235 // TODO: handle the cases by introducing more CFG/Loop analysis.
3236 if (producer->getBlock() != op->getBlock())
3237 return failure();
3238
3239 // `isEquivalentTo` doesn't catch all cases, so we conservatively match
3240 // the cases we know how to convert
3241 if (producer->getNumResults() != 1 || !producer->hasOneUse() ||
3242 producer->getNumRegions() != 0 || producer->getNumSuccessors() != 0 ||
3243 !producer->hasTrait<OpTrait::Elementwise>() || !isPure(producer))
3244 return failure();
3245 }
3246
3247 // Check if the lhs and the rhs are the same kind of op, have the
3248 // same structure of inputs, types, and attributes.
3252 return failure();
3253
3255 SmallVector<Operation *> createdSelects;
3256 SmallVector<Value> operands;
3257 Type conditionType = op.getCondition().getType();
3258 for (auto [a, b] : llvm::zip(lhs->getOperands(), rhs->getOperands())) {
3259 // For select(c, F(a, k), F(b, k)), we should transform it into
3260 // F(select(c, a, b), k) instead of F(select(c, a, b), select(c, k, k))
3261 if (a == b) {
3262 operands.push_back(a);
3263 continue;
3264 }
3265 if (!conditionType.isSignlessInteger(1) &&
3266 (!isa<VectorType, TensorType>(a.getType()) ||
3267 cast<ShapedType>(a.getType()).clone(rewriter.getI1Type()) !=
3268 conditionType)) {
3269
3270 for (Operation *created : llvm::reverse(createdSelects))
3271 rewriter.eraseOp(created);
3272 return failure();
3273 }
3274
3275 // Always creating a new pair would not merging equivalent results.
3276 auto [it, inserted] = selected.try_emplace(std::make_pair(a, b));
3277 if (inserted) {
3278 auto select = arith::SelectOp::create(rewriter, op.getLoc(),
3279 op.getCondition(), a, b);
3280 it->second = select;
3281 createdSelects.push_back(select);
3282 }
3283 operands.push_back(it->second);
3284 }
3285
3286 Operation *common = rewriter.clone(*lhs);
3287 common->setOperands(operands);
3288 rewriter.replaceOp(op, common->getResults());
3289 return success();
3290 }
3291};
3292
3293void arith::SelectOp::getCanonicalizationPatterns(RewritePatternSet &results,
3294 MLIRContext *context) {
3295 results.add<RedundantSelectFalse, RedundantSelectTrue, SelectNotCond,
3296 SelectI1ToNot, SelectCmpISgeToMaxSI, SelectCmpISgeToMinSI,
3297 SelectCmpISgtToMaxSI, SelectCmpISgtToMinSI, SelectCmpISleToMaxSI,
3298 SelectCmpISleToMinSI, SelectCmpISltToMaxSI, SelectCmpISltToMinSI,
3299 SelectCmpIUgeToMaxUI, SelectCmpIUgeToMinUI, SelectCmpIUgtToMaxUI,
3300 SelectCmpIUgtToMinUI, SelectCmpIUleToMaxUI, SelectCmpIUleToMinUI,
3301 SelectCmpIUltToMaxUI, SelectCmpIUltToMinUI, SelectToExtUI>(
3302 context);
3303 results.add<SelectCommonElementwiseOp>(context);
3304}
3305
3306OpFoldResult arith::SelectOp::fold(FoldAdaptor adaptor) {
3307 Value trueVal = getTrueValue();
3308 Value falseVal = getFalseValue();
3309 if (trueVal == falseVal)
3310 return trueVal;
3311
3312 Value condition = getCondition();
3313
3314 // select true, %0, %1 => %0
3315 if (matchPattern(adaptor.getCondition(), m_One()))
3316 return trueVal;
3317
3318 // select false, %0, %1 => %1
3319 if (matchPattern(adaptor.getCondition(), m_Zero()))
3320 return falseVal;
3321
3322 // If either operand is fully poisoned, return the other.
3323 if (matchPattern(adaptor.getTrueValue(), ub::m_Poison()))
3324 return falseVal;
3325
3326 if (matchPattern(adaptor.getFalseValue(), ub::m_Poison()))
3327 return trueVal;
3328
3329 // select %x, true, false => %x
3330 if (getType().isSignlessInteger(1) &&
3331 matchPattern(adaptor.getTrueValue(), m_One()) &&
3332 matchPattern(adaptor.getFalseValue(), m_Zero()))
3333 return condition;
3334
3335 if (auto cmp = condition.getDefiningOp<arith::CmpIOp>()) {
3336 auto pred = cmp.getPredicate();
3337 if (pred == arith::CmpIPredicate::eq || pred == arith::CmpIPredicate::ne) {
3338 auto cmpLhs = cmp.getLhs();
3339 auto cmpRhs = cmp.getRhs();
3340
3341 // %0 = arith.cmpi eq, %arg0, %arg1
3342 // %1 = arith.select %0, %arg0, %arg1 => %arg1
3343
3344 // %0 = arith.cmpi ne, %arg0, %arg1
3345 // %1 = arith.select %0, %arg0, %arg1 => %arg0
3346
3347 if ((cmpLhs == trueVal && cmpRhs == falseVal) ||
3348 (cmpRhs == trueVal && cmpLhs == falseVal))
3349 return pred == arith::CmpIPredicate::ne ? trueVal : falseVal;
3350 }
3351 }
3352
3353 // Constant-fold constant operands over non-splat constant condition.
3354 // select %cst_vec, %cst0, %cst1 => %cst2
3355 if (auto cond =
3356 dyn_cast_if_present<DenseElementsAttr>(adaptor.getCondition())) {
3357 // DenseElementsAttr by construction always has a static shape.
3358 assert(cond.getType().hasStaticShape() &&
3359 "DenseElementsAttr must have static shape");
3360 if (auto lhs =
3361 dyn_cast_if_present<DenseElementsAttr>(adaptor.getTrueValue())) {
3362 if (auto rhs =
3363 dyn_cast_if_present<DenseElementsAttr>(adaptor.getFalseValue())) {
3364 SmallVector<Attribute> results;
3365 results.reserve(static_cast<size_t>(cond.getNumElements()));
3366 auto condVals = llvm::make_range(cond.value_begin<BoolAttr>(),
3367 cond.value_end<BoolAttr>());
3368 auto lhsVals = llvm::make_range(lhs.value_begin<Attribute>(),
3369 lhs.value_end<Attribute>());
3370 auto rhsVals = llvm::make_range(rhs.value_begin<Attribute>(),
3371 rhs.value_end<Attribute>());
3372
3373 for (auto [condVal, lhsVal, rhsVal] :
3374 llvm::zip_equal(condVals, lhsVals, rhsVals))
3375 results.push_back(condVal.getValue() ? lhsVal : rhsVal);
3376
3377 return DenseElementsAttr::get(lhs.getType(), results);
3378 }
3379 }
3380 }
3381
3382 return nullptr;
3383}
3384
3385ParseResult SelectOp::parse(OpAsmParser &parser, OperationState &result) {
3386 Type conditionType, resultType;
3387 SmallVector<OpAsmParser::UnresolvedOperand, 3> operands;
3388 if (parser.parseOperandList(operands, /*requiredOperandCount=*/3) ||
3389 parser.parseOptionalAttrDict(result.attributes) ||
3390 parser.parseColonType(resultType))
3391 return failure();
3392
3393 // Check for the explicit condition type if this is a masked tensor or vector.
3394 if (succeeded(parser.parseOptionalComma())) {
3395 conditionType = resultType;
3396 if (parser.parseType(resultType))
3397 return failure();
3398 } else {
3399 conditionType = parser.getBuilder().getI1Type();
3400 }
3401
3402 result.addTypes(resultType);
3403 return parser.resolveOperands(operands,
3404 {conditionType, resultType, resultType},
3405 parser.getNameLoc(), result.operands);
3406}
3407
3408void arith::SelectOp::print(OpAsmPrinter &p) {
3409 p << " " << getOperands();
3410 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
3411 p << " : ";
3412 if (ShapedType condType = dyn_cast<ShapedType>(getCondition().getType()))
3413 p << condType << ", ";
3414 p << getType();
3415}
3416
3417LogicalResult arith::SelectOp::verify() {
3418 Type conditionType = getCondition().getType();
3419 if (conditionType.isSignlessInteger(1))
3420 return success();
3421
3422 // If the result type is a vector or tensor, the type can be a mask with the
3423 // same elements.
3424 Type resultType = getType();
3425 if (!llvm::isa<TensorType, VectorType>(resultType))
3426 return emitOpError() << "expected condition to be a signless i1, but got "
3427 << conditionType;
3428 Type shapedConditionType = getI1SameShape(resultType);
3429 if (conditionType != shapedConditionType) {
3430 return emitOpError() << "expected condition type to have the same shape "
3431 "as the result type, expected "
3432 << shapedConditionType << ", but got "
3433 << conditionType;
3434 }
3435 return success();
3436}
3437//===----------------------------------------------------------------------===//
3438// ShLIOp
3439//===----------------------------------------------------------------------===//
3440
3441OpFoldResult arith::ShLIOp::fold(FoldAdaptor adaptor) {
3442 // TODO: shli(x, c) -> poison when c is out of range (c >= bit width). An
3443 // out-of-range shift amount is undefined behaviour and could fold to poison,
3444 // but that would make the arith dialect depend on the ub dialect to
3445 // materialize ub.poison; left out for now.
3446
3447 // shli(x, 0) -> x
3448 if (matchPattern(adaptor.getRhs(), m_Zero()))
3449 return getLhs();
3450 // shli(0, x) -> 0. An out-of-range shift amount yields poison, so refining
3451 // it to 0 is valid.
3452 if (matchPattern(adaptor.getLhs(), m_Zero()))
3453 return getLhs();
3454 // Don't fold if shifting more or equal than the bit width.
3455 bool bounded = false;
3457 adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
3458 bounded = b.ult(b.getBitWidth());
3459 return a.shl(b);
3460 });
3461 return bounded ? result : Attribute();
3462}
3463
3464//===----------------------------------------------------------------------===//
3465// ShRUIOp
3466//===----------------------------------------------------------------------===//
3467
3468OpFoldResult arith::ShRUIOp::fold(FoldAdaptor adaptor) {
3469 // TODO: shrui(x, c) -> poison when c is out of range (c >= bit width). An
3470 // out-of-range shift amount is undefined behaviour and could fold to poison,
3471 // but that would make the arith dialect depend on the ub dialect to
3472 // materialize ub.poison; left out for now.
3473
3474 // shrui(x, 0) -> x
3475 if (matchPattern(adaptor.getRhs(), m_Zero()))
3476 return getLhs();
3477 // shrui(0, x) -> 0. An out-of-range shift amount yields poison, so refining
3478 // it to 0 is valid.
3479 if (matchPattern(adaptor.getLhs(), m_Zero()))
3480 return getLhs();
3481 // shrui(x, x) -> 0. For any in-range shift amount v < bitwidth, v >> v == 0
3482 // (v < 2^v); out-of-range amounts yield poison, so 0 is a valid refinement.
3483 if (getLhs() == getRhs())
3484 return getIntegerAttrOfType(getType(), 0);
3485 // Don't fold if shifting more or equal than the bit width.
3486 bool bounded = false;
3488 adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
3489 bounded = b.ult(b.getBitWidth());
3490 return a.lshr(b);
3491 });
3492 return bounded ? result : Attribute();
3493}
3494
3495//===----------------------------------------------------------------------===//
3496// ShRSIOp
3497//===----------------------------------------------------------------------===//
3498
3499OpFoldResult arith::ShRSIOp::fold(FoldAdaptor adaptor) {
3500 // TODO: shrsi(x, c) -> poison when c is out of range (c >= bit width). An
3501 // out-of-range shift amount is undefined behaviour and could fold to poison,
3502 // but that would make the arith dialect depend on the ub dialect to
3503 // materialize ub.poison; left out for now.
3504
3505 // shrsi(x, 0) -> x
3506 if (matchPattern(adaptor.getRhs(), m_Zero()))
3507 return getLhs();
3508 // shrsi(0, x) -> 0. An out-of-range shift amount yields poison, so refining
3509 // it to 0 is valid.
3510 if (matchPattern(adaptor.getLhs(), m_Zero()))
3511 return getLhs();
3512 // shrsi(x, x) -> 0. For any in-range shift amount v < bitwidth, v is a small
3513 // non-negative value and v >> v == 0; out-of-range amounts yield poison.
3514 if (getLhs() == getRhs())
3515 return getIntegerAttrOfType(getType(), 0);
3516 // shrsi(-1, x) -> -1. Arithmetic shift of all-ones is all-ones for any
3517 // in-range amount; out-of-range amounts yield poison.
3518 if (APInt val;
3519 matchPattern(adaptor.getLhs(), m_ConstantInt(&val)) && val.isAllOnes())
3520 return getLhs();
3521 // Don't fold if shifting more or equal than the bit width.
3522 bool bounded = false;
3524 adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
3525 bounded = b.ult(b.getBitWidth());
3526 return a.ashr(b);
3527 });
3528 return bounded ? result : Attribute();
3529}
3530
3531//===----------------------------------------------------------------------===//
3532// Atomic Enum
3533//===----------------------------------------------------------------------===//
3534
3535/// Returns the identity value attribute associated with an AtomicRMWKind op.
3536TypedAttr mlir::arith::getIdentityValueAttr(AtomicRMWKind kind, Type resultType,
3537 OpBuilder &builder, Location loc,
3538 bool useOnlyFiniteValue) {
3539 switch (kind) {
3540 case AtomicRMWKind::maximumf: {
3541 const llvm::fltSemantics &semantic =
3542 llvm::cast<FloatType>(resultType).getFloatSemantics();
3543 APFloat identity = useOnlyFiniteValue
3544 ? APFloat::getLargest(semantic, /*Negative=*/true)
3545 : APFloat::getInf(semantic, /*Negative=*/true);
3546 return builder.getFloatAttr(resultType, identity);
3547 }
3548 case AtomicRMWKind::maxnumf: {
3549 const llvm::fltSemantics &semantic =
3550 llvm::cast<FloatType>(resultType).getFloatSemantics();
3551 APFloat identity = useOnlyFiniteValue
3552 ? APFloat::getLargest(semantic, /*Negative=*/true)
3553 : APFloat::getNaN(semantic, /*Negative=*/true);
3554 return builder.getFloatAttr(resultType, identity);
3555 }
3556 case AtomicRMWKind::addf:
3557 case AtomicRMWKind::addi:
3558 case AtomicRMWKind::maxu:
3559 case AtomicRMWKind::ori:
3560 case AtomicRMWKind::xori:
3561 return builder.getZeroAttr(resultType);
3562 case AtomicRMWKind::andi:
3563 return builder.getIntegerAttr(
3564 resultType,
3565 APInt::getAllOnes(llvm::cast<IntegerType>(resultType).getWidth()));
3566 case AtomicRMWKind::maxs:
3567 return builder.getIntegerAttr(
3568 resultType, APInt::getSignedMinValue(
3569 llvm::cast<IntegerType>(resultType).getWidth()));
3570 case AtomicRMWKind::minimumf: {
3571 const llvm::fltSemantics &semantic =
3572 llvm::cast<FloatType>(resultType).getFloatSemantics();
3573 APFloat identity = useOnlyFiniteValue
3574 ? APFloat::getLargest(semantic, /*Negative=*/false)
3575 : APFloat::getInf(semantic, /*Negative=*/false);
3576
3577 return builder.getFloatAttr(resultType, identity);
3578 }
3579 case AtomicRMWKind::minnumf: {
3580 const llvm::fltSemantics &semantic =
3581 llvm::cast<FloatType>(resultType).getFloatSemantics();
3582 APFloat identity = useOnlyFiniteValue
3583 ? APFloat::getLargest(semantic, /*Negative=*/false)
3584 : APFloat::getNaN(semantic, /*Negative=*/false);
3585 return builder.getFloatAttr(resultType, identity);
3586 }
3587 case AtomicRMWKind::mins:
3588 return builder.getIntegerAttr(
3589 resultType, APInt::getSignedMaxValue(
3590 llvm::cast<IntegerType>(resultType).getWidth()));
3591 case AtomicRMWKind::minu:
3592 return builder.getIntegerAttr(
3593 resultType,
3594 APInt::getMaxValue(llvm::cast<IntegerType>(resultType).getWidth()));
3595 case AtomicRMWKind::muli:
3596 return builder.getIntegerAttr(resultType, 1);
3597 case AtomicRMWKind::mulf:
3598 return builder.getFloatAttr(resultType, 1);
3599 // `assign` is not a reduction and has no identity element.
3600 case AtomicRMWKind::assign:
3601 break;
3602 }
3603 (void)emitOptionalError(loc, "Reduction operation type not supported");
3604 return nullptr;
3605}
3606
3607/// Returns the identity numeric value of the given op.
3608std::optional<TypedAttr> mlir::arith::getNeutralElement(Operation *op) {
3609 std::optional<AtomicRMWKind> maybeKind =
3611 // Floating-point operations.
3612 .Case([](arith::AddFOp op) { return AtomicRMWKind::addf; })
3613 .Case([](arith::MulFOp op) { return AtomicRMWKind::mulf; })
3614 .Case([](arith::MaximumFOp op) { return AtomicRMWKind::maximumf; })
3615 .Case([](arith::MinimumFOp op) { return AtomicRMWKind::minimumf; })
3616 .Case([](arith::MaxNumFOp op) { return AtomicRMWKind::maxnumf; })
3617 .Case([](arith::MinNumFOp op) { return AtomicRMWKind::minnumf; })
3618 // Integer operations.
3619 .Case([](arith::AddIOp op) { return AtomicRMWKind::addi; })
3620 .Case([](arith::OrIOp op) { return AtomicRMWKind::ori; })
3621 .Case([](arith::XOrIOp op) { return AtomicRMWKind::xori; })
3622 .Case([](arith::AndIOp op) { return AtomicRMWKind::andi; })
3623 .Case([](arith::MaxUIOp op) { return AtomicRMWKind::maxu; })
3624 .Case([](arith::MinUIOp op) { return AtomicRMWKind::minu; })
3625 .Case([](arith::MaxSIOp op) { return AtomicRMWKind::maxs; })
3626 .Case([](arith::MinSIOp op) { return AtomicRMWKind::mins; })
3627 .Case([](arith::MulIOp op) { return AtomicRMWKind::muli; })
3628 .Default(std::nullopt);
3629 if (!maybeKind) {
3630 return std::nullopt;
3631 }
3632
3633 bool useOnlyFiniteValue = false;
3634 auto fmfOpInterface = dyn_cast<ArithFastMathInterface>(op);
3635 if (fmfOpInterface) {
3636 arith::FastMathFlagsAttr fmfAttr = fmfOpInterface.getFastMathFlagsAttr();
3637 useOnlyFiniteValue =
3638 bitEnumContainsAny(fmfAttr.getValue(), arith::FastMathFlags::ninf);
3639 if (*maybeKind == AtomicRMWKind::maxnumf ||
3640 *maybeKind == AtomicRMWKind::minnumf) {
3641 if (bitEnumContainsAny(fmfAttr.getValue(), arith::FastMathFlags::nnan)) {
3642 *maybeKind = *maybeKind == AtomicRMWKind::maxnumf
3643 ? AtomicRMWKind::maximumf
3644 : AtomicRMWKind::minimumf;
3645 } else {
3646 useOnlyFiniteValue = false;
3647 }
3648 }
3649 }
3650
3651 // Builder only used as helper for attribute creation.
3652 OpBuilder b(op->getContext());
3653 Type resultType = op->getResult(0).getType();
3654
3655 return getIdentityValueAttr(*maybeKind, resultType, b, op->getLoc(),
3656 useOnlyFiniteValue);
3657}
3658
3659/// Returns the identity value associated with an AtomicRMWKind op.
3660Value mlir::arith::getIdentityValue(AtomicRMWKind op, Type resultType,
3661 OpBuilder &builder, Location loc,
3662 bool useOnlyFiniteValue) {
3663 if (auto attr = getIdentityValueAttr(op, resultType, builder, loc,
3664 useOnlyFiniteValue))
3665 return arith::ConstantOp::create(builder, loc, attr);
3666 return {};
3667}
3668
3669/// Return the value obtained by applying the reduction operation kind
3670/// associated with a binary AtomicRMWKind op to `lhs` and `rhs`.
3672 Location loc, Value lhs, Value rhs) {
3673 switch (op) {
3674 case AtomicRMWKind::addf:
3675 return arith::AddFOp::create(builder, loc, lhs, rhs);
3676 case AtomicRMWKind::addi:
3677 return arith::AddIOp::create(builder, loc, lhs, rhs);
3678 case AtomicRMWKind::mulf:
3679 return arith::MulFOp::create(builder, loc, lhs, rhs);
3680 case AtomicRMWKind::muli:
3681 return arith::MulIOp::create(builder, loc, lhs, rhs);
3682 case AtomicRMWKind::maximumf:
3683 return arith::MaximumFOp::create(builder, loc, lhs, rhs);
3684 case AtomicRMWKind::minimumf:
3685 return arith::MinimumFOp::create(builder, loc, lhs, rhs);
3686 case AtomicRMWKind::maxnumf:
3687 return arith::MaxNumFOp::create(builder, loc, lhs, rhs);
3688 case AtomicRMWKind::minnumf:
3689 return arith::MinNumFOp::create(builder, loc, lhs, rhs);
3690 case AtomicRMWKind::maxs:
3691 return arith::MaxSIOp::create(builder, loc, lhs, rhs);
3692 case AtomicRMWKind::mins:
3693 return arith::MinSIOp::create(builder, loc, lhs, rhs);
3694 case AtomicRMWKind::maxu:
3695 return arith::MaxUIOp::create(builder, loc, lhs, rhs);
3696 case AtomicRMWKind::minu:
3697 return arith::MinUIOp::create(builder, loc, lhs, rhs);
3698 case AtomicRMWKind::ori:
3699 return arith::OrIOp::create(builder, loc, lhs, rhs);
3700 case AtomicRMWKind::andi:
3701 return arith::AndIOp::create(builder, loc, lhs, rhs);
3702 case AtomicRMWKind::xori:
3703 return arith::XOrIOp::create(builder, loc, lhs, rhs);
3704 // `assign` is not a reduction and has no corresponding binary operation.
3705 case AtomicRMWKind::assign:
3706 break;
3707 }
3708 (void)emitOptionalError(loc, "Reduction operation type not supported");
3709 return nullptr;
3710}
3711
3712//===----------------------------------------------------------------------===//
3713// TableGen'd op method definitions
3714//===----------------------------------------------------------------------===//
3715
3716#define GET_OP_CLASSES
3717#include "mlir/Dialect/Arith/IR/ArithOps.cpp.inc"
3718
3719//===----------------------------------------------------------------------===//
3720// TableGen'd enum attribute definitions
3721//===----------------------------------------------------------------------===//
3722
3723#include "mlir/Dialect/Arith/IR/ArithOpsEnums.cpp.inc"
return success()
static Speculation::Speculatability getDivUISpeculatability(Value divisor)
Returns whether an unsigned division by divisor is speculatable.
Definition ArithOps.cpp:903
static bool checkWidthChangeCast(TypeRange inputs, TypeRange outputs)
Validate a cast that changes the width of a type.
static IntegerAttr mulIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:68
static IntegerOverflowFlagsAttr mergeOverflowFlags(IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2)
Definition ArithOps.cpp:91
static Value foldIdempotentOfSameOp(OpTy op)
Fold op(a, op(a, b)) to op(a, b) for an associative, commutative and idempotent op (e....
static constexpr llvm::RoundingMode kDefaultRoundingMode
Default rounding mode according to default LLVM floating-point environment.
Definition ArithOps.cpp:41
static Type getTypeIfLike(Type type)
Get allowed underlying types for vectors and tensors.
static bool applyCmpPredicateToEqualOperands(arith::CmpIPredicate predicate)
Returns true if the predicate is true for two equal operands.
static FailureOr< APFloat > convertFloatValue(APFloat sourceValue, const llvm::fltSemantics &targetSemantics, llvm::RoundingMode roundingMode=kDefaultRoundingMode)
Attempts to convert sourceValue to an APFloat value with targetSemantics and roundingMode,...
static Attribute foldScalingCastOp(Attribute inAttr, Attribute scaleAttr, Type resultType, function_ref< std::optional< APFloat >(const APFloat &, const APFloat &)> calculate)
Fold calculate element-wise over the operands of a scaling cast op.
static Value foldDivMul(Value lhs, Value rhs, arith::IntegerOverflowFlags ovfFlags)
Fold (a * b) / b -> a
Definition ArithOps.cpp:852
static bool hasSameEncoding(Type typeA, Type typeB)
Return false if both types are ranked tensor with mismatching encoding.
static llvm::RoundingMode convertArithRoundingModeToLLVMIR(std::optional< RoundingMode > roundingMode)
Equivalent to convertRoundingModeToLLVM(convertArithRoundingModeToLLVM(roundingMode)).
Definition ArithOps.cpp:166
static Type getUnderlyingType(Type type, type_list< ShapedTypes... >, type_list< ElementTypes... >)
Returns a non-null type only if the provided type is one of the allowed types or one of the allowed s...
static std::optional< int64_t > getIntegerWidth(Type t)
APInt(APInt::*)(const APInt &, bool &) const OverflowCheckedBinaryOp
Definition ArithOps.cpp:97
static Speculation::Speculatability getDivSISpeculatability(Value divisor)
Returns whether a signed division by divisor is speculatable.
Definition ArithOps.cpp:957
static IntegerAttr orIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:78
static IntegerAttr addIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:58
static Attribute getBoolAttribute(Type type, bool value)
Definition ArithOps.cpp:226
static bool areIndexCastCompatible(TypeRange inputs, TypeRange outputs)
static bool isFoldableScalingScale(Value scale)
Only scales that already are f8E8M0FNU fold.
static bool checkIntFloatCast(TypeRange inputs, TypeRange outputs)
static LogicalResult verifyExtOp(Op op)
static IntegerAttr subIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:63
static Attribute getIntegerAttrOfType(Type type, int64_t value)
Return a scalar or splat integer attribute of type (an integer/index type or a shaped type thereof) h...
Definition ArithOps.cpp:240
static IntegerAttr andIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:73
static int64_t getScalarOrElementWidth(Type type)
Definition ArithOps.cpp:189
static Type getTypeIfLikeOrMemRef(Type type)
Get allowed underlying types for vectors, tensors, and memrefs.
static Type getI1SameShape(Type type)
Return the type of the same shape (scalar, vector or tensor) containing i1.
Definition ArithOps.cpp:263
static bool areValidCastInputsAndOutputs(TypeRange inputs, TypeRange outputs)
static IntegerOverflowFlagsAttr mergeOverflowFlagsForReassociation(IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2, Attribute lhs, Attribute rhs, OverflowCheckedBinaryOp signedOp, OverflowCheckedBinaryOp unsignedOp)
Definition ArithOps.cpp:102
static IntegerAttr xorIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
Definition ArithOps.cpp:83
static APInt calculateUnsignedBorrow(const APInt &lhs, const APInt &rhs)
Definition ArithOps.cpp:591
static bool isExactIntToFPCast(Value intValue, Value fpValue, bool isSigned)
Returns true if every value of intValue's integer type converts exactly.
Definition ArithOps.cpp:202
std::tuple< Types... > * type_list
static IntegerAttr applyToIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs, function_ref< APInt(const APInt &, const APInt &)> binFn)
Definition ArithOps.cpp:49
static APInt calculateUnsignedOverflow(const APInt &sum, const APInt &operand)
Definition ArithOps.cpp:527
static FailureOr< APInt > getIntOrSplatIntValue(Attribute attr)
Definition ArithOps.cpp:218
static unsigned getIndexCastWidth(Type t)
Return the bit-width of t for the purpose of index_cast width checks.
static LogicalResult verifyTruncateOp(Op op)
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
if(!isCopyOut)
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
#define mul(a, b)
#define add(a, b)
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
Attributes are known-constant values of operations.
Definition Attributes.h:25
static BoolAttr get(MLIRContext *context, bool value)
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
IntegerType getI1Type()
Definition Builders.cpp:61
IndexType getIndexType()
Definition Builders.cpp:59
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
Location getLoc() const
Accessors for the implied location.
Definition Builders.h:665
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:466
This class represents a single result from folding an operation.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
result_range getResults()
Definition Operation.h:442
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & insert(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
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.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isIndex() const
Definition Types.cpp:56
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Specialization of arith.constant op that returns a floating point value.
Definition Arith.h:64
static ConstantFloatOp create(OpBuilder &builder, Location location, FloatType type, const APFloat &value)
Definition ArithOps.cpp:424
static bool classof(Operation *op)
Definition ArithOps.cpp:441
static void build(OpBuilder &builder, OperationState &result, FloatType type, const APFloat &value)
Build a constant float op that produces a float of the specified type.
Definition ArithOps.cpp:418
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static void build(OpBuilder &builder, OperationState &result, int64_t value)
Build a constant int op that produces an index.
Definition ArithOps.cpp:447
static bool classof(Operation *op)
Definition ArithOps.cpp:468
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
Specialization of arith.constant op that returns an integer value.
Definition Arith.h:26
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:352
static void build(OpBuilder &builder, OperationState &result, int64_t value, unsigned width)
Build a constant int op that produces an integer of the specified width.
Definition ArithOps.cpp:345
static bool classof(Operation *op)
Definition ArithOps.cpp:412
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
std::optional< TypedAttr > getNeutralElement(Operation *op)
Return the identity numeric value associated to the give op.
bool applyCmpPredicate(arith::CmpIPredicate predicate, const APInt &lhs, const APInt &rhs)
Compute lhs pred rhs, where pred is one of the known integer comparison predicates.
TypedAttr getIdentityValueAttr(AtomicRMWKind kind, Type resultType, OpBuilder &builder, Location loc, bool useOnlyFiniteValue=false)
Returns the identity value attribute associated with an AtomicRMWKind op.
Value getReductionOp(AtomicRMWKind op, OpBuilder &builder, Location loc, Value lhs, Value rhs)
Returns the value obtained by applying the reduction operation kind associated with a binary AtomicRM...
Value getIdentityValue(AtomicRMWKind op, Type resultType, OpBuilder &builder, Location loc, bool useOnlyFiniteValue=false)
Returns the identity value associated with an AtomicRMWKind op.
arith::CmpIPredicate invertPredicate(arith::CmpIPredicate pred)
Invert an integer comparison predicate.
Definition ArithOps.cpp:133
Value getZeroConstant(OpBuilder &builder, Location loc, Type type)
Creates an arith.constant operation with a zero value of type type.
Definition ArithOps.cpp:474
auto m_Val(Value v)
Definition Matchers.h:539
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
Definition UBMatchers.h:46
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
Attribute constFoldBinaryOpConditional(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Performs constant folding calculate with element-wise behavior on the two attributes in operands and ...
detail::constant_float_predicate_matcher m_NaNFloat()
Matches a constant scalar / vector splat / tensor splat float ones.
Definition Matchers.h:421
LogicalResult verifyCompatibleShapes(TypeRange types1, TypeRange types2)
Returns success if the given two arrays have the same number of elements and each pair wise entries h...
Attribute constFoldCastOp(ArrayRef< Attribute > operands, Type resType, CalculationT &&calculate)
Attribute constFoldBinaryOp(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
detail::constant_int_range_predicate_matcher m_IntRangeWithoutNegOneS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
Definition Matchers.h:471
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
detail::constant_float_predicate_matcher m_PosZeroFloat()
Matches a constant scalar / vector splat / tensor splat float positive zero.
Definition Matchers.h:404
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Definition Matchers.h:442
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
Attribute constFoldUnaryOpConditional(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Performs constant folding calculate with element-wise behavior on the one attributes in operands and ...
detail::constant_float_predicate_matcher m_AnyZeroFloat()
Matches a constant scalar / vector splat / tensor splat float (both positive and negative) zero.
Definition Matchers.h:399
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
Definition Matchers.h:478
detail::constant_float_predicate_matcher m_NegInfFloat()
Matches a constant scalar / vector splat / tensor splat float negative infinity.
Definition Matchers.h:435
detail::constant_float_predicate_matcher m_NegZeroFloat()
Matches a constant scalar / vector splat / tensor splat float negative zero.
Definition Matchers.h:409
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
Definition Matchers.h:462
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
detail::op_matcher< OpClass > m_Op()
Matches the given OpClass.
Definition Matchers.h:484
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
Attribute constFoldUnaryOp(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
detail::constant_float_predicate_matcher m_PosInfFloat()
Matches a constant scalar / vector splat / tensor splat float positive infinity.
Definition Matchers.h:427
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
detail::constant_float_predicate_matcher m_OneFloat()
Matches a constant scalar / vector splat / tensor splat float ones.
Definition Matchers.h:414
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroU()
Matches a constant scalar / vector splat / tensor splat integer or a unsigned integer range that does...
Definition Matchers.h:455
select(M, F(a0, a1, ..., a_n), F(b0, b1, ..., b_n)) -> F(select(M, a0, b0), select(M,...
LogicalResult matchAndRewrite(arith::SelectOp op, PatternRewriter &rewriter) const override
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This trait tags element-wise ops on vectors or tensors.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.
static LogicalResult ignoreValueEquivalence(Value lhs, Value rhs)
Helper that can be used with isEquivalentTo above to consider ops equivalent even if their operands a...
This represents an operation in an abstracted form, suitable for use with the builder APIs.