MLIR 24.0.0git
TosaCanonicalizations.cpp
Go to the documentation of this file.
1//===- TosaCanonicalizations.cpp - Canonicalization patterns & folders ----===//
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// \file
10// TOSA canonicalization patterns and folders.
11//
12//===----------------------------------------------------------------------===//
13
20#include "mlir/Dialect/Traits.h"
23#include "mlir/IR/IRMapping.h"
24#include "mlir/IR/Matchers.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APInt.h"
31
32#include <functional>
33
34using namespace mlir;
35using namespace mlir::tosa;
36
37namespace {
38OpFoldResult foldToInputIfTypeMatches(Type typeRef, Value input) {
39 return input.getType() == typeRef ? OpFoldResult(input) : OpFoldResult{};
40}
41} // namespace
42
43//===----------------------------------------------------------------------===//
44// Operator Canonicalizers.
45//===----------------------------------------------------------------------===//
46
47//===----------------------------------------------------------------------===//
48// Tensor Data Engine Operators.
49//===----------------------------------------------------------------------===//
50
51// Check that the zero point of the tensor and padding operations are aligned.
52static bool checkMatchingPadConstAndZp(Value padConst, Value zp) {
53 // Check that padConst is a constant value and a scalar tensor
54 DenseElementsAttr padConstAttr;
55 if (!matchPattern(padConst, m_Constant(&padConstAttr)) ||
56 (padConstAttr.size() != 1)) {
57 return false;
58 }
59
60 // Check that floating point pad is zero
61 if (auto padConstFpAttr = mlir::dyn_cast<DenseFPElementsAttr>(padConstAttr)) {
62 float padConstVal = (*padConstFpAttr.begin()).convertToFloat();
63 return padConstVal == 0.0f;
64 }
65
66 // Check that the zp and padConst align for the integer (quantized) case
67 if (auto padConstIntAttr =
68 mlir::dyn_cast<DenseIntElementsAttr>(padConstAttr)) {
70 // Check that zp is a constant value and a scalar tensor
71 if (!matchPattern(zp, m_Constant(&zpAttr)) || (padConstAttr.size() != 1)) {
72 return false;
73 }
74
75 // Check equality
76 int64_t zpVal = (*zpAttr.begin()).getSExtValue();
77 int64_t padConstVal = (*padConstIntAttr.begin()).getSExtValue();
78 return zpVal == padConstVal;
79 }
80
81 // Bail-out on unsupported type
82 return false;
83}
84
85namespace {
86template <typename OpTy>
87struct PoolPadFoldAdaptor;
88
89template <>
90struct PoolPadFoldAdaptor<tosa::MaxPool2dOp> {
91 using OpTy = tosa::MaxPool2dOp;
92 static bool checkKernelCompliance(OpTy op, const ArrayRef<int64_t> newPad) {
93 const llvm::ArrayRef<int64_t> kernel = op.getKernel();
94 if (newPad[2] >= kernel[1] || newPad[3] >= kernel[1] ||
95 newPad[0] >= kernel[0] || newPad[1] >= kernel[0])
96 return false;
97 return true;
98 }
99 static bool checkPadConstCompliance(OpTy, Value padConst) {
100 // Check that padConst is a constant value and a scalar tensor
101 DenseElementsAttr padConstAttr;
102 if (!matchPattern(padConst, m_Constant(&padConstAttr)) ||
103 padConstAttr.size() != 1) {
104 return false;
105 }
106
107 // Pad needs to be in the minimum value to be able to merge
108 if (auto padConstFpAttr =
109 mlir::dyn_cast<DenseFPElementsAttr>(padConstAttr)) {
110 const APFloat padConstVal = *padConstFpAttr.begin();
111 const APFloat lowestVal =
112 APFloat::getLargest(padConstVal.getSemantics(), true);
113 return padConstVal == lowestVal;
114 }
115 if (auto padConstIntAttr =
116 mlir::dyn_cast<DenseIntElementsAttr>(padConstAttr)) {
117 const APInt padConstVal = *padConstIntAttr.begin();
118 const unsigned int bitWidth = padConstVal.getBitWidth();
119 const APInt lowestVal =
120 padConstIntAttr.getElementType().isUnsignedInteger()
121 ? APInt::getZero(bitWidth)
122 : APInt::getSignedMinValue(bitWidth);
123 return padConstVal == lowestVal;
124 }
125
126 // Bail-out on unsupported type
127 return false;
128 }
129 static void replaceOpWithNewPad(PatternRewriter &rewriter, OpTy op,
130 Value padInput, ArrayRef<int64_t> newPad) {
131 rewriter.replaceOpWithNewOp<tosa::MaxPool2dOp>(
132 op, op.getType(), padInput, op.getKernel(), op.getStride(),
133 rewriter.getDenseI64ArrayAttr(newPad), op.getNanMode());
134 }
135};
136
137template <typename OpTy>
138struct ConvPadFoldAdaptor {
139 static bool checkKernelCompliance(OpTy, const ArrayRef<int64_t>) {
140 return true;
141 }
142 static bool checkPadConstCompliance(OpTy op, Value padConst) {
143 return checkMatchingPadConstAndZp(padConst, op.getInputZp());
144 }
145 static void replaceOpWithNewPad(PatternRewriter &rewriter, OpTy op,
146 Value padInput, ArrayRef<int64_t> newPad) {
147 rewriter.replaceOpWithNewOp<OpTy>(
148 op, op.getResult().getType(), padInput, op.getWeight(), op.getBias(),
149 op.getInputZp(), op.getWeightZp(), newPad, op.getStrideAttr(),
150 op.getDilationAttr(), op.getAccType(), op.getLocalBound());
151 }
152};
153
154// Pattern attempts to fold a `tosa.pad` operator to a following tensor
155// operation like `tosa.conv2d` by merging the padding associated with the
156// pad operator directly to the implicit padding of the tensor operation.
157// This helps eliminate the explicit padding operator if unused.
158template <typename OpTy, typename AdaptorTy>
159struct FoldPadToTensorOp : public OpRewritePattern<OpTy> {
160 using OpRewritePattern<OpTy>::OpRewritePattern;
161
162 LogicalResult matchAndRewrite(OpTy tensorOp,
163 PatternRewriter &rewriter) const override {
164 // Check producer is a tosa::PadOp
165 auto padOp = tensorOp.getInput().template getDefiningOp<tosa::PadOp>();
166 if (!padOp)
167 return rewriter.notifyMatchFailure(tensorOp,
168 "Producer must be a tosa::PadOp.");
169
170 // Validate that tensor operation has sane padding
171 const std::vector<int64_t> &tensorOpPad = tensorOp.getPad().vec();
172 if (tensorOpPad.size() != 4) // pad_top, pad_bottom, pad_left, pad_right
173 return rewriter.notifyMatchFailure(
174 tensorOp, "Tensor operation padding shall have 4 elements.");
175
176 // Validate tosa::PadOp padding
177 DenseIntElementsAttr padOpPadding;
178 if (!matchPattern(padOp.getPadding(), m_Constant(&padOpPadding))) {
179 return rewriter.notifyMatchFailure(
180 tensorOp,
181 "The `padding` input specified on the tosa::PadOp must be constant.");
182 }
183 // N_before, N_after, H_before, H_after, W_before, W_after, C_before,
184 // C_after
185 if (padOpPadding.size() != 8)
186 return rewriter.notifyMatchFailure(tensorOp,
187 "Pad padding should have 8 elements.");
188 int64_t padNBefore = (*(padOpPadding.begin() + 0)).getLimitedValue();
189 int64_t padNAfter = (*(padOpPadding.begin() + 1)).getLimitedValue();
190 int64_t padHBefore = (*(padOpPadding.begin() + 2)).getLimitedValue();
191 int64_t padHAfter = (*(padOpPadding.begin() + 3)).getLimitedValue();
192 int64_t padWBefore = (*(padOpPadding.begin() + 4)).getLimitedValue();
193 int64_t padWAfter = (*(padOpPadding.begin() + 5)).getLimitedValue();
194 int64_t padCBefore = (*(padOpPadding.begin() + 6)).getLimitedValue();
195 int64_t padCAfter = (*(padOpPadding.begin() + 7)).getLimitedValue();
196
197 if (padNBefore != 0 || padNAfter != 0 || padCBefore != 0 || padCAfter != 0)
198 return rewriter.notifyMatchFailure(
199 tensorOp, "Folding padding in N or C dimensions is not supported.");
200
201 // Fold padding from Pad into the tensor operation
202 // 4 elements - pad_top, pad_bottom, pad_left, pad_right
203 SmallVector<int64_t> foldedPad(tensorOpPad.size());
204 foldedPad[0] = padHBefore + tensorOpPad[0];
205 foldedPad[1] = padHAfter + tensorOpPad[1];
206 foldedPad[2] = padWBefore + tensorOpPad[2];
207 foldedPad[3] = padWAfter + tensorOpPad[3];
208
209 // Check kernel related restrictions
210 if (!AdaptorTy::checkKernelCompliance(tensorOp, foldedPad)) {
211 return rewriter.notifyMatchFailure(
212 tensorOp, "Padding size not aligned with kernel restrictions.");
213 }
214
215 // Check padding constant restrictions
216 if (!AdaptorTy::checkPadConstCompliance(tensorOp, padOp.getPadConst())) {
217 return rewriter.notifyMatchFailure(
218 tensorOp,
219 "Padding constant is not aligned with operator zero-point.");
220 }
221
222 // Check that padding doesn't grow more than 8K level (8192) for now
223 if (llvm::any_of(foldedPad, [](int64_t padVal) { return padVal > 8192; })) {
224 return rewriter.notifyMatchFailure(
225 tensorOp, "Padding size more than the 8K level limit.");
226 }
227
228 // Create operator
229 AdaptorTy::replaceOpWithNewPad(rewriter, tensorOp, padOp.getInput1(),
230 foldedPad);
231
232 return success();
233 }
234};
235} // namespace
236
237void Conv2DOp::getCanonicalizationPatterns(RewritePatternSet &results,
238 MLIRContext *context) {
239 results.add<
240 FoldPadToTensorOp<tosa::Conv2DOp, ConvPadFoldAdaptor<tosa::Conv2DOp>>>(
241 context);
242}
243
244void DepthwiseConv2DOp::getCanonicalizationPatterns(RewritePatternSet &results,
245 MLIRContext *context) {
246 results.add<FoldPadToTensorOp<tosa::DepthwiseConv2DOp,
247 ConvPadFoldAdaptor<tosa::DepthwiseConv2DOp>>>(
248 context);
249}
250
252 : public OpRewritePattern<tosa::AvgPool2dAdaptiveOp> {
254
255 LogicalResult matchAndRewrite(tosa::AvgPool2dAdaptiveOp op,
256 PatternRewriter &rewriter) const override {
260 if (!tosa::getConstShapeValues(op.getKernel().getDefiningOp(), kernel) ||
261 !tosa::getConstShapeValues(op.getStride().getDefiningOp(), stride) ||
262 !tosa::getConstShapeValues(op.getPad().getDefiningOp(), pad))
263 return rewriter.notifyMatchFailure(
264 op, "expected constant kernel, stride, and pad operands");
265
266 auto replacement = tosa::AvgPool2dOp::create(
267 rewriter, op.getLoc(), op.getType(), op.getInput(), op.getInputZp(),
268 op.getOutputZp(), rewriter.getDenseI64ArrayAttr(kernel),
269 rewriter.getDenseI64ArrayAttr(stride),
270 rewriter.getDenseI64ArrayAttr(pad), op.getAccTypeAttr());
271 rewriter.replaceOp(op, replacement.getOutput());
272 return success();
273 }
274};
275
276struct AvgPool2dIsNoOp : public OpRewritePattern<tosa::AvgPool2dOp> {
278
279 LogicalResult matchAndRewrite(tosa::AvgPool2dOp op,
280 PatternRewriter &rewriter) const override {
281 // Prevent canonicalization if input/output shapes don't align
282 if (op.getInput().getType() != op.getOutput().getType())
283 return rewriter.notifyMatchFailure(
284 op, "expected input and output types to match");
285
286 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
287 if (!llvm::isa<FloatType>(inputType.getElementType()))
288 return rewriter.notifyMatchFailure(op,
289 "expected floating-point input type");
290
291 // For statically known zero points, the verifier ensures zero points are
292 // zero for floating-point types
293 if (!matchPattern(op.getInputZp(), m_Constant()) ||
294 !matchPattern(op.getOutputZp(), m_Constant()))
295 return rewriter.notifyMatchFailure(
296 op,
297 "expected input and output zero points to be statically verifiable");
298
299 if (!llvm::all_of(op.getKernel(), [](int64_t val) { return val == 1; }))
300 return rewriter.notifyMatchFailure(op, "expected unit kernel");
301
302 if (!llvm::all_of(op.getStride(), [](int64_t val) { return val == 1; }))
303 return rewriter.notifyMatchFailure(op, "expected unit stride");
304
305 if (!llvm::all_of(op.getPad(), [](int64_t val) { return val == 0; }))
306 return rewriter.notifyMatchFailure(op, "expected zero padding");
307
308 rewriter.replaceOp(op, op.getInput());
309 return success();
310 }
311};
312
313void AvgPool2dOp::getCanonicalizationPatterns(RewritePatternSet &results,
314 MLIRContext *context) {
315 results.add<AvgPool2dIsNoOp>(context);
316}
317
318void AvgPool2dAdaptiveOp::getCanonicalizationPatterns(
319 RewritePatternSet &results, MLIRContext *context) {
320 results.add<AvgPool2dAdaptiveToAvgPool2d>(context);
321}
322
323struct MaxPool2dIsNoOp : public OpRewritePattern<tosa::MaxPool2dOp> {
325
326 LogicalResult matchAndRewrite(tosa::MaxPool2dOp op,
327 PatternRewriter &rewriter) const override {
328 Value input = op.getInput();
329 Value output = op.getOutput();
330 ShapedType inputType = llvm::cast<ShapedType>(input.getType());
331 ShapedType outputType = llvm::cast<ShapedType>(output.getType());
332
333 if (input.getType() == output.getType() &&
334 llvm::all_of(op.getKernel(), [](int64_t val) { return val == 1; }) &&
335 llvm::all_of(op.getStride(), [](int64_t val) { return val == 1; }) &&
336 llvm::all_of(op.getPad(), [](int64_t val) { return val == 0; }) &&
337 op.getNanMode() == tosa::NanPropagationMode::PROPAGATE) {
338 rewriter.replaceOp(op, input);
339 return success();
340 }
341
342 if (!inputType.hasStaticShape() || !outputType.hasStaticShape()) {
343 return failure();
344 }
345
346 // If the output and input shapes are 1x1, then this is a no op.
347 ArrayRef<int64_t> outputShape = outputType.getShape();
348 if (outputShape[1] != 1 || outputShape[2] != 1) {
349 return failure();
350 }
351
352 ArrayRef<int64_t> inputShape = inputType.getShape();
353 if (inputShape[1] != 1 || inputShape[2] != 1) {
354 return failure();
355 }
356
357 rewriter.replaceOp(op, input);
358 return success();
359 }
360};
361
362void MaxPool2dOp::getCanonicalizationPatterns(RewritePatternSet &results,
363 MLIRContext *context) {
364 results.add<MaxPool2dIsNoOp,
365 FoldPadToTensorOp<tosa::MaxPool2dOp,
366 PoolPadFoldAdaptor<tosa::MaxPool2dOp>>>(
367 context);
368}
369
371 : public OpRewritePattern<tosa::MaxPool2dAdaptiveOp> {
373
374 LogicalResult matchAndRewrite(tosa::MaxPool2dAdaptiveOp op,
375 PatternRewriter &rewriter) const override {
379 if (!tosa::getConstShapeValues(op.getKernel().getDefiningOp(), kernel) ||
380 !tosa::getConstShapeValues(op.getStride().getDefiningOp(), stride) ||
381 !tosa::getConstShapeValues(op.getPad().getDefiningOp(), pad))
382 return rewriter.notifyMatchFailure(
383 op, "expected constant kernel, stride, and pad operands");
384
385 auto replacement = tosa::MaxPool2dOp::create(
386 rewriter, op.getLoc(), op.getType(), op.getInput(),
387 rewriter.getDenseI64ArrayAttr(kernel),
388 rewriter.getDenseI64ArrayAttr(stride),
389 rewriter.getDenseI64ArrayAttr(pad), op.getNanModeAttr());
390 rewriter.replaceOp(op, replacement.getOutput());
391 return success();
392 }
393};
394
395void MaxPool2dAdaptiveOp::getCanonicalizationPatterns(
396 RewritePatternSet &results, MLIRContext *context) {
397 results.add<MaxPool2dAdaptiveToMaxPool2d>(context);
398}
399
400//===----------------------------------------------------------------------===//
401// Data Layout / Memory Reinterpretation.
402//===----------------------------------------------------------------------===//
403
404struct ConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
405 using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
406
407 LogicalResult matchAndRewrite(tosa::ConcatOp op,
408 PatternRewriter &rewriter) const override {
409 if (op.getInput1().size() != 1)
410 return failure();
411 if (op.getInput1().front().getType() != op.getType()) {
412 rewriter
413 .replaceOpWithNewOp<tensor::CastOp>(op, op.getType(),
414 op.getInput1().front())
415 .getResult();
416 return success();
417 }
418
419 rewriter.replaceOp(op, op.getInput1().front());
420 return success();
421 }
422};
423
424struct ConsecutiveConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
425 using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
426
427 LogicalResult matchAndRewrite(tosa::ConcatOp op,
428 PatternRewriter &rewriter) const override {
429 // Rewrite consecutive concats on the same axis into a single op.
430 // Keep track of the operands so we are able to construct a new concat
431 // later. Conservatively assume that we double the number of operands when
432 // canonicalizing
433 SmallVector<Value, 8> concatOperands;
434 concatOperands.reserve(2 * op.getNumOperands());
435
436 int32_t maxNumOperands = 0;
437 if (auto targetEnvAttr = tosa::lookupTargetEnv(op))
438 maxNumOperands =
439 getTosaLevelFromEnum(targetEnvAttr.getLevel()).MAX_TENSOR_LIST_SIZE;
440
441 // Find all operands that are foldable concats
442 bool foundRewritableConcat = false;
443 for (Value operand : op.getOperands()) {
444 concatOperands.emplace_back(operand);
445
446 auto producer = operand.getDefiningOp<tosa::ConcatOp>();
447 if (!producer)
448 continue;
449
450 // Not rewritable if axes are not the same
451 if (op.getAxis() != producer.getAxis())
452 continue;
453
454 // Replace the original operand with all incoming operands
455 foundRewritableConcat = true;
456 concatOperands.pop_back();
457 llvm::append_range(concatOperands, producer->getOperands());
458 }
459
460 if (!foundRewritableConcat)
461 return rewriter.notifyMatchFailure(op,
462 "No rewritable concat operand found.");
463
464 if (maxNumOperands > 0 &&
465 concatOperands.size() > static_cast<size_t>(maxNumOperands))
466 return rewriter.notifyMatchFailure(
467 op, "Rewriting would exceed the maximum number of operands for the "
468 "target environment level.");
469
470 rewriter.replaceOpWithNewOp<tosa::ConcatOp>(
471 op, op.getType(), concatOperands, op.getAxisAttr());
472 return success();
473 }
474};
475
476void ConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
477 MLIRContext *context) {
479}
480
481LogicalResult SelectOp::canonicalize(SelectOp op, PatternRewriter &rewriter) {
482 auto notOp = op.getInput1().getDefiningOp<tosa::LogicalNotOp>();
483 if (!notOp)
484 return failure();
485 rewriter.modifyOpInPlace(op, [&]() {
486 op.getOperation()->setOperands(
487 {notOp.getInput1(), op.getOnFalse(), op.getOnTrue()});
488 });
489 return success();
490}
491
493 : public OpRewritePattern<tosa::TransposeOp> {
495
496 LogicalResult matchAndRewrite(tosa::TransposeOp transposeOp,
497 PatternRewriter &rewriter) const override {
498 // Input is also TransposeOp - transpose(transpose(A)).
499 auto innerTranspose =
500 transposeOp.getInput1().getDefiningOp<tosa::TransposeOp>();
501 if (!innerTranspose)
502 return rewriter.notifyMatchFailure(transposeOp,
503 "input must be transpose operation");
504
505 const llvm::ArrayRef<int32_t> transposePerms = transposeOp.getPerms();
506 const llvm::ArrayRef<int32_t> innerTransposePerms =
507 innerTranspose.getPerms();
508
509 if (transposePerms.size() != innerTransposePerms.size())
510 return rewriter.notifyMatchFailure(
511 transposeOp,
512 "transpose and inner transpose perms sizes must be equal");
513 if (transposePerms.empty())
514 return rewriter.notifyMatchFailure(
515 transposeOp, "transpose perms sizes must be positive");
516
517 // Consolidate transposes into one transpose.
518 SmallVector<int32_t> perms(transposePerms.size());
519 for (int i = 0, s = transposePerms.size(); i < s; ++i)
520 perms[i] = innerTransposePerms[transposePerms[i]];
521
522 rewriter.replaceOpWithNewOp<tosa::TransposeOp>(
523 transposeOp, transposeOp.getResult().getType(),
524 innerTranspose.getInput1(), rewriter.getDenseI32ArrayAttr(perms));
525
526 return success();
527 }
528};
529
530// Determines the case when tosa.transpose is a tosa.reshape operation.
531struct TransposeIsReshape : public OpRewritePattern<tosa::TransposeOp> {
533
534 LogicalResult matchAndRewrite(tosa::TransposeOp op,
535 PatternRewriter &rewriter) const override {
536 if (op.getInput1().getDefiningOp<tosa::TransposeOp>())
537 return rewriter.notifyMatchFailure(
538 op, "Src is from transpose, can compose transposes");
539
540 Value result = op.getResult();
541 for (Operation *subop : result.getUsers()) {
542 if (isa_and_nonnull<tosa::TransposeOp>(subop))
543 return rewriter.notifyMatchFailure(
544 op, "Dest is used by transpose, can compose transposes");
545 }
546
547 auto input = op.getInput1();
548 auto inputTy = llvm::cast<ShapedType>(input.getType());
549 if (!inputTy.hasRank())
550 return rewriter.notifyMatchFailure(op, "Unranked input.");
551
552 int64_t numDynDims = 0;
553 for (int i = 0; i < inputTy.getRank(); ++i)
554 if (inputTy.isDynamicDim(i))
555 numDynDims++;
556
557 if (numDynDims > 1)
558 return rewriter.notifyMatchFailure(op, "Has more than one dynamic dim.");
559
560 const llvm::ArrayRef<int32_t> permValues = op.getPerms();
561
562 SmallVector<int64_t> nonZeroPerms;
563 nonZeroPerms.reserve(permValues.size());
564 for (auto idx : permValues) {
565 auto sz = inputTy.getDimSize(idx);
566 if (sz != 1)
567 nonZeroPerms.push_back(idx);
568 }
569
570 for (int i = 1, s = nonZeroPerms.size(); i < s; ++i)
571 if (nonZeroPerms[i - 1] > nonZeroPerms[i])
572 return rewriter.notifyMatchFailure(op,
573 "Transpose changes memory layout.");
574
575 SmallVector<int64_t> newShape;
576 newShape.reserve(inputTy.getRank());
577 for (int i = 0, s = inputTy.getRank(); i < s; ++i)
578 newShape.push_back(inputTy.getDimSize(permValues[i]));
579
580 rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
581 op, op.getType(), op.getInput1(),
582 getTosaConstShape(rewriter, op.getLoc(), newShape));
583 return success();
584 }
585};
586
587void TransposeOp::getCanonicalizationPatterns(RewritePatternSet &results,
588 MLIRContext *context) {
589 results.add<ConsolidateTransposeOptimization, TransposeIsReshape>(context);
590}
591
592struct ClampIsNoOp : public OpRewritePattern<tosa::ClampOp> {
594
595 LogicalResult matchAndRewrite(tosa::ClampOp op,
596 PatternRewriter &rewriter) const override {
597 Value input = op.getInput();
598 auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
599 auto inputElementType = inputType.getElementType();
600
601 if (isa<FloatType>(inputElementType)) {
602 // Unlike integer types, floating point types can represent infinity.
603 const auto minClamp =
604 llvm::cast<mlir::FloatAttr>(op.getMinValAttr()).getValue();
605 const auto maxClamp =
606 llvm::cast<mlir::FloatAttr>(op.getMaxValAttr()).getValue();
607 const bool isMin = minClamp.isNegInfinity();
608 const bool isMax = maxClamp.isInfinity();
609
610 if (isMin && isMax) {
611 rewriter.replaceOp(op, input);
612 return success();
613 }
614 return failure();
615 }
616
617 // i1 types are boolean in TOSA
618 const bool isBoolean = inputElementType.isInteger(1);
619 if (inputElementType.isUnsignedInteger() || isBoolean) {
620 const int64_t minClamp = llvm::cast<mlir::IntegerAttr>(op.getMinValAttr())
621 .getValue()
622 .getZExtValue();
623 const int64_t maxClamp = llvm::cast<mlir::IntegerAttr>(op.getMaxValAttr())
624 .getValue()
625 .getZExtValue();
626
627 const unsigned bitWidth = inputElementType.getIntOrFloatBitWidth();
628 const int64_t intMin = APInt::getMinValue(bitWidth).getZExtValue();
629 const int64_t intMax = APInt::getMaxValue(bitWidth).getZExtValue();
630
631 if (minClamp <= intMin && maxClamp >= intMax) {
632 rewriter.replaceOp(op, input);
633 return success();
634 }
635 return failure();
636 }
637
638 if (llvm::isa<IntegerType>(inputElementType)) {
639 const int64_t minClamp =
640 llvm::cast<mlir::IntegerAttr>(op.getMinValAttr()).getInt();
641 const int64_t maxClamp =
642 llvm::cast<mlir::IntegerAttr>(op.getMaxValAttr()).getInt();
643
644 const unsigned bitWidth = inputElementType.getIntOrFloatBitWidth();
645 const int64_t intMin = APInt::getSignedMinValue(bitWidth).getSExtValue();
646 const int64_t intMax = APInt::getSignedMaxValue(bitWidth).getSExtValue();
647
648 if (minClamp <= intMin && maxClamp >= intMax) {
649 rewriter.replaceOp(op, input);
650 return success();
651 }
652 return failure();
653 }
654
655 return failure();
656 }
657};
658
659// Attempts the following transformation:
660//
661// For integers a, b, a', and b' such that [a, b] ∩ [a', b'] ≠ ∅ and input
662// tensor X the following identity holds:
663//
664// CLAMP(CLAMP(X, a, b), a', b') = CLAMP(X, max(a, a'), min(b, b'))
665//
666// subject to the following valid NaN propagation semantics:
667// --------------------------------------------
668// | OUTER CLAMP | INNER CLAMP | RESULT MODE |
669// |-------------|--------------|-------------|
670// | PROPAGATE | PROPAGATE | PROPAGATE |
671// | PROPAGATE | IGNORE | IGNORE |
672// | IGNORE | PROPAGATE | INVALID |
673// | IGNORE | IGNORE | IGNORE |
674// |------------------------------------------|
675
676struct ClampClampOptimization : public OpRewritePattern<tosa::ClampOp> {
677 using OpRewritePattern<tosa::ClampOp>::OpRewritePattern;
678
679 // Helper structure to describe the range of a clamp operation.
680 template <typename T>
681 struct ClampRange {
682 ClampRange(const T &start, const T &end) : start(start), end(end) {}
685
686 // Helper function to determine if two Clamp ranges intersect.
687 bool intersects(const ClampRange<T> &otherRange) {
688 return start < otherRange.end && otherRange.start < end;
689 }
690 };
691
692 LogicalResult matchAndRewrite(tosa::ClampOp op,
693 PatternRewriter &rewriter) const override {
694 Value input = op.getInput();
695
696 // Check the input to the CLAMP op is itself a CLAMP.
697 auto clampOp = input.getDefiningOp<tosa::ClampOp>();
698 if (!clampOp)
699 return failure();
700
701 // Check we have a valid NaN propagation combination.
702 const auto opNanMode = op.getNanMode();
703 const auto clampNanMode = clampOp.getNanMode();
704 if (opNanMode == NanPropagationMode::IGNORE &&
705 clampNanMode == NanPropagationMode::PROPAGATE)
706 return failure();
707
708 auto maxValAttr = op.getMaxValAttr();
709 auto minValAttr = op.getMinValAttr();
710 auto clampOpMaxValAttr = clampOp.getMaxValAttr();
711 auto clampOpMinValAttr = clampOp.getMinValAttr();
712
713 auto inputEType = llvm::cast<ShapedType>(input.getType()).getElementType();
714 if (auto quantType =
715 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputEType)) {
716 inputEType = getStorageElementTypeFromQuantized(quantType);
717 }
718
719 Attribute newMinValAttr, newMaxValAttr;
720 if (mlir::isa<FloatType>(inputEType)) {
721 auto floatMaxValAttr = cast<mlir::FloatAttr>(maxValAttr);
722 auto floatMinValAttr = cast<mlir::FloatAttr>(minValAttr);
723 auto clampOpFloatMaxValAttr = cast<mlir::FloatAttr>(clampOpMaxValAttr);
724 auto clampOpFloatMinValAttr = cast<mlir::FloatAttr>(clampOpMinValAttr);
725
726 // Check we have intersecting ranges.
727 const auto opMinFloat = floatMinValAttr.getValue();
728 const auto opMaxFloat = floatMaxValAttr.getValue();
729 const auto clampOpMinFloat = clampOpFloatMinValAttr.getValue();
730 const auto clampOpMaxFloat = clampOpFloatMaxValAttr.getValue();
731 ClampRange<APFloat> opRangeFloatRange(opMinFloat, opMaxFloat);
732 ClampRange<APFloat> clampRangeFloatRange(clampOpMinFloat,
733 clampOpMaxFloat);
734 if (!opRangeFloatRange.intersects(clampRangeFloatRange))
735 return failure();
736
737 // Run the transformation.
738 auto newMinVal = std::max(opMinFloat, clampOpMinFloat);
739 auto newMaxVal = std::min(opMaxFloat, clampOpMaxFloat);
740 newMinValAttr = rewriter.getFloatAttr(inputEType, newMinVal);
741 newMaxValAttr = rewriter.getFloatAttr(inputEType, newMaxVal);
742 } else {
743 assert(mlir::isa<IntegerType>(inputEType));
744 auto intMaxValAttr = cast<mlir::IntegerAttr>(maxValAttr);
745 auto intMinValAttr = cast<mlir::IntegerAttr>(minValAttr);
746 auto clampOpIntMaxValAttr = cast<mlir::IntegerAttr>(clampOpMaxValAttr);
747 auto clampOpIntMinValAttr = cast<mlir::IntegerAttr>(clampOpMinValAttr);
748
749 if (inputEType.isUnsignedInteger()) {
750 // Check we have intersecting ranges.
751 const auto opMinInt = intMinValAttr.getUInt();
752 const auto opMaxInt = intMaxValAttr.getUInt();
753 const auto clampOpMinInt = clampOpIntMinValAttr.getUInt();
754 const auto clampOpMaxInt = clampOpIntMaxValAttr.getUInt();
755 ClampRange<std::uint64_t> opRangeIntRange(opMinInt, opMaxInt);
756 ClampRange<std::uint64_t> clampRangeIntRange(clampOpMinInt,
757 clampOpMaxInt);
758 if (!opRangeIntRange.intersects(clampRangeIntRange))
759 return failure();
760
761 // Run the transformation.
762 auto newMinVal = std::max(opMinInt, clampOpMinInt);
763 auto newMaxVal = std::min(opMaxInt, clampOpMaxInt);
764 newMinValAttr = rewriter.getIntegerAttr(inputEType, newMinVal);
765 newMaxValAttr = rewriter.getIntegerAttr(inputEType, newMaxVal);
766 } else {
767 // Check we have intersecting ranges.
768 const auto opMinInt = intMinValAttr.getInt();
769 const auto opMaxInt = intMaxValAttr.getInt();
770 const auto clampOpMinInt = clampOpIntMinValAttr.getInt();
771 const auto clampOpMaxInt = clampOpIntMaxValAttr.getInt();
772 ClampRange<std::int64_t> opRangeIntRange(opMinInt, opMaxInt);
773 ClampRange<std::int64_t> clampRangeIntRange(clampOpMinInt,
774 clampOpMaxInt);
775 if (!opRangeIntRange.intersects(clampRangeIntRange))
776 return failure();
777
778 // Run the transformation.
779 auto newMinVal = std::max(opMinInt, clampOpMinInt);
780 auto newMaxVal = std::min(opMaxInt, clampOpMaxInt);
781 newMinValAttr = rewriter.getIntegerAttr(inputEType, newMinVal);
782 newMaxValAttr = rewriter.getIntegerAttr(inputEType, newMaxVal);
783 }
784 }
785
786 auto newMode = (opNanMode != clampNanMode)
787 ? tosa::NanPropagationMode::IGNORE
788 : opNanMode;
789
790 auto newModeAttr =
791 NanPropagationModeAttr::get(rewriter.getContext(), newMode);
792
793 rewriter.replaceOpWithNewOp<tosa::ClampOp>(
794 op, op.getType(), clampOp.getInput(), newMinValAttr, newMaxValAttr,
795 newModeAttr);
796 return success();
797 }
798};
799
800void ClampOp::getCanonicalizationPatterns(RewritePatternSet &results,
801 MLIRContext *context) {
802 results.add<ClampIsNoOp>(context);
803 results.add<ClampClampOptimization>(context);
804}
805
806struct ConcatSliceOptimization : public OpRewritePattern<tosa::SliceOp> {
807 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
808
809 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
810 PatternRewriter &rewriter) const override {
811 Value sliceInput = sliceOp.getInput1();
812 auto concatOp = sliceInput.getDefiningOp<tosa::ConcatOp>();
813 if (!concatOp)
814 return rewriter.notifyMatchFailure(
815 sliceOp, "slice input must be concat operation");
816
817 OperandRange inputs = concatOp.getInput1();
818 auto concatType = dyn_cast<RankedTensorType>(concatOp.getType());
819 if (!concatType || !concatType.hasStaticShape())
820 return rewriter.notifyMatchFailure(
821 sliceOp, "slice input must be a static ranked tensor");
822 int32_t axis = concatOp.getAxis();
823
824 DenseElementsAttr startElems;
825 DenseElementsAttr sizeElems;
826
827 if (!matchPattern(sliceOp.getStart(), m_Constant(&startElems)))
828 return rewriter.notifyMatchFailure(
829 sliceOp, "start of slice must be a static ranked shape");
830
831 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems)))
832 return rewriter.notifyMatchFailure(
833 sliceOp, "size of slice must be a static ranked shape");
834
835 llvm::SmallVector<int64_t> sliceStarts =
836 llvm::to_vector(startElems.getValues<int64_t>());
837 llvm::SmallVector<int64_t> sliceSizes =
838 llvm::to_vector(sizeElems.getValues<int64_t>());
839
840 // Validate slice on the concatenated axis. Slicing along this
841 // axis should span only one of the inputs to the concatenate
842 // operation.
843 std::optional<Value> replaceWithSlice;
844 for (auto input : inputs) {
845 auto inputType = dyn_cast<RankedTensorType>(input.getType());
846 if (!inputType || !inputType.hasStaticShape())
847 return rewriter.notifyMatchFailure(
848 sliceOp, "concat input must be a static ranked tensor");
849
850 if (sliceStarts[axis] >= 0 && (sliceStarts[axis] + sliceSizes[axis]) <=
851 inputType.getDimSize(axis)) {
852 auto start_op =
853 getTosaConstShape(rewriter, sliceOp.getLoc(), sliceStarts);
854 auto size_op =
855 getTosaConstShape(rewriter, sliceOp.getLoc(), sliceSizes);
856 replaceWithSlice =
857 tosa::SliceOp::create(rewriter, sliceOp.getLoc(), sliceOp.getType(),
858 input, start_op, size_op)
859 .getResult();
860 break;
861 }
862 sliceStarts[axis] -= inputType.getDimSize(axis);
863 }
864
865 if (!replaceWithSlice)
866 return rewriter.notifyMatchFailure(
867 sliceOp, "corresponding concat input not found for slice");
868
869 rewriter.replaceOp(sliceOp, replaceWithSlice.value());
870 return success();
871 }
872};
873
874struct PadSliceOptimization : public OpRewritePattern<tosa::SliceOp> {
875 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
876
877 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
878 PatternRewriter &rewriter) const override {
879 Value sliceInput = sliceOp.getInput1();
880
881 // Check if producer is a PadOp
882 auto padOp = sliceInput.getDefiningOp<tosa::PadOp>();
883 if (!padOp)
884 return rewriter.notifyMatchFailure(sliceOp,
885 "slice input must be a pad operation");
886
887 // Check PadOp has a single consumer
888 if (!padOp->hasOneUse())
889 return rewriter.notifyMatchFailure(sliceOp,
890 "pad shall have a single consumer");
891
892 // Check input is statically ranked
893 auto inputTy = dyn_cast<RankedTensorType>(padOp.getInput1().getType());
894 auto padTy = dyn_cast<RankedTensorType>(padOp.getType());
895 if (!inputTy || !padTy || !inputTy.hasRank())
896 return rewriter.notifyMatchFailure(sliceOp,
897 "slice input must be a ranked tensor");
898
899 // Validate and extract tosa::PadOp padding
900 DenseIntElementsAttr paddingElems;
901 if (!matchPattern(padOp.getPadding(), m_Constant(&paddingElems))) {
902 return rewriter.notifyMatchFailure(
903 sliceOp,
904 "`padding` input specified on the tosa::PadOp must be constant.");
905 }
906 llvm::SmallVector<int64_t> padPaddings =
907 llvm::to_vector(paddingElems.getValues<int64_t>());
908
909 // Extract slice parameters
910 DenseElementsAttr startElems;
911 if (!matchPattern(sliceOp.getStart(), m_Constant(&startElems)))
912 return rewriter.notifyMatchFailure(
913 sliceOp, "start of slice must be a static ranked shape");
914 llvm::SmallVector<int64_t> sliceStarts =
915 llvm::to_vector(startElems.getValues<int64_t>());
916
917 DenseElementsAttr sizeElems;
918 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems)))
919 return rewriter.notifyMatchFailure(
920 sliceOp, "size of slice must be a static ranked shape");
921 llvm::SmallVector<int64_t> sliceSizes =
922 llvm::to_vector(sizeElems.getValues<int64_t>());
923
924 // Check if dynamic dimensions are sliced
925 const int64_t rank = inputTy.getRank();
926 if (llvm::any_of(llvm::seq<int64_t>(0, rank), [&](int64_t i) {
927 const bool isDimDynamic = inputTy.isDynamicDim(i);
928 const bool isDimSliced =
929 (sliceStarts[i] != 0) || (sliceSizes[i] != kInferableDimSize);
930
931 return isDimDynamic && isDimSliced;
932 })) {
933 return rewriter.notifyMatchFailure(
934 sliceOp, "axis that are sliced shall be statically known.");
935 }
936
937 // Update the parameters
938 llvm::SmallVector<int64_t> newSliceStarts(rank, 0);
939 llvm::SmallVector<int64_t> newPadPaddings(2 * rank, 0);
940 llvm::SmallVector<int64_t> newPadShape(rank, ShapedType::kDynamic);
941 bool updated = false;
942
943 for (int64_t i = 0; i < rank; ++i) {
944 const int64_t padLo = padPaddings[i * 2];
945 const int64_t padHi = padPaddings[i * 2 + 1];
946 const int64_t sliceStart = sliceStarts[i];
947 const int64_t sliceSize = sliceSizes[i];
948 const int64_t sliceEnd = sliceStart + sliceSize;
949
950 // If dimension is dynamic pass-through
951 if (inputTy.isDynamicDim(i)) {
952 newPadPaddings[i * 2] = padLo;
953 newPadPaddings[i * 2 + 1] = padHi;
954 newSliceStarts[i] = sliceStart;
955 continue;
956 }
957
958 // Handle static dimensions
959 const int64_t dimSize = inputTy.getShape()[i];
960 const int64_t dimTotal = padLo + dimSize + padHi;
961
962 // Check slice within bounds
963 if (sliceStart < 0 || sliceEnd > dimTotal)
964 return rewriter.notifyMatchFailure(sliceOp, "slice is out-of-bounds");
965
966 // Compute updated slice start parameter
967 const int64_t newSliceStart = std::max<int64_t>(sliceStart - padLo, 0);
968 newSliceStarts[i] = newSliceStart;
969 updated |= newSliceStart != sliceStart;
970
971 // Compute updated pad parameters
972 const int64_t newPadLo = std::max<int64_t>(padLo - sliceStart, 0);
973 const int64_t newPadHi =
974 std::max<int64_t>(sliceEnd - (padLo + dimSize), 0);
975 newPadPaddings[i * 2] = newPadLo;
976 newPadPaddings[i * 2 + 1] = newPadHi;
977 updated |= (newPadLo != padLo) || (newPadHi != padHi);
978
979 // Calculate new pad output shape
980 newPadShape[i] =
981 newPadPaddings[i * 2] + dimSize + newPadPaddings[i * 2 + 1];
982 }
983
984 // Check that we actually need to proceed with the rewrite
985 if (!updated)
986 return rewriter.notifyMatchFailure(
987 sliceOp, "terminate condition; nothing to rewrite");
988
989 // Create a PadOp with updated padding
990 auto newPaddingsOp =
991 getTosaConstShape(rewriter, sliceOp.getLoc(), newPadPaddings);
992 auto newPadTy =
993 RankedTensorType::get(newPadShape, inputTy.getElementType());
994 auto newPadOp = tosa::PadOp::create(rewriter, padOp.getLoc(), newPadTy,
995 padOp.getInput1(), newPaddingsOp,
996 padOp.getPadConst());
997
998 // Update SliceOp and point to new PadOp
999 auto newStartOp =
1000 getTosaConstShape(rewriter, sliceOp.getLoc(), newSliceStarts);
1001 rewriter.replaceOpWithNewOp<tosa::SliceOp>(sliceOp, sliceOp.getType(),
1002 newPadOp.getResult(), newStartOp,
1003 sliceOp.getSize());
1004
1005 return success();
1006 }
1007};
1008
1009// Update size operand of tosa.slice if size has dynamic dims but corresponding
1010// output dim is static
1012 : public OpRewritePattern<tosa::SliceOp> {
1013 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
1014
1015 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
1016 PatternRewriter &rewriter) const override {
1017 ShapedType resultType = cast<ShapedType>(sliceOp.getType());
1018 if (!resultType.hasRank())
1019 return rewriter.notifyMatchFailure(sliceOp, "output must be ranked");
1020
1021 ElementsAttr sizeElems;
1022 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems))) {
1023 return rewriter.notifyMatchFailure(
1024 sliceOp, "size of slice must be a static ranked shape");
1025 }
1026
1027 llvm::SmallVector<int64_t> sliceSizes =
1028 llvm::to_vector(sizeElems.getValues<int64_t>());
1029
1030 bool replaceSliceSize{false};
1031 // if size op has kInferableDimSize indicating dynamic shape but
1032 // corresponding dim on the output is statically known, update size to match
1033 // with known output dim shape
1034 for (const auto &[index, size] : llvm::enumerate(sliceSizes)) {
1035 if (size == kInferableDimSize && !resultType.isDynamicDim(index)) {
1036 sliceSizes[index] = resultType.getDimSize(index);
1037 replaceSliceSize = true;
1038 }
1039 }
1040
1041 if (!replaceSliceSize) {
1042 return rewriter.notifyMatchFailure(
1043 sliceOp, "no dimension of size of slice is dynamic that resolves "
1044 "to static output shape");
1045 }
1046
1047 auto size_op = getTosaConstShape(rewriter, sliceOp.getLoc(), sliceSizes);
1048 auto newSliceOp =
1049 tosa::SliceOp::create(rewriter, sliceOp.getLoc(), sliceOp.getType(),
1050 sliceOp.getInput1(), sliceOp.getStart(), size_op);
1051
1052 rewriter.replaceOp(sliceOp, newSliceOp.getResult());
1053 return success();
1054 }
1055};
1056
1057void SliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1058 MLIRContext *context) {
1059 results.add<ConcatSliceOptimization, PadSliceOptimization,
1060 SliceDynamicSizeCanonicalization>(context);
1061}
1062
1064 using OpRewritePattern<tosa::CastOp>::OpRewritePattern;
1065
1066 LogicalResult matchAndRewrite(tosa::CastOp castOp,
1067 PatternRewriter &rewriter) const override {
1068 const Value castInput = castOp.getInput();
1069 auto innerCastOp = castInput.getDefiningOp<tosa::CastOp>();
1070 if (!innerCastOp)
1071 return rewriter.notifyMatchFailure(castOp,
1072 "input must be cast operation");
1073
1074 const Value innerCastInput = innerCastOp.getInput();
1075
1076 const ShapedType innerInputType =
1077 llvm::cast<ShapedType>(innerCastInput.getType());
1078 const ShapedType innerOutputType =
1079 llvm::cast<ShapedType>(innerCastOp.getType());
1080 const ShapedType outerOutputType = llvm::cast<ShapedType>(castOp.getType());
1081
1082 const Type innerInputElemType = innerInputType.getElementType();
1083 const Type innerOutputElemType = innerOutputType.getElementType();
1084 const Type outerOutputElemType = outerOutputType.getElementType();
1085
1086 const SmallVector<Type, 3> types = {innerInputElemType, innerOutputElemType,
1087 outerOutputElemType};
1088
1089 if (llvm::any_of(types, [](const Type type) {
1090 // Support a specific set of floating point types since we need to be
1091 // careful in not introducing unsupported type combinations
1092 return !(type.isInteger() ||
1093 llvm::isa<Float8E4M3FNType, Float8E5M2Type, BFloat16Type,
1094 Float16Type, Float32Type>(type));
1095 }))
1096 return rewriter.notifyMatchFailure(
1097 castOp, "only integer and f32, f16, bf16, f8E4M3FN, f8E5M2 types are "
1098 "supported");
1099
1100 if (llvm::isa<Float8E5M2Type>(innerInputElemType) &&
1101 llvm::isa<Float8E4M3FNType>(outerOutputElemType)) {
1102 return rewriter.notifyMatchFailure(
1103 castOp, "avoid introducing f8E5M2 -> f8E4M3FN casts which are not "
1104 "legal in TOSA");
1105 }
1106
1107 if (llvm::isa<Float8E4M3FNType>(innerInputElemType) &&
1108 llvm::isa<Float8E5M2Type>(outerOutputElemType)) {
1109 return rewriter.notifyMatchFailure(
1110 castOp, "avoid introducing f8E4M3FN -> f8E5M2 casts which are not "
1111 "legal in TOSA");
1112 }
1113
1114 if (llvm::isa<Float8E5M2Type, Float8E4M3FNType>(innerInputElemType) &&
1115 outerOutputElemType.isInteger()) {
1116 return rewriter.notifyMatchFailure(
1117 castOp, "avoid introducing fp8 -> integer casts which are not "
1118 "legal in TOSA");
1119 }
1120
1121 if (innerInputElemType.isInteger() &&
1122 llvm::isa<Float8E5M2Type, Float8E4M3FNType>(outerOutputElemType)) {
1123 return rewriter.notifyMatchFailure(
1124 castOp, "avoid introducing integer -> fp8 casts which are not "
1125 "legal in TOSA");
1126 }
1127
1128 if (llvm::isa<Float16Type>(innerInputElemType) &&
1129 llvm::isa<BFloat16Type>(outerOutputElemType)) {
1130 return rewriter.notifyMatchFailure(
1131 castOp, "avoid introducing fp16 -> bf16 casts which are not "
1132 "legal in TOSA");
1133 }
1134
1135 if (llvm::isa<BFloat16Type>(innerInputElemType) &&
1136 llvm::isa<Float16Type>(outerOutputElemType)) {
1137 return rewriter.notifyMatchFailure(
1138 castOp, "avoid introducing bf16 -> fp16 casts which are not "
1139 "legal in TOSA");
1140 }
1141
1142 const auto isIntegerOneOfWidth = [](Type type, size_t bitwidth1,
1143 size_t bitwidth2) {
1144 return type.isInteger(bitwidth1) || type.isInteger(bitwidth2);
1145 };
1146
1147 if (isIntegerOneOfWidth(innerInputElemType, 8, 16) &&
1148 outerOutputElemType.isInteger(64)) {
1149 return rewriter.notifyMatchFailure(
1150 castOp, "avoid introducing i8/i16 -> i64 casts which are not "
1151 "legal in TOSA");
1152 }
1153
1154 if (isIntegerOneOfWidth(innerInputElemType, 1, 64) &&
1155 !outerOutputElemType.isInteger()) {
1156 return rewriter.notifyMatchFailure(
1157 castOp, "avoid introducing bool/i64 to float casts which are not "
1158 "supported in all versions of TOSA");
1159 }
1160
1161 if (!innerInputElemType.isInteger() &&
1162 isIntegerOneOfWidth(outerOutputElemType, 1, 64)) {
1163 return rewriter.notifyMatchFailure(
1164 castOp, "avoid introducing float to bool/i64 casts which are not "
1165 "supported in all versions of TOSA");
1166 }
1167
1168 // Check that the cast we're considering for removal is non-narrowing
1169 if (isNarrowingCast(innerInputType, innerOutputType))
1170 return rewriter.notifyMatchFailure(castOp,
1171 "inner cast operation is narrowing");
1172
1173 rewriter.replaceOpWithNewOp<tosa::CastOp>(castOp, outerOutputType,
1174 innerCastInput);
1175
1176 return success();
1177 }
1178
1179 bool supportsNaN(const llvm::fltSemantics &semantics) const {
1180 return semantics.nonFiniteBehavior !=
1181 llvm::fltNonfiniteBehavior::FiniteOnly;
1182 }
1183
1184 bool supportsInf(const llvm::fltSemantics &semantics) const {
1185 return semantics.nonFiniteBehavior == llvm::fltNonfiniteBehavior::IEEE754;
1186 }
1187
1188 bool isNarrowingCast(const ShapedType inType,
1189 const ShapedType outType) const {
1190
1191 if (inType.getElementType().isInteger() &&
1192 outType.getElementType().isInteger()) {
1193
1194 const auto inTypeSignedness =
1195 cast<IntegerType>(inType.getElementType()).getSignedness();
1196 const auto outTypeSignedness =
1197 cast<IntegerType>(outType.getElementType()).getSignedness();
1198
1199 return (inTypeSignedness != outTypeSignedness ||
1200 inType.getElementTypeBitWidth() >
1201 outType.getElementTypeBitWidth());
1202 }
1203
1204 if (inType.getElementType().isFloat() &&
1205 outType.getElementType().isFloat()) {
1206
1207 FloatType inElemTy = cast<FloatType>(inType.getElementType());
1208 FloatType outElemTy = cast<FloatType>(outType.getElementType());
1209 llvm::fltSemantics inTypeSemantics = inElemTy.getFloatSemantics();
1210 llvm::fltSemantics outTypeSemantics = outElemTy.getFloatSemantics();
1211
1212 // If the list of supported types needs to be updated in the future, the
1213 // check down below will need to be revised, for example to account for
1214 // unsigned floating point types, or types that use negative zero as the
1215 // representation for NaN.
1216 [[maybe_unused]] const auto isSupported = [](Type elemType) {
1217 return llvm::isa<Float8E4M3FNType, Float8E5M2Type, BFloat16Type,
1218 Float16Type, Float32Type>(elemType);
1219 };
1220
1221 assert(isSupported(inElemTy) &&
1222 "unsupported input element type in isNarrowingCast");
1223 assert(isSupported(outElemTy) &&
1224 "unsupported output element type in isNarrowingCast");
1225
1226 return (
1227 inTypeSemantics.maxExponent > outTypeSemantics.maxExponent ||
1228 inTypeSemantics.minExponent < outTypeSemantics.minExponent ||
1229 inTypeSemantics.precision > outTypeSemantics.precision ||
1230 (supportsNaN(inTypeSemantics) && !supportsNaN(outTypeSemantics)) ||
1231 (supportsInf(inTypeSemantics) && !supportsInf(outTypeSemantics)));
1232 }
1233
1234 // While some cases of int -> float casts can be non-narrowing, consider
1235 // them narrowing for the purposes of this optimization
1236 return true;
1237 }
1238};
1239
1241 : public OpRewritePattern<tosa::CastOp> {
1242 using OpRewritePattern<tosa::CastOp>::OpRewritePattern;
1243
1244 LogicalResult matchAndRewrite(tosa::CastOp castOp,
1245 PatternRewriter &rewriter) const override {
1246 const Value outerInput = castOp.getInput();
1247 auto innerCastOp = outerInput.getDefiningOp<tosa::CastOp>();
1248 if (!innerCastOp)
1249 return rewriter.notifyMatchFailure(castOp,
1250 "input must be a cast operation");
1251
1252 const Value innerInput = innerCastOp.getInput();
1253 const auto innerInputTy = llvm::cast<ShapedType>(innerInput.getType());
1254 const auto innerOutputTy = llvm::cast<ShapedType>(innerCastOp.getType());
1255 const auto outerOutputTy = llvm::cast<ShapedType>(castOp.getType());
1256
1257 if (!llvm::isa<tosa::BlockScaledType>(innerInputTy.getElementType()))
1258 return rewriter.notifyMatchFailure(
1259 castOp, "inner cast input must have block scaled element type");
1260
1261 if (innerInputTy != outerOutputTy)
1262 return rewriter.notifyMatchFailure(
1263 castOp, "inner input type must match outer output type");
1264
1265 const Type innerOutputElemType = innerOutputTy.getElementType();
1266 const bool isLosslessCast =
1267 isa<Float32Type, BFloat16Type>(innerOutputElemType);
1268 if (!isLosslessCast)
1269 return rewriter.notifyMatchFailure(
1270 castOp, "avoid cancelling casts that should be lossy");
1271
1272 rewriter.replaceOp(castOp, innerInput);
1273
1274 return success();
1275 }
1276};
1277
1278void CastOp::getCanonicalizationPatterns(RewritePatternSet &results,
1279 MLIRContext *context) {
1280 results.add<NonNarrowingCastsOptimization,
1281 CancellingBlockScaledCastsOptimization>(context);
1282}
1283
1285 : public OpRewritePattern<tosa::CastToBlockScaledOp> {
1286 using OpRewritePattern<tosa::CastToBlockScaledOp>::OpRewritePattern;
1287
1288 LogicalResult matchAndRewrite(tosa::CastToBlockScaledOp castToBlockScaledOp,
1289 PatternRewriter &rewriter) const override {
1290 const Value castToBlockScaledInput = castToBlockScaledOp.getInputData();
1291 auto castFromBlockScaledOp =
1292 castToBlockScaledInput.getDefiningOp<tosa::CastFromBlockScaledOp>();
1293 if (!castFromBlockScaledOp)
1294 return rewriter.notifyMatchFailure(
1295 castToBlockScaledOp,
1296 "input must be cast_from_block_scaled operation");
1297
1298 const Value innerData = castFromBlockScaledOp.getInputData();
1299 const Value innerScale = castFromBlockScaledOp.getInputScale();
1300 const auto innerDataTy = llvm::cast<ShapedType>(innerData.getType());
1301 const auto innerScaleTy = llvm::cast<ShapedType>(innerScale.getType());
1302
1303 const Value outerData = castToBlockScaledOp.getOutputData();
1304 const Value outerScale = castToBlockScaledOp.getOutputScale();
1305 const auto outerDataTy = llvm::cast<ShapedType>(outerData.getType());
1306 const auto outerScaleTy = llvm::cast<ShapedType>(outerScale.getType());
1307
1308 if (innerDataTy != outerDataTy || innerScaleTy != outerScaleTy) {
1309 return rewriter.notifyMatchFailure(
1310 castToBlockScaledOp,
1311 "inputs types to cast_from_block_scaled operation must match output "
1312 "types to cast_to_block_scaled");
1313 }
1314
1315 if (castFromBlockScaledOp.getBlockSize() !=
1316 castToBlockScaledOp.getBlockSize()) {
1317 return rewriter.notifyMatchFailure(
1318 castToBlockScaledOp, "block sizes for cast_from_block_scaled and "
1319 "cast_to_block_scaled must match");
1320 }
1321
1322 rewriter.replaceOp(castToBlockScaledOp, {innerData, innerScale});
1323
1324 return success();
1325 }
1326};
1327
1328void CastToBlockScaledOp::getCanonicalizationPatterns(
1329 RewritePatternSet &results, MLIRContext *context) {
1330 results.add<CancellingCastToFromBlockScaledOptimization>(context);
1331}
1332
1333struct RowGatherToGather : public OpRewritePattern<tosa::RowGatherOp> {
1334 using OpRewritePattern<tosa::RowGatherOp>::OpRewritePattern;
1335
1336 LogicalResult matchAndRewrite(tosa::RowGatherOp op,
1337 PatternRewriter &rewriter) const override {
1338 const FailureOr<int32_t> rowCount =
1340 if (failed(rowCount) || rowCount.value() != 1)
1341 return failure();
1342
1343 rewriter.replaceOpWithNewOp<tosa::GatherOp>(
1344 op, op.getOutput().getType(), op.getValues(), op.getIndices());
1345 return success();
1346 }
1347};
1348
1349void RowGatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
1350 MLIRContext *context) {
1351 results.add<RowGatherToGather>(context);
1352}
1353
1354//===----------------------------------------------------------------------===//
1355// Operator Folders.
1356//===----------------------------------------------------------------------===//
1357
1358template <typename Folder>
1359static DenseElementsAttr
1361 bool foldDenseValues = false) {
1362 if (!lhs || !rhs)
1363 return {};
1364
1365 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1366 return {};
1367
1368 const auto lETy = llvm::cast<ShapedType>(lhs.getType()).getElementType();
1369 const auto rETy = llvm::cast<ShapedType>(rhs.getType()).getElementType();
1370 if (lETy != rETy)
1371 return {};
1372
1373 if (lhs.isSplat() && rhs.isSplat()) {
1374 if (isa<FloatType>(lETy)) {
1375 const APFloat l = lhs.getSplatValue<APFloat>();
1376 const APFloat r = rhs.getSplatValue<APFloat>();
1377 const auto maybeResult = Folder::fold(l, r);
1378 if (failed(maybeResult))
1379 return {};
1380 return DenseElementsAttr::get(returnTy, maybeResult.value());
1381 }
1382
1383 if (const auto lIntTy = llvm::dyn_cast<IntegerType>(lETy)) {
1384 const APInt l = lhs.getSplatValue<APInt>();
1385 const APInt r = rhs.getSplatValue<APInt>();
1386 const auto maybeResult = Folder::fold(l, r, lIntTy.isUnsigned());
1387 if (failed(maybeResult))
1388 return {};
1389 return DenseElementsAttr::get(returnTy, maybeResult.value());
1390 }
1391 }
1392
1393 if (foldDenseValues) {
1394 assert(lETy.isIntOrIndex() &&
1395 "Only integer types are currently supported.");
1396 SmallVector<APInt> resultValues;
1397 for (auto [l, r] :
1398 llvm::zip(lhs.getValues<APInt>(), rhs.getValues<APInt>())) {
1399 const auto maybeResult = Folder::fold(l, r, false);
1400 if (failed(maybeResult))
1401 return {};
1402 resultValues.push_back(maybeResult.value());
1403 }
1404 return DenseElementsAttr::get(returnTy, resultValues);
1405 }
1406
1407 return {};
1408}
1409
1410template <typename Folder>
1411static DenseElementsAttr unaryFolder(DenseElementsAttr val, ShapedType returnTy,
1412 bool foldDenseValues = false) {
1413 if (!val)
1414 return {};
1415
1416 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1417 return {};
1418
1419 const auto vETy = llvm::cast<ShapedType>(val.getType()).getElementType();
1420
1421 if (val.isSplat()) {
1422 if (const auto vIntTy = llvm::dyn_cast<IntegerType>(vETy)) {
1423 const APInt v = val.getSplatValue<APInt>();
1424 const auto maybeResult = Folder::fold(v, vIntTy.isUnsigned());
1425 if (failed(maybeResult))
1426 return {};
1427 return DenseElementsAttr::get(returnTy, maybeResult.value());
1428 }
1429 }
1430
1431 if (foldDenseValues) {
1432 mlir::Type elemTy = val.getElementType();
1433 if (elemTy.isIntOrIndex()) {
1434 SmallVector<APInt> resultValues;
1435 for (auto const &v : val.getValues<APInt>()) {
1436 const auto maybeResult = Folder::fold(v, false);
1437 if (failed(maybeResult))
1438 return {};
1439 resultValues.push_back(maybeResult.value());
1440 }
1441 return DenseElementsAttr::get(returnTy, resultValues);
1442 }
1443 }
1444
1445 // Folding arbitrarily sized tensor operations is not supported
1446 return {};
1447}
1448
1449static FailureOr<int64_t> getSingleI64From1ElementTensor(Value v) {
1450 DenseIntElementsAttr dense{};
1451 if (!matchPattern(v, m_Constant(&dense)))
1452 return failure();
1453
1454 assert(dense.isSplat());
1455 APInt a = dense.getSplatValue<APInt>();
1456 return a.getSExtValue();
1457}
1458
1460 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1461 const bool isUnsigned) {
1462 bool overflow;
1463 const APInt result =
1464 isUnsigned ? lhs.uadd_ov(rhs, overflow) : lhs.sadd_ov(rhs, overflow);
1465 if (overflow)
1466 return failure();
1467 return result;
1468 }
1469
1470 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1471 return lhs + rhs;
1472 }
1473};
1474
1476 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1477 const bool isUnsigned) {
1478 bool overflow;
1479 const APInt result =
1480 isUnsigned ? lhs.usub_ov(rhs, overflow) : lhs.ssub_ov(rhs, overflow);
1481 if (overflow)
1482 return failure();
1483 return result;
1484 }
1485
1486 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1487 return lhs - rhs;
1488 }
1489};
1490
1492 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1493 const bool isUnsigned) {
1494
1495 const unsigned originalWidth = lhs.getBitWidth();
1496
1497 // Check same type
1498 if (lhs.getBitWidth() != rhs.getBitWidth()) {
1499 return failure();
1500 }
1501
1502 // If either is `0`
1503 if (lhs == 0 || rhs == 0)
1504 return APInt::getZero(originalWidth);
1505
1506 bool overflow = false;
1507 APInt const result =
1508 isUnsigned ? lhs.umul_ov(rhs, overflow) : lhs.smul_ov(rhs, overflow);
1509
1510 if (overflow)
1511 return failure();
1512
1513 return result.trunc(originalWidth);
1514 }
1515
1516 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1517 return lhs * rhs;
1518 }
1519};
1520
1521static bool signsDiffer(const APInt &a, const APInt &b) {
1522 return a.isNegative() != b.isNegative();
1523}
1524
1525template <bool Ceil>
1527 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1528 bool isUnsigned) {
1529 if (lhs.getBitWidth() != rhs.getBitWidth())
1530 return failure();
1531 if (rhs.isZero())
1532 return failure();
1533
1534 if (isUnsigned) {
1535 APInt q{};
1536 APInt r{};
1537 APInt::udivrem(lhs, rhs, q, r);
1538 if (!r.isZero() && Ceil) {
1539 return q + 1;
1540 }
1541 return q;
1542 }
1543
1544 // Signed: start from trunc-toward-zero, then adjust to ceil.
1545 bool overflow{false};
1546 APInt const q = lhs.sdiv_ov(rhs, overflow);
1547 if (overflow)
1548 return failure();
1549 APInt const r = lhs.srem(rhs);
1550
1551 if (Ceil && !r.isZero() && !signsDiffer(lhs, rhs)) {
1552 // Same sign => exact quotient is positive; trunc is below ceil =>
1553 // increment q.
1554 return q + 1;
1555 }
1556 return q;
1557 }
1558
1559 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1560 return lhs / rhs;
1561 }
1562};
1563
1565 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1566 bool isUnsigned) {
1567 if (lhs.getBitWidth() != rhs.getBitWidth())
1568 return failure();
1569 if (lhs.isNegative() || (!rhs.isStrictlyPositive()))
1570 return failure();
1571
1572 if (isUnsigned) {
1573 return lhs.urem(rhs);
1574 }
1575
1576 return lhs.srem(rhs);
1577 }
1578
1579 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1580 auto t = lhs;
1581 auto const r = t.mod(rhs);
1582 if (llvm::APFloatBase::opStatus::opOK == r) {
1583 return t;
1584 }
1585 return failure();
1586 }
1587};
1588
1590 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1591 bool isUnsigned) {
1592 if (lhs.getBitWidth() != rhs.getBitWidth())
1593 return failure();
1594 return lhs.getSExtValue() >= rhs.getSExtValue() ? lhs : rhs;
1595 }
1596
1597 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1598 return lhs >= rhs ? lhs : rhs;
1599 }
1600};
1601
1603 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1604 bool isUnsigned) {
1605 if (lhs.getBitWidth() != rhs.getBitWidth())
1606 return failure();
1607 return lhs.getSExtValue() <= rhs.getSExtValue() ? lhs : rhs;
1608 }
1609
1610 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1611 return lhs <= rhs ? lhs : rhs;
1612 }
1613};
1614
1616 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1617 auto const numBits = value.getBitWidth();
1618 if (isUnsigned) {
1619 auto const zextv = value.getZExtValue();
1620 if (zextv >= numBits)
1621 return failure();
1622 return APInt::getOneBitSet(numBits, zextv);
1623 }
1624 auto const sextv = value.getSExtValue();
1625 if (sextv < 0 || sextv >= numBits || (value.isNegative()))
1626 return failure();
1627 return APInt::getOneBitSet(numBits, sextv);
1628 }
1629};
1630
1631// The specification requires shape div operations to have non-negative lhs and
1632// strictly positive rhs so we can only fold when these conditions are met.
1633template <bool Ceil>
1635 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1636 bool isUnsigned) {
1637 assert(!isUnsigned &&
1638 "unsigned values are not supported for shape div folders");
1639 if (lhs.isNegative() || !rhs.isStrictlyPositive())
1640 return failure();
1641 return DivFoldAdaptor<Ceil>::fold(lhs, rhs, isUnsigned);
1642 }
1643
1644 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1645 return failure();
1646 }
1647};
1648
1650 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1651 if (!value.isStrictlyPositive())
1652 return failure();
1653 return APInt(/*numBits=*/value.getBitWidth(), value.ceilLogBase2());
1654 }
1655};
1656
1658 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1659 if (!value.isStrictlyPositive())
1660 return failure();
1661 return APInt(/*numBits=*/value.getBitWidth(), value.logBase2());
1662 }
1663};
1664
1666 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1667 const bool isUnsigned) {
1668 return isUnsigned ? APInt(1, lhs.ugt(rhs)) : APInt(1, lhs.sgt(rhs));
1669 }
1670
1671 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1672 return APInt(1, lhs > rhs);
1673 }
1674};
1675
1677 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1678 const bool isUnsigned) {
1679 return isUnsigned ? APInt(1, lhs.uge(rhs)) : APInt(1, lhs.sge(rhs));
1680 }
1681
1682 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1683 return APInt(1, lhs >= rhs);
1684 }
1685};
1686
1688 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1689 const bool isUnsigned) {
1690 return APInt(1, lhs == rhs);
1691 }
1692
1693 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1694 return APInt(1, lhs == rhs);
1695 }
1696};
1697
1698static bool isSplatZero(Type elemType, DenseElementsAttr val) {
1699 if (llvm::isa<FloatType>(elemType))
1700 return val && val.isSplat() && val.getSplatValue<APFloat>().isZero();
1701 if (llvm::isa<IntegerType>(elemType))
1702 return val && val.isSplat() && val.getSplatValue<APInt>().isZero();
1703 return false;
1704}
1705
1706static bool isSplatOne(Type elemType, DenseElementsAttr val, int64_t shift) {
1707 if (llvm::isa<FloatType>(elemType))
1708 return val && val.isSplat() &&
1709 val.getSplatValue<APFloat>().isExactlyValue(1.0);
1710 if (llvm::isa<IntegerType>(elemType)) {
1711 const int64_t shifted = 1LL << shift;
1712 return val && val.isSplat() &&
1713 val.getSplatValue<APInt>().getSExtValue() == shifted;
1714 }
1715 return false;
1716}
1717
1718OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
1719 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1720 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1721 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1722 if (!lhsTy || !rhsTy || !resultTy)
1723 return {};
1724
1725 // Cannot create an ElementsAttr from non-int/float/index types
1726 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1727 !rhsTy.getElementType().isIntOrIndexOrFloat())
1728 return {};
1729
1730 auto resultETy = resultTy.getElementType();
1731 auto lhsAttr =
1732 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1733 auto rhsAttr =
1734 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1735
1736 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1737 lhsTy.getShape(), rhsTy.getShape());
1738 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1739 return getInput1();
1740 if (isBroadcastable && rhsTy == resultTy && isSplatZero(resultETy, lhsAttr))
1741 return getInput2();
1742
1743 if (!lhsAttr || !rhsAttr)
1744 return {};
1745
1746 return binaryFolder<AddFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1747}
1748
1749OpFoldResult ArgMaxOp::fold(FoldAdaptor adaptor) {
1750 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput().getType());
1751 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
1752 if (!inputTy || !outputTy || !inputTy.hasStaticShape() ||
1753 !outputTy.hasStaticShape())
1754 return {};
1755
1756 const Type outputElementTy = getElementTypeOrSelf(outputTy);
1757 if (inputTy.getDimSize(getAxis()) == 1 && outputElementTy.isInteger()) {
1758 const auto outputElemIntTy = cast<IntegerType>(outputElementTy);
1759 const APInt zero = APInt::getZero(outputElemIntTy.getWidth());
1760 return DenseElementsAttr::get(outputTy, zero);
1761 }
1762
1763 return {};
1764}
1765
1766OpFoldResult IntDivOp::fold(FoldAdaptor adaptor) {
1767 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1768 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1769 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1770 if (!lhsTy || !rhsTy || !resultTy)
1771 return {};
1772 if (lhsTy.getElementType() != rhsTy.getElementType())
1773 return {};
1774
1775 // IntDivOp inputs must be integer type, no need to check for quantized
1776 // type
1777 auto resultETy = resultTy.getElementType();
1778 auto lhsAttr =
1779 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1780 auto rhsAttr =
1781 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1782 if (lhsAttr && lhsAttr.isSplat() && rhsAttr && rhsAttr.isSplat()) {
1783 if (llvm::isa<IntegerType>(resultETy) && resultTy.hasStaticShape() &&
1784 lhsAttr.getSplatValue<APInt>().isZero() &&
1785 !rhsAttr.getSplatValue<APInt>().isZero()) {
1786 return lhsAttr.resizeSplat(resultTy);
1787 }
1788 }
1789
1790 if (rhsAttr && rhsAttr.isSplat()) {
1791 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1792 lhsTy.getShape(), rhsTy.getShape());
1793 if (isBroadcastable && lhsTy == resultTy &&
1794 llvm::isa<IntegerType>(resultETy) &&
1795 rhsAttr.getSplatValue<APInt>().isOne())
1796 return getInput1();
1797 }
1798
1799 if (rhsAttr && lhsAttr && rhsAttr.isSplat() && lhsAttr.isSplat() &&
1800 llvm::isa<IntegerType>(resultETy) && resultTy.hasStaticShape()) {
1801 APInt l = lhsAttr.getSplatValue<APInt>();
1802 APInt r = rhsAttr.getSplatValue<APInt>();
1803 if (!r.isZero()) {
1804 auto intTy = dyn_cast<mlir::IntegerType>(resultETy);
1805 auto const result =
1806 DivFoldAdaptor</*Ceil*/ false>::fold(l, r, intTy.isUnsigned());
1807 if (failed(result))
1808 return {};
1809 return DenseElementsAttr::get(resultTy, result.value());
1810 }
1811 }
1812
1813 return {};
1814}
1815
1816namespace {
1817// calculate lhs * rhs >> shift according to TOSA Spec
1818// return nullopt if result is not in range of int32_t when shift > 0
1819std::optional<APInt> mulInt(APInt lhs, APInt rhs, int32_t shift,
1820 unsigned bitwidth) {
1821 bool overflow = false;
1822 APInt result = lhs.sext(64).smul_ov(rhs.sext(64), overflow);
1823
1824 if (overflow)
1825 return std::nullopt;
1826
1827 if (shift > 0) {
1828 auto round = APInt(64, 1) << (shift - 1);
1829 result += round;
1830 result.ashrInPlace(shift);
1831 // REQUIRE(product >= minimum_s<i32_t>() && product <=
1832 // maximum_s<i32_t>())
1833 if (!(result.getSExtValue() >= INT32_MIN &&
1834 result.getSExtValue() <= INT32_MAX)) {
1835 // REQUIRE failed
1836 return std::nullopt;
1837 }
1838 }
1839
1840 return result.trunc(bitwidth);
1841}
1842
1843DenseElementsAttr mulBinaryFolder(DenseElementsAttr lhs, DenseElementsAttr rhs,
1844 RankedTensorType ty, int32_t shift) {
1845 // A constant result can only be built for a statically-shaped type.
1846 if (!ty.hasStaticShape())
1847 return {};
1848 if (rhs && lhs && rhs.isSplat() && lhs.isSplat()) {
1849 if (llvm::isa<IntegerType>(ty.getElementType())) {
1850 APInt l = lhs.getSplatValue<APInt>();
1851 APInt r = rhs.getSplatValue<APInt>();
1852
1853 if (shift == 0) {
1854 return DenseElementsAttr::get(ty, l * r);
1855 }
1856
1857 auto bitwidth = ty.getElementType().getIntOrFloatBitWidth();
1858 const std::optional<APInt> result = mulInt(l, r, shift, bitwidth);
1859 if (!result)
1860 return {};
1861 return DenseElementsAttr::get(ty, result.value());
1862 }
1863
1864 if (llvm::isa<FloatType>(ty.getElementType())) {
1865 APFloat l = lhs.getSplatValue<APFloat>();
1866 APFloat r = rhs.getSplatValue<APFloat>();
1867 APFloat result = l * r;
1868 return DenseElementsAttr::get(ty, result);
1869 }
1870 }
1871
1872 return {};
1873}
1874} // namespace
1875
1876OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
1877 auto lhs = getInput1();
1878 auto rhs = getInput2();
1879 auto lhsTy = llvm::dyn_cast<RankedTensorType>(lhs.getType());
1880 auto rhsTy = llvm::dyn_cast<RankedTensorType>(rhs.getType());
1881 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1882 if (!lhsTy || !rhsTy || !resultTy)
1883 return {};
1884
1885 auto resultETy = resultTy.getElementType();
1886 auto lhsAttr =
1887 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1888 auto rhsAttr =
1889 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1890
1891 // Result right shift on i32_t data type only. For simplification,
1892 // synthesize a zero shift for other data type.
1893 int32_t shift = 0;
1894 if (resultETy.isInteger(32)) {
1895 ElementsAttr shift_elem;
1896 if (getShift().getImpl()) {
1897 if (!matchPattern(getShift(), m_Constant(&shift_elem)))
1898 // cannot be folded when the shift value is unknown.
1899 return {};
1900 shift = shift_elem.getValues<IntegerAttr>()[0].getInt();
1901 }
1902 }
1903
1904 if (rhsTy == resultTy && isSplatZero(resultETy, lhsAttr) &&
1905 resultTy.hasStaticShape())
1906 // constant values can only be resized if resulting type is static
1907 return lhsAttr.resizeSplat(resultTy);
1908 if (lhsTy == resultTy && isSplatZero(resultETy, rhsAttr) &&
1909 resultTy.hasStaticShape())
1910 return rhsAttr.resizeSplat(resultTy);
1911
1912 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1913 lhsTy.getShape(), rhsTy.getShape());
1914 if (isBroadcastable && rhsTy == resultTy &&
1915 isSplatOne(resultETy, lhsAttr, shift))
1916 return rhs;
1917 if (isBroadcastable && lhsTy == resultTy &&
1918 isSplatOne(resultETy, rhsAttr, shift))
1919 return lhs;
1920
1921 return mulBinaryFolder(lhsAttr, rhsAttr, resultTy, shift);
1922}
1923
1924OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
1925 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1926 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1927 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1928 if (!lhsTy || !rhsTy || !resultTy)
1929 return {};
1930
1931 // Cannot create an ElementsAttr from non-int/float/index types
1932 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1933 !rhsTy.getElementType().isIntOrIndexOrFloat())
1934 return {};
1935
1936 auto resultETy = resultTy.getElementType();
1937 auto lhsAttr =
1938 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1939 auto rhsAttr =
1940 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1941
1942 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1943 lhsTy.getShape(), rhsTy.getShape());
1944 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1945 return getInput1();
1946
1947 if (!lhsAttr || !rhsAttr)
1948 return {};
1949
1950 return binaryFolder<SubFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1951}
1952
1953OpFoldResult GreaterOp::fold(FoldAdaptor adaptor) {
1954 auto resultTy = llvm::cast<ShapedType>(getType());
1955 auto lhsAttr =
1956 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1957 auto rhsAttr =
1958 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1959
1960 if (!lhsAttr || !rhsAttr)
1961 return {};
1962
1963 return binaryFolder<GreaterFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1964}
1965
1966OpFoldResult GreaterEqualOp::fold(FoldAdaptor adaptor) {
1967 auto resultTy = llvm::cast<ShapedType>(getType());
1968 auto lhsAttr =
1969 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1970 auto rhsAttr =
1971 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1972
1973 if (!lhsAttr || !rhsAttr)
1974 return {};
1975
1976 return binaryFolder<GreaterEqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1977}
1978
1979OpFoldResult EqualOp::fold(FoldAdaptor adaptor) {
1980 auto resultTy = llvm::cast<ShapedType>(getType());
1981 auto lhsAttr =
1982 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1983 auto rhsAttr =
1984 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1985 Value lhs = getInput1();
1986 Value rhs = getInput2();
1987 auto lhsTy = llvm::cast<ShapedType>(lhs.getType());
1988
1989 // If we are comparing an integer value to itself it is always true. We
1990 // can not do this with float due to float values.
1991 if (llvm::isa<IntegerType>(lhsTy.getElementType()) && resultTy.hasRank() &&
1992 resultTy.hasStaticShape() && lhs == rhs) {
1993 return DenseElementsAttr::get(resultTy, true);
1994 }
1995
1996 if (!lhsAttr || !rhsAttr)
1997 return {};
1998
1999 return binaryFolder<EqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
2000}
2001
2002OpFoldResult CastOp::fold(FoldAdaptor adaptor) {
2003 if (getInput().getType() == getType())
2004 return getInput();
2005
2006 auto operand = llvm::dyn_cast_if_present<ElementsAttr>(adaptor.getInput());
2007 if (!operand)
2008 return {};
2009
2010 auto inTy = llvm::cast<ShapedType>(getInput().getType());
2011 auto outTy = llvm::cast<ShapedType>(getType());
2012 if (!outTy.hasRank() || !outTy.hasStaticShape())
2013 return {};
2014 auto inETy = inTy.getElementType();
2015 auto outETy = outTy.getElementType();
2016
2017 if (operand.isSplat()) {
2018 if (llvm::isa<FloatType>(inETy) && llvm::isa<FloatType>(outETy)) {
2019 bool overflow;
2020 auto splatVal = operand.getSplatValue<APFloat>();
2021 auto &semantics = llvm::cast<FloatType>(outETy).getFloatSemantics();
2022 splatVal.convert(semantics, llvm::RoundingMode::NearestTiesToEven,
2023 &overflow);
2024 return SplatElementsAttr::get(outTy, splatVal);
2025 }
2026
2027 if (llvm::isa<IntegerType>(inETy) && llvm::isa<FloatType>(outETy)) {
2028 auto unsign = llvm::cast<IntegerType>(inETy).isUnsignedInteger();
2029 APFloat splatVal(llvm::cast<FloatType>(outETy).getFloatSemantics());
2030 splatVal.convertFromAPInt(operand.getSplatValue<APInt>(), !unsign,
2031 llvm::RoundingMode::NearestTiesToEven);
2032 return SplatElementsAttr::get(outTy, splatVal);
2033 }
2034
2035 if (llvm::isa<FloatType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2036 auto unsign = llvm::cast<IntegerType>(outETy).isUnsignedInteger();
2037 auto intVal = APSInt(
2038 llvm::cast<IntegerType>(outETy).getIntOrFloatBitWidth(), unsign);
2039 auto floatVal = operand.getSplatValue<APFloat>();
2040 bool exact;
2041 floatVal.convertToInteger(intVal, llvm::RoundingMode::NearestTiesToEven,
2042 &exact);
2043 return SplatElementsAttr::get(outTy, intVal);
2044 }
2045
2046 if (llvm::isa<IntegerType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2047 const auto inIntType = llvm::cast<IntegerType>(inETy);
2048 auto unsignIn = inIntType.isUnsignedInteger();
2049 bool trunc =
2050 inETy.getIntOrFloatBitWidth() > outETy.getIntOrFloatBitWidth();
2051 auto intVal = operand.getSplatValue<APInt>();
2052 auto bitwidth = outETy.getIntOrFloatBitWidth();
2053
2054 // i1 types are boolean in TOSA
2055 if (outETy.isInteger(1)) {
2056 intVal = APInt(bitwidth, intVal.isZero() ? 0 : 1);
2057 } else if (trunc) {
2058 intVal = intVal.trunc(bitwidth);
2059 } else if (unsignIn || inIntType.isInteger(1)) {
2060 intVal = intVal.zext(bitwidth);
2061 } else {
2062 intVal = intVal.sext(bitwidth);
2063 }
2064
2065 return SplatElementsAttr::get(outTy, intVal);
2066 }
2067 }
2068
2069 return {};
2070}
2071
2072OpFoldResult ConstOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2073
2074OpFoldResult ConstShapeOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2075
2076#define REDUCE_FOLDER(OP) \
2077 OpFoldResult OP::fold(FoldAdaptor adaptor) { \
2078 ShapedType inputTy = llvm::cast<ShapedType>(getInput().getType()); \
2079 if (!inputTy.hasRank()) \
2080 return {}; \
2081 if (inputTy != getType()) \
2082 return {}; \
2083 if (inputTy.getRank() == 0 || inputTy.getDimSize(getAxis()) == 1) \
2084 return getInput(); \
2085 return {}; \
2086 }
2087
2088REDUCE_FOLDER(ReduceAllOp)
2089REDUCE_FOLDER(ReduceAnyOp)
2090REDUCE_FOLDER(ReduceMaxOp)
2091REDUCE_FOLDER(ReduceMinOp)
2092REDUCE_FOLDER(ReduceProductOp)
2093REDUCE_FOLDER(ReduceSumOp)
2094#undef REDUCE_FOLDER
2095
2096OpFoldResult ReshapeOp::fold(FoldAdaptor adaptor) {
2097 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2098 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2099
2100 if (!inputTy || !outputTy)
2101 return {};
2102
2103 // Fold when the input and output types are the same. This is only safe
2104 // when there is at most 1 dynamic dimension. For 2 or more dynamic
2105 // dimensions, there may still be a productive reshape.
2106 if (inputTy == outputTy && inputTy.getNumDynamicDims() < 2)
2107 return getInput1();
2108
2109 // reshape(reshape(x)) -> reshape(x)
2110 if (auto reshapeOp = llvm::dyn_cast_if_present<tosa::ReshapeOp>(
2111 getInput1().getDefiningOp())) {
2112 getInput1Mutable().assign(reshapeOp.getInput1());
2113 return getResult();
2114 }
2115
2116 // Cannot create an ElementsAttr from non-int/float/index types
2117 if (!inputTy.getElementType().isIntOrIndexOrFloat())
2118 return {};
2119
2120 // reshape(const(x)) -> const(reshape-attr(x))
2121 if (auto operand =
2122 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2123 // Constants must have static shape.
2124 if (!outputTy.hasStaticShape())
2125 return {};
2126
2127 // Okay to duplicate splat constants.
2128 if (operand.isSplat())
2129 return SplatElementsAttr::get(outputTy,
2130 operand.getSplatValue<Attribute>());
2131
2132 // Don't duplicate other constants.
2133 if (!getInput1().hasOneUse())
2134 return {};
2135
2137 if (!tosa::getConstShapeValues(getShape().getDefiningOp(), shapeVec))
2138 return {};
2139
2140 return operand.reshape(
2141 llvm::cast<ShapedType>(operand.getType()).clone(shapeVec));
2142 }
2143
2144 return {};
2145}
2146
2147OpFoldResult PadOp::fold(FoldAdaptor adaptor) {
2148 // If the pad is all zeros we can fold this operation away.
2149 if (adaptor.getPadding() && getInput1().getType() == getType()) {
2150 auto densePad = llvm::dyn_cast<DenseElementsAttr>(adaptor.getPadding());
2151 if (densePad && densePad.isSplat() &&
2152 densePad.getSplatValue<APInt>().isZero()) {
2153 return getInput1();
2154 }
2155 }
2156
2157 return {};
2158}
2159
2160// Fold away cases where a tosa.resize operation returns a copy
2161// of the input image.
2162OpFoldResult ResizeOp::fold(FoldAdaptor adaptor) {
2163 auto scaleAttr =
2164 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getScale());
2165 auto offsetAttr =
2166 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getOffset());
2167 auto borderAttr =
2168 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getBorder());
2169 if (!scaleAttr || !offsetAttr || !borderAttr) {
2170 return {};
2171 }
2172
2173 auto scale = tosa::convertFromIntAttr(scaleAttr, /* rank = */ 4);
2174 auto offset = tosa::convertFromIntAttr(offsetAttr, /* rank = */ 2);
2175 auto border = tosa::convertFromIntAttr(borderAttr, /* rank = */ 2);
2176 if (scale.size() != 4 || offset.size() != 2 || border.size() != 2) {
2177 return {};
2178 }
2179
2180 // Check unit scaling.
2181 if (scale[0] != scale[1] || scale[2] != scale[3]) {
2182 return {};
2183 }
2184
2185 // There should be no offset.
2186 if (offset[0] != 0 || offset[1] != 0) {
2187 return {};
2188 }
2189
2190 // There should be no border.
2191 if (border[0] != 0 || border[1] != 0) {
2192 return {};
2193 }
2194
2195 return foldToInputIfTypeMatches(getType(), getInput());
2196}
2197
2198OpFoldResult ReverseOp::fold(FoldAdaptor adaptor) {
2199 auto operand = getInput1();
2200 auto operandTy = llvm::cast<ShapedType>(operand.getType());
2201 auto axis = getAxis();
2202 // If the dim-length is 1, or reversing axis is unit-dim, also a no-op.
2203 const bool isSplatInput =
2204 llvm::isa_and_nonnull<SplatElementsAttr>(adaptor.getInput1());
2205 if (!operandTy.hasRank() ||
2206 (!isSplatInput && operandTy.getDimSize(axis) != 1))
2207 return {};
2208 return foldToInputIfTypeMatches(getType(), operand);
2209}
2210
2211OpFoldResult SliceOp::fold(FoldAdaptor adaptor) {
2212 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2213 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2214
2215 if (!inputTy || !outputTy)
2216 return {};
2217
2218 if (inputTy == outputTy && inputTy.hasStaticShape())
2219 return getInput1();
2220
2221 // Check if this is a no-op slice (starts at 0 and size matches input)
2222
2223 DenseElementsAttr startElems;
2224 if (!matchPattern(getStart(), m_Constant(&startElems)))
2225 return {};
2226
2227 // Check if all start values are zero
2228 bool startIsZeros =
2229 llvm::all_of(startElems.getValues<APInt>(),
2230 [](const APInt &val) { return val.isZero(); });
2231
2232 if (startIsZeros) {
2233
2234 // Check if size matches input shape
2235 DenseElementsAttr sizeElems;
2236 if (!matchPattern(getSize(), m_Constant(&sizeElems)))
2237 return {};
2238
2239 auto inputShape = inputTy.getShape();
2240 auto sizeValues = sizeElems.getValues<APInt>();
2241
2242 bool sizeMatchesInput = true;
2243 for (const auto &[i, sizeVal] : llvm::enumerate(sizeValues)) {
2244 int64_t size = sizeVal.getSExtValue();
2245
2246 if (inputTy.isDynamicDim(i)) {
2247 // For dynamic dimensions, check for kInferableDimSize indicating full
2248 // dimension is sliced
2249 if (size != kInferableDimSize) {
2250 sizeMatchesInput = false;
2251 break;
2252 }
2253 } else {
2254 // For static dimensions, check that size must match exactly or be
2255 // kInferableDimSize indicating full dimension is sliced
2256 if (size != kInferableDimSize && size != inputShape[i]) {
2257 sizeMatchesInput = false;
2258 break;
2259 }
2260 }
2261 }
2262
2263 if (sizeMatchesInput)
2264 return getInput1();
2265 }
2266
2267 // The following checks require the input to be a constant
2268 if (!adaptor.getInput1())
2269 return {};
2270
2271 // Cannot create an ElementsAttr from non-int/float/index types
2272 if (!inputTy.getElementType().isIntOrIndexOrFloat() ||
2273 !outputTy.getElementType().isIntOrIndexOrFloat())
2274 return {};
2275
2276 auto operand = llvm::cast<ElementsAttr>(adaptor.getInput1());
2277 if (operand.isSplat() && outputTy.hasStaticShape()) {
2278 return SplatElementsAttr::get(outputTy, operand.getSplatValue<Attribute>());
2279 }
2280
2281 if (inputTy.hasStaticShape() && outputTy.hasStaticShape() &&
2282 outputTy.getNumElements() == 1) {
2283 llvm::SmallVector<uint64_t> indices =
2284 llvm::to_vector(startElems.getValues<uint64_t>());
2285 if (auto values = operand.tryGetValues<Attribute>())
2286 return SplatElementsAttr::get(outputTy, (*values)[indices]);
2287 }
2288
2289 return {};
2290}
2291
2292OpFoldResult tosa::SelectOp::fold(FoldAdaptor adaptor) {
2293 const Value pred = getPred();
2294 const Value onTrue = getOnTrue();
2295 const Value onFalse = getOnFalse();
2296
2297 const auto predTy = llvm::dyn_cast<RankedTensorType>(pred.getType());
2298 const auto onTrueTy = llvm::dyn_cast<RankedTensorType>(onTrue.getType());
2299 const auto onFalseTy = llvm::dyn_cast<RankedTensorType>(onFalse.getType());
2300 if (!predTy || !onTrueTy || !onFalseTy)
2301 return {};
2302
2303 const Type resultTy = getType();
2304
2305 const ArrayRef<int64_t> predShape = predTy.getShape();
2306 const ArrayRef<int64_t> onTrueShape = onTrueTy.getShape();
2307
2308 if (onTrue == onFalse && onTrueTy == resultTy &&
2309 OpTrait::util::staticallyKnownBroadcastable(predShape, onTrueShape))
2310 return onTrue;
2311
2312 auto predicate =
2313 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getInput1());
2314 if (!predicate)
2315 return {};
2316 if (!predicate.isSplat())
2317 return {};
2318
2319 const bool predicateValue = predicate.getSplatValue<APInt>().getBoolValue();
2320
2321 SmallVector<SmallVector<int64_t>, 3> shapes;
2322 shapes.emplace_back(predShape);
2323 shapes.emplace_back(onTrueShape);
2324 shapes.emplace_back(onFalseTy.getShape());
2325 const bool isBroadcastable =
2327
2328 if (predicateValue == true && onTrueTy == resultTy && isBroadcastable)
2329 return onTrue;
2330 if (predicateValue == false && onFalseTy == resultTy && isBroadcastable)
2331 return onFalse;
2332 return {};
2333}
2334
2335static LogicalResult verifyTileIsBroadcast(tosa::TileOp tileOp) {
2336 const auto inputType =
2337 dyn_cast<RankedTensorType>(tileOp.getInput1().getType());
2338 const auto outputType = dyn_cast<RankedTensorType>(tileOp.getType());
2339 if (!inputType || !outputType)
2340 return failure();
2341
2342 SmallVector<int64_t> multiples;
2343 if (failed(tileOp.getConstantMultiples(multiples)))
2344 return failure();
2345
2346 for (const auto [index, multiple] : llvm::enumerate(multiples)) {
2347 if (multiple == 1)
2348 continue;
2349 if (outputType.isDynamicDim(index))
2350 return failure();
2351 if (inputType.getDimSize(index) != 1)
2352 return failure();
2353 }
2354
2355 return success();
2356}
2357
2359 : public OpRewritePattern<tosa::TileOp> {
2360 using OpRewritePattern<tosa::TileOp>::OpRewritePattern;
2361
2362 LogicalResult matchAndRewrite(tosa::TileOp tileOp,
2363 PatternRewriter &rewriter) const override {
2364 Value tileOutput = tileOp.getOutput();
2365 if (!tileOutput.hasOneUse())
2366 return rewriter.notifyMatchFailure(tileOp,
2367 "tile output must have one use");
2368
2369 Operation *user = *tileOutput.user_begin();
2370 const bool isBinaryElementwise =
2371 user->getNumOperands() == 2 &&
2373 if (!isBinaryElementwise && !isa<tosa::MulOp>(user))
2374 return rewriter.notifyMatchFailure(
2375 tileOp, "consumer must be binary broadcastable");
2376
2377 if (failed(verifyTileIsBroadcast(tileOp)))
2378 return rewriter.notifyMatchFailure(
2379 tileOp, "tile must only expand statically-known singleton dims");
2380
2381 Value lhsOperand = user->getOperand(0);
2382 Value rhsOperand = user->getOperand(1);
2383 Value otherOperand = lhsOperand == tileOutput ? rhsOperand : lhsOperand;
2384 Value tileInput = tileOp.getInput1();
2385
2386 const ShapedType newOtherType = cast<ShapedType>(otherOperand.getType());
2387 const ShapedType newTileType = cast<ShapedType>(tileInput.getType());
2388 SmallVector<int64_t> broadcastedShape;
2390 newOtherType.getShape(), newTileType.getShape(), broadcastedShape);
2391
2392 const ShapedType outputType = cast<ShapedType>(user->getResultTypes()[0]);
2393 if (!llvm::equal(broadcastedShape, outputType.getShape()))
2394 return rewriter.notifyMatchFailure(
2395 tileOp, "tile output must be broadcastable to consumer operands");
2396
2397 rewriter.setInsertionPoint(user);
2398 IRMapping mapper;
2399 mapper.map(tileOutput, tileOp.getInput1());
2400 Operation *newUser = rewriter.clone(*user, mapper);
2401 rewriter.replaceOp(user, newUser->getResults());
2402 return success();
2403 }
2404};
2405
2406void TileOp::getCanonicalizationPatterns(RewritePatternSet &results,
2407 MLIRContext *context) {
2408 results.add<RemoveBroadcastTileFromBinaryElementwise>(context);
2409}
2410
2411OpFoldResult TileOp::fold(FoldAdaptor adaptor) {
2412 if (getInput1().getType() == getType()) {
2413 if (auto multiples = llvm::dyn_cast_if_present<DenseElementsAttr>(
2414 adaptor.getMultiples())) {
2415 if (multiples.isSplat() &&
2416 multiples.getSplatValue<APInt>().getSExtValue() == 1)
2417 return getInput1();
2418 if (auto int_array_attr =
2419 llvm::dyn_cast<DenseIntElementsAttr>(multiples)) {
2420 if (llvm::all_of(int_array_attr.getValues<APInt>(),
2421 [](APInt v) { return v.getSExtValue() == 1; }))
2422 return getInput1();
2423 }
2424 }
2425 }
2426 return {};
2427}
2428
2429OpFoldResult TransposeOp::fold(FoldAdaptor adaptor) {
2430 auto resultTy = llvm::cast<ShapedType>(getType());
2431
2432 // Transposing splat values just means reshaping.
2433 if (auto input =
2434 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2435 if (input.isSplat() && resultTy.hasRank() && resultTy.hasStaticShape() &&
2436 input.getType().getElementType() == resultTy.getElementType())
2437 return input.reshape(resultTy);
2438 }
2439
2440 // Transpose is not the identity transpose.
2441 const llvm::ArrayRef<int32_t> perms = getPerms();
2442
2443 if (!llvm::equal(llvm::seq<int32_t>(0, perms.size()), perms))
2444 return {};
2445
2446 return foldToInputIfTypeMatches(getType(), getInput1());
2447}
2448
2449OpFoldResult tosa::NegateOp::fold(FoldAdaptor adaptor) {
2450 // Element-wise negate(negate(x)) = x
2451 // iff all zero points are constant 0
2452 auto definingOp = getInput1().getDefiningOp<tosa::NegateOp>();
2453 if (!definingOp) {
2454 // defining op of input1 is not a negate, cannot fold
2455 return {};
2456 }
2457
2458 if (FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
2459 failed(maybeIZp) || *maybeIZp != 0) {
2460 // input1 zero point is not constant 0, cannot fold
2461 return {};
2462 }
2463 if (FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
2464 failed(maybeOZp) || *maybeOZp != 0) {
2465 // output zero point is not constant 0, cannot fold
2466 return {};
2467 }
2468 if (FailureOr<int64_t> maybeIZp = definingOp.getInput1ZeroPoint();
2469 failed(maybeIZp) || *maybeIZp != 0) {
2470 // definingOp's input1 zero point is not constant 0, cannot fold
2471 return {};
2472 }
2473 if (FailureOr<int64_t> maybeOZp = definingOp.getOutputZeroPoint();
2474 failed(maybeOZp) || *maybeOZp != 0) {
2475 // definingOp's output zero point is not constant 0, cannot fold
2476 return {};
2477 }
2478
2479 return foldToInputIfTypeMatches(getType(), definingOp.getInput1());
2480}
2481
2482OpFoldResult tosa::AbsOp::fold(FoldAdaptor adaptor) {
2483 auto input = getInput1();
2484 // Element-wise abs(abs(x)) = abs(x)
2485 if (input.getDefiningOp<tosa::AbsOp>())
2486 return foldToInputIfTypeMatches(getType(), input);
2487
2488 return {};
2489}
2490
2491OpFoldResult tosa::ReciprocalOp::fold(FoldAdaptor adaptor) {
2492 auto input = adaptor.getInput1();
2493
2494 auto inputAttr = llvm::dyn_cast_if_present<DenseElementsAttr>(input);
2495 // Fold splat inputs only.
2496 if (!inputAttr || !inputAttr.isSplat())
2497 return {};
2498
2499 auto shapeType = llvm::cast<ShapedType>(getType());
2500 if (!shapeType.hasRank() || !shapeType.hasStaticShape())
2501 return {};
2502 if (auto floatType = llvm::dyn_cast<FloatType>(inputAttr.getElementType())) {
2503 auto floatVal = inputAttr.getSplatValue<APFloat>();
2504 return DenseElementsAttr::get(shapeType,
2505 ReciprocalOp::calcOneElement(floatVal));
2506 }
2507
2508 return {};
2509}
2510
2511template <typename Op, typename OpFoldAdaptor>
2513 auto input1ConstShape =
2514 dyn_cast<tosa::ConstShapeOp>(op->getInput().getDefiningOp());
2515 if (!input1ConstShape)
2516 return {};
2517
2518 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2519
2520 return unaryFolder<OpFoldAdaptor>(input1Attr, input1Attr.getType(),
2521 /*foldDenseValues=*/true);
2522}
2523
2524template <typename Op, typename OpFoldAdaptor>
2526 auto input1ConstShape =
2527 dyn_cast<tosa::ConstShapeOp>(op->getInput1().getDefiningOp());
2528 auto input2ConstShape =
2529 dyn_cast<tosa::ConstShapeOp>(op->getInput2().getDefiningOp());
2530 if (!input1ConstShape || !input2ConstShape)
2531 return {};
2532
2533 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2534 const auto input2Attr = cast<DenseElementsAttr>(input2ConstShape.getValues());
2535
2536 return binaryFolder<OpFoldAdaptor>(input1Attr, input2Attr,
2537 input1Attr.getType(),
2538 /*foldDenseValues=*/true);
2539}
2540
2541OpFoldResult tosa::DimOp::fold(FoldAdaptor adaptor) {
2542 const auto inputTy = llvm::dyn_cast<ShapedType>(getInput1().getType());
2543 if (!inputTy || !inputTy.hasRank())
2544 return {};
2545 const int32_t axis = getAxis();
2546 const int64_t dimSize = inputTy.getDimSize(axis);
2547 if (ShapedType::isDynamic(dimSize))
2548 return {};
2549
2550 OpBuilder builder(getContext());
2551 const auto resultAttrTy =
2552 RankedTensorType::get(/*rank=*/1, builder.getIndexType());
2553 return DenseElementsAttr::get(resultAttrTy, dimSize);
2554}
2555
2556OpFoldResult concatShapeFold(tosa::ConcatShapeOp *op) {
2557 auto const inputs = op->getInput();
2558
2559 if (inputs.empty())
2560 return {};
2561
2562 SmallVector<APInt> concatDims;
2563 concatDims.reserve(/*max elem*/ 64);
2564 for (auto const &v : inputs) {
2565 auto vConstShape = dyn_cast<tosa::ConstShapeOp>(v.getDefiningOp());
2566 if (!vConstShape)
2567 return {};
2568
2569 const auto vAttr = cast<DenseElementsAttr>(vConstShape.getValues());
2570 assert(vAttr);
2571
2572 auto const vAttrVals = vAttr.getValues<APInt>();
2573 for (auto const &v : vAttrVals) {
2574 concatDims.push_back(v);
2575 }
2576 }
2577
2578 auto *ctx = op->getContext();
2579 assert(ctx != nullptr && "ctx is nullptr");
2580 auto const rankedTy = RankedTensorType::get(
2581 {static_cast<int64_t>(concatDims.size())}, IndexType::get(ctx));
2582
2583 return DenseElementsAttr::get(rankedTy, concatDims);
2584}
2585
2586OpFoldResult sliceShapeFold(tosa::SliceShapeOp *op) {
2587 auto const input1 = op->getInput();
2588 auto const input2 = op->getStart();
2589 auto const input3 = op->getSize();
2590
2591 auto input1ConstShape = dyn_cast<tosa::ConstShapeOp>(input1.getDefiningOp());
2592
2593 if (!input1ConstShape)
2594 return {};
2595
2596 auto const input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2597 if (!input1Attr)
2598 return {};
2599
2600 auto const input1Vals = input1Attr.getValues<APInt>();
2601 auto const totalInput1 = input1Vals.size();
2602
2603 auto const start = getSingleI64From1ElementTensor(input2);
2604 auto const size = getSingleI64From1ElementTensor(input3);
2605
2606 if (failed(start) || failed(size))
2607 return {};
2608
2609 auto const startV = static_cast<int32_t>(start.value());
2610 auto const sizeV = static_cast<int32_t>(size.value());
2611
2612 if ((sizeV <= 0) || (startV < 0) ||
2613 (static_cast<size_t>(startV + sizeV) > totalInput1))
2614 return {};
2615
2616 SmallVector<APInt> sliceOfInput;
2617 sliceOfInput.reserve(totalInput1);
2618
2619 for (auto i = startV; i < (startV + sizeV); i++) {
2620 sliceOfInput.push_back(input1Vals[i]);
2621 }
2622
2623 auto *ctx = op->getContext();
2624 assert(ctx != nullptr && "ctx is nullptr");
2625
2626 auto const rankedTy = RankedTensorType::get(
2627 {static_cast<int64_t>(sliceOfInput.size())}, IndexType::get(ctx));
2628
2629 return DenseElementsAttr::get(rankedTy, sliceOfInput);
2630}
2631
2632OpFoldResult tosa::AddShapeOp::fold(FoldAdaptor adaptor) {
2634}
2635
2636OpFoldResult tosa::SubShapeOp::fold(FoldAdaptor adaptor) {
2638}
2639
2640OpFoldResult tosa::MulShapeOp::fold(FoldAdaptor adaptor) {
2642}
2643
2644OpFoldResult tosa::DivCeilShapeOp::fold(FoldAdaptor adaptor) {
2645 return binaryFold<DivCeilShapeOp, ShapeDivFoldAdaptor</*Ceil*/ true>>(this);
2646}
2647
2648OpFoldResult tosa::DivFloorShapeOp::fold(FoldAdaptor adaptor) {
2649 return binaryFold<DivFloorShapeOp, ShapeDivFoldAdaptor</*Ceil*/ false>>(this);
2650}
2651
2652OpFoldResult tosa::ModShapeOp::fold(FoldAdaptor adaptor) {
2654}
2655
2656OpFoldResult tosa::MaxShapeOp::fold(FoldAdaptor adaptor) {
2658}
2659
2660OpFoldResult tosa::MinShapeOp::fold(FoldAdaptor adaptor) {
2662}
2663
2664OpFoldResult tosa::Exp2ShapeOp::fold(FoldAdaptor adaptor) {
2666}
2667
2668OpFoldResult tosa::Log2CeilShapeOp::fold(FoldAdaptor adaptor) {
2670}
2671
2672OpFoldResult tosa::Log2FloorShapeOp::fold(FoldAdaptor adaptor) {
2674}
2675
2676OpFoldResult tosa::ConcatShapeOp::fold(FoldAdaptor adaptor) {
2677 return concatShapeFold(this);
2678}
2679
2680OpFoldResult tosa::SliceShapeOp::fold(FoldAdaptor adaptor) {
2681 return sliceShapeFold(this);
2682}
return success()
static bool isSplatZero(Type elemType, DenseElementsAttr val)
Returns true if 'val' is a splat of zero, false otherwise.
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
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 the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
#define REDUCE_FOLDER(OP)
OpFoldResult concatShapeFold(tosa::ConcatShapeOp *op)
static DenseElementsAttr binaryFolder(DenseElementsAttr lhs, DenseElementsAttr rhs, ShapedType returnTy, bool foldDenseValues=false)
static DenseElementsAttr unaryFolder(DenseElementsAttr val, ShapedType returnTy, bool foldDenseValues=false)
static LogicalResult verifyTileIsBroadcast(tosa::TileOp tileOp)
OpFoldResult sliceShapeFold(tosa::SliceShapeOp *op)
static FailureOr< int64_t > getSingleI64From1ElementTensor(Value v)
OpFoldResult binaryFold(Op *op)
static bool isSplatOne(Type elemType, DenseElementsAttr val, int64_t shift)
OpFoldResult unaryShapeFold(Op *op)
static bool checkMatchingPadConstAndZp(Value padConst, Value zp)
static bool signsDiffer(const APInt &a, const APInt &b)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
Attributes are known-constant values of operations.
Definition Attributes.h:25
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
MLIRContext * getContext() const
Definition Builders.h:56
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
int64_t size() const
Returns the number of elements held by this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
Type getElementType() const
Return the element type of this DenseElementsAttr.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
An attribute that represents a reference to a dense integer vector or tensor object.
iterator begin() const
Iterator access to the integer element values.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
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:571
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
This class represents a single result from folding an operation.
This class indicates that an op is tosa-elementwise (permits broadcasting, unlike Elementwise trait).
Definition TosaOps.h:61
This provides public APIs that all operations should have.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:774
unsigned getNumOperands()
Definition Operation.h:371
result_type_range getResultTypes()
Definition Operation.h:453
result_range getResults()
Definition Operation.h:440
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
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...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
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
user_iterator user_begin() const
Definition Value.h:216
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
bool staticallyKnownBroadcastable(ArrayRef< SmallVector< int64_t, 6 > > shapes)
Returns true if a broadcast between n shapes is guaranteed to be successful and not result in an erro...
Definition Traits.cpp:24
bool getBroadcastedShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2, SmallVectorImpl< int64_t > &resultShape)
Returns true and sets resultShape to the broadcasted shape from the two given shapes if they are broa...
Definition Traits.cpp:59
DynamicAPInt round(const Fraction &f)
Definition Fraction.h:136
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
TosaLevel getTosaLevelFromEnum(const Level level)
Definition TargetEnv.cpp:15
constexpr int64_t kInferableDimSize
Represents a dimension in the shape of a tensor that can be inferred based on the other provided dime...
Definition TosaOps.h:100
SmallVector< int64_t > convertFromIntAttr(const DenseElementsAttr &attr, const int rank)
TargetEnvAttr lookupTargetEnv(Operation *op)
FailureOr< T > getConstantScalarIntValue(Value val)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
Type getStorageElementTypeFromQuantized(quant::QuantizedType quantizedType)
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
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
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:307
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::AvgPool2dAdaptiveOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::AvgPool2dOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::CastOp castOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::CastToBlockScaledOp castToBlockScaledOp, PatternRewriter &rewriter) const override
bool intersects(const ClampRange< T > &otherRange)
ClampRange(const T &start, const T &end)
LogicalResult matchAndRewrite(tosa::ClampOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::ClampOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::ConcatOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::ConcatOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::TransposeOp transposeOp, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::MaxPool2dAdaptiveOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::MaxPool2dOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
bool isNarrowingCast(const ShapedType inType, const ShapedType outType) const
LogicalResult matchAndRewrite(tosa::CastOp castOp, PatternRewriter &rewriter) const override
bool supportsInf(const llvm::fltSemantics &semantics) const
bool supportsNaN(const llvm::fltSemantics &semantics) const
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::TileOp tileOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::RowGatherOp op, PatternRewriter &rewriter) const override
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
LogicalResult matchAndRewrite(tosa::TransposeOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
int32_t MAX_TENSOR_LIST_SIZE
Definition TargetEnv.h:30