MLIR 24.0.0git
TosaToLinalg.cpp
Go to the documentation of this file.
1//===- TosaToLinalg.cpp - Lowering Tosa to Linalg Dialect -----------------===//
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// These rewriters lower from the Tosa to the Linalg dialect.
10//
11//===----------------------------------------------------------------------===//
12
14#include "TosaToLinalgUtils.h"
26#include "mlir/IR/Matchers.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Sequence.h"
32#include "llvm/ADT/SmallVectorExtras.h"
33
34#include <type_traits>
35
36using namespace mlir;
37using namespace mlir::tosa;
38
39template <typename OpTy>
41 TypeRange resultTypes,
42 ValueRange operands) {
43 typename OpTy::Properties properties{};
44 OpTy::populateDefaultProperties(
45 OperationName(OpTy::getOperationName(), builder.getContext()),
46 properties);
47 return OpTy::create(builder, loc, resultTypes, operands, properties,
48 /*discardableAttributes=*/{});
49}
50
51// Helper function to materialize the semantically correct compare and select
52// operations given a binary operation with a specific NaN propagation mode.
53//
54// In the case of "PROPAGATE" semantics no compare and selection is required and
55// this function does nothing.
56//
57// In the case of "IGNORE" semantics this function materializes a comparison of
58// the current operands to the op which will return true for any NaN
59// argument and then selects between the non-NaN operation argument and the
60// calculated result based on whether the lhs or rhs is NaN or not. In pseudo
61// code:
62//
63// In the case that the op is operating on non floating point types we ignore
64// the attribute completely, this is consistent with the TOSA spec which has
65// the following wording: "This attribute is ignored by non floating-point
66// types."
67//
68// binary<op>(lhs, rhs):
69// result = op(lhs, rhs)
70// if lhs == NaN return rhs
71// if rhs == NaN return lhs
72// return result
73template <typename OpTy>
74static Value
76 Value lhs, Value rhs, Value result) {
77 // NaN propagation has no meaning for non floating point types.
78 if (!isa<FloatType>(getElementTypeOrSelf(lhs)))
79 return result;
80
81 auto nanMode = op.getNanMode();
82 if (nanMode == NanPropagationMode::PROPAGATE)
83 return result;
84
85 // Unordered comparison of NaN against itself will always return true.
86 Value lhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
87 arith::CmpFPredicate::UNO, lhs, lhs);
88 Value rhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
89 arith::CmpFPredicate::UNO, rhs, rhs);
90 Value rhsOrResult =
91 arith::SelectOp::create(rewriter, op.getLoc(), lhsIsNaN, rhs, result);
92 return arith::SelectOp::create(rewriter, op.getLoc(), rhsIsNaN, lhs,
93 rhsOrResult);
94}
95
97 Operation *op, ValueRange args, ArrayRef<Type> resultTypes,
98 ConversionPatternRewriter &rewriter) {
99 Location loc = op->getLoc();
100 auto elementTy =
101 cast<ShapedType>(op->getOperand(0).getType()).getElementType();
102
103 // tosa::AbsOp
104 if (isa<tosa::AbsOp>(op) && isa<FloatType>(elementTy))
105 return createWithDefaultProperties<math::AbsFOp>(rewriter, loc, resultTypes,
106 args);
107
108 if (isa<tosa::AbsOp>(op) && isa<IntegerType>(elementTy)) {
109 auto zero = arith::ConstantOp::create(rewriter, loc,
110 rewriter.getZeroAttr(elementTy));
111 auto neg = arith::SubIOp::create(rewriter, loc, zero, args[0]);
112 return arith::MaxSIOp::create(rewriter, loc, args[0], neg);
113 }
114
115 // tosa::AddOp
116 if (isa<tosa::AddOp>(op) && isa<FloatType>(elementTy))
118 resultTypes, args);
119
120 if (isa<tosa::AddOp>(op) && isa<IntegerType>(elementTy))
122 resultTypes, args);
123
124 // tosa::SubOp
125 if (isa<tosa::SubOp>(op) && isa<FloatType>(elementTy))
127 resultTypes, args);
128
129 if (isa<tosa::SubOp>(op) && isa<IntegerType>(elementTy))
131 resultTypes, args);
132
133 // tosa::IntDivOp
134 if (isa<tosa::IntDivOp>(op) && isa<IntegerType>(elementTy))
136 resultTypes, args);
137
138 // tosa::ReciprocalOp
139 if (isa<tosa::ReciprocalOp>(op) && isa<FloatType>(elementTy)) {
140 auto one =
141 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
142 return arith::DivFOp::create(rewriter, loc, one, args[0]);
143 }
144
145 // tosa::MulOp
146 if (isa<tosa::MulOp>(op)) {
147 auto shiftVal = cast<tosa::MulOp>(op).getShift();
148 DenseElementsAttr shiftElem;
149 bool shiftIsConstant = true;
150 int32_t shift = 0;
151 if (matchPattern(shiftVal, m_Constant(&shiftElem)))
152 shift = shiftElem.getValues<IntegerAttr>()[0].getInt();
153 else
154 shiftIsConstant = false;
155
156 if (isa<FloatType>(elementTy)) {
157 if (shift != 0) {
158 (void)rewriter.notifyMatchFailure(op,
159 "Cannot have shift value for float");
160 return nullptr;
161 }
162 return arith::MulFOp::create(rewriter, loc, args[0], args[1]);
163 }
164
165 if (isa<IntegerType>(elementTy)) {
166 Value a = args[0];
167 Value b = args[1];
168
169 if (shift > 0 || !shiftIsConstant) {
170 Value shiftConst;
171 if (shiftIsConstant)
172 shiftConst = arith::ConstantIntOp::create(rewriter, loc, shift,
173 /*bitwidth=*/8);
174
175 if (!a.getType().isInteger(32))
176 a = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), a);
177
178 if (!b.getType().isInteger(32))
179 b = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), b);
180
181 auto shiftAmount = shiftIsConstant ? shiftConst : args[2];
182 auto roundingAttr = RoundingModeAttr::get(rewriter.getContext(),
183 RoundingMode::SINGLE_ROUND);
184 auto result =
185 tosa::ApplyScaleOp::create(rewriter, loc, rewriter.getI32Type(), a,
186 b, shiftAmount, roundingAttr);
187
188 return result;
189 }
190
191 int aWidth = a.getType().getIntOrFloatBitWidth();
192 int bWidth = b.getType().getIntOrFloatBitWidth();
193 int cWidth = resultTypes[0].getIntOrFloatBitWidth();
194
195 if (aWidth < cWidth)
196 a = arith::ExtSIOp::create(rewriter, loc, resultTypes[0], a);
197 if (bWidth < cWidth)
198 b = arith::ExtSIOp::create(rewriter, loc, resultTypes[0], b);
199
200 return arith::MulIOp::create(rewriter, loc, resultTypes, a, b);
201 }
202 }
203
204 // tosa::NegateOp
205 if (isa<tosa::NegateOp>(op)) {
206 auto negate = cast<tosa::NegateOp>(op);
207
208 int64_t inZp = 0, outZp = 0;
209 FailureOr<int64_t> maybeInZp = negate.getInput1ZeroPoint();
210 FailureOr<int64_t> maybeOutZp = negate.getOutputZeroPoint();
211 bool hasInZp = !failed(maybeInZp);
212 bool hasOutZp = !failed(maybeOutZp);
213 if (hasInZp)
214 inZp = *maybeInZp;
215 if (hasOutZp)
216 outZp = *maybeOutZp;
217
218 if (isa<FloatType>(elementTy))
219 return arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
220
221 if (isa<IntegerType>(elementTy)) {
222 Value zpAddValue;
223 Type intermediateType;
224 // Compute the maximum value that can occur in the intermediate buffer.
225 const int32_t inputBitWidth = elementTy.getIntOrFloatBitWidth();
226 int intermediateBitWidth = 64;
227
228 if (hasInZp && hasOutZp) {
229 // Compute the maximum value that can occur in the intermediate buffer.
230 // Zero points can only be non-zero for int8, so their sum fits in
231 // int64_t. The bound is computed with 128 bits so that it cannot
232 // overflow for 64-bit inputs.
233 const int64_t zpAdd = inZp + outZp;
234 const APInt maxValue =
235 APInt::getSignedMaxValue(inputBitWidth).sext(128) +
236 std::abs(zpAdd) + 1;
237
238 // Convert that maximum value into the maximum bitwidth needed to
239 // represent it.
240 if (maxValue.sle(APInt::getSignedMaxValue(16).getSExtValue())) {
241 intermediateBitWidth = 16;
242 } else if (maxValue.sle(APInt::getSignedMaxValue(32).getSExtValue())) {
243 intermediateBitWidth = 32;
244 }
245
246 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
247 zpAddValue = arith::ConstantOp::create(
248 rewriter, loc, rewriter.getIntegerAttr(intermediateType, zpAdd));
249 } else {
250 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
251 Value arg1 = args[1];
252 Value arg2 = args[2];
253 // Avoid verifier-invalid no-op sign-extends; only widen when needed.
254 if (arg1.getType() != intermediateType)
255 arg1 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg1);
256 if (arg2.getType() != intermediateType)
257 arg2 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg2);
258 zpAddValue =
259 arith::AddIOp::create(rewriter, loc, intermediateType, arg1, arg2);
260 }
261
262 // The negation can be applied by doing:
263 // outputValue = inZp + outZp - inputValue
264 Value ext = args[0];
265 if (ext.getType() != intermediateType)
266 ext = arith::ExtSIOp::create(rewriter, loc, intermediateType, ext);
267 auto sub = arith::SubIOp::create(rewriter, loc, zpAddValue, ext);
268
269 // Clamp to the negation range.
271 rewriter, loc, intermediateType,
272 APInt::getSignedMinValue(inputBitWidth).getSExtValue());
274 rewriter, loc, intermediateType,
275 APInt::getSignedMaxValue(inputBitWidth).getSExtValue());
276 auto clamp = clampIntHelper(loc, sub, min, max, rewriter, false);
277
278 // Truncate to the final value, skipping no-op trunci when widths match.
279 if (clamp.getType() == elementTy)
280 return clamp;
281 return arith::TruncIOp::create(rewriter, loc, elementTy, clamp);
282 }
283 }
284
285 // tosa::BitwiseAndOp
286 if (isa<tosa::BitwiseAndOp>(op) && isa<IntegerType>(elementTy))
287 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
288
289 // tosa::BitwiseOrOp
290 if (isa<tosa::BitwiseOrOp>(op) && isa<IntegerType>(elementTy))
291 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
292
293 // tosa::BitwiseNotOp
294 if (isa<tosa::BitwiseNotOp>(op) && isa<IntegerType>(elementTy)) {
295 auto allOnesAttr = rewriter.getIntegerAttr(
296 elementTy, APInt::getAllOnes(elementTy.getIntOrFloatBitWidth()));
297 auto allOnes = arith::ConstantOp::create(rewriter, loc, allOnesAttr);
298 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], allOnes);
299 }
300
301 // tosa::BitwiseXOrOp
302 if (isa<tosa::BitwiseXorOp>(op) && isa<IntegerType>(elementTy))
303 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
304
305 // tosa::LogicalLeftShiftOp
306 if (isa<tosa::LogicalLeftShiftOp>(op) && isa<IntegerType>(elementTy))
308 resultTypes, args);
309
310 // tosa::LogicalRightShiftOp
311 if (isa<tosa::LogicalRightShiftOp>(op) && isa<IntegerType>(elementTy))
313 resultTypes, args);
314
315 // tosa::ArithmeticRightShiftOp
316 if (isa<tosa::ArithmeticRightShiftOp>(op) && isa<IntegerType>(elementTy)) {
318 rewriter, loc, resultTypes, args);
319 bool round = cast<tosa::ArithmeticRightShiftOp>(op).getRound();
320 if (!round) {
321 return result;
322 }
323
324 Type i1Ty = IntegerType::get(rewriter.getContext(), /*width=*/1);
325 auto one = arith::ConstantOp::create(rewriter, loc,
326 IntegerAttr::get(elementTy, 1));
327 auto zero = arith::ConstantOp::create(rewriter, loc,
328 IntegerAttr::get(elementTy, 0));
329 auto i1zero =
330 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 0));
331 auto i1one =
332 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 1));
333
334 // Checking that input2 != 0
335 auto shiftValueGreaterThanZero = arith::CmpIOp::create(
336 rewriter, loc, arith::CmpIPredicate::sgt, args[1], zero);
337
338 // Checking for the last bit of input1 to be 1
339 auto subtract =
340 arith::SubIOp::create(rewriter, loc, resultTypes, args[1], one);
341 auto shifted =
342 arith::ShRSIOp::create(rewriter, loc, resultTypes, args[0], subtract)
343 ->getResults();
345 rewriter, loc, TypeRange{i1Ty}, shifted);
346 auto isInputOdd =
347 arith::AndIOp::create(rewriter, loc, i1Ty, truncated, i1one);
348 // shifted, truncated, isInputOdd can be poison when input2 is 0.
349 auto shouldRound = arith::SelectOp::create(
350 rewriter, loc, i1Ty, shiftValueGreaterThanZero, isInputOdd, i1zero);
351 auto extended =
352 arith::ExtUIOp::create(rewriter, loc, resultTypes, shouldRound);
353 return arith::AddIOp::create(rewriter, loc, resultTypes, result, extended);
354 }
355
356 // tosa::ClzOp
357 if (isa<tosa::ClzOp>(op) && isa<IntegerType>(elementTy)) {
358 return math::CountLeadingZerosOp::create(rewriter, loc, elementTy, args[0]);
359 }
360
361 // tosa::LogicalAnd
362 if (isa<tosa::LogicalAndOp>(op) && elementTy.isInteger(1))
363 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
364
365 // tosa::LogicalNot
366 if (isa<tosa::LogicalNotOp>(op) && elementTy.isInteger(1)) {
367 auto one = arith::ConstantOp::create(rewriter, loc,
368 rewriter.getIntegerAttr(elementTy, 1));
369 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], one);
370 }
371
372 // tosa::LogicalOr
373 if (isa<tosa::LogicalOrOp>(op) && elementTy.isInteger(1))
374 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
375
376 // tosa::LogicalXor
377 if (isa<tosa::LogicalXorOp>(op) && elementTy.isInteger(1))
378 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
379
380 // tosa::PowOp
381 if (isa<tosa::PowOp>(op) && isa<FloatType>(elementTy))
383 resultTypes, args);
384
385 // tosa::RsqrtOp
386 if (isa<tosa::RsqrtOp>(op) && isa<FloatType>(elementTy))
388 resultTypes, args);
389
390 // tosa::LogOp
391 if (isa<tosa::LogOp>(op) && isa<FloatType>(elementTy))
393 resultTypes, args);
394
395 // tosa::ExpOp
396 if (isa<tosa::ExpOp>(op) && isa<FloatType>(elementTy))
398 resultTypes, args);
399
400 // tosa::SinOp
401 if (isa<tosa::SinOp>(op) && isa<FloatType>(elementTy))
403 resultTypes, args);
404
405 // tosa::CosOp
406 if (isa<tosa::CosOp>(op) && isa<FloatType>(elementTy))
408 resultTypes, args);
409
410 // tosa::TanhOp
411 if (isa<tosa::TanhOp>(op) && isa<FloatType>(elementTy))
413 resultTypes, args);
414
415 // tosa::ErfOp
416 if (isa<tosa::ErfOp>(op) && llvm::isa<FloatType>(elementTy))
418 resultTypes, args);
419
420 // tosa::GreaterOp
421 if (isa<tosa::GreaterOp>(op) && isa<FloatType>(elementTy))
422 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGT,
423 args[0], args[1]);
424
425 if (isa<tosa::GreaterOp>(op) && elementTy.isSignlessInteger())
426 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sgt,
427 args[0], args[1]);
428
429 // tosa::GreaterEqualOp
430 if (isa<tosa::GreaterEqualOp>(op) && isa<FloatType>(elementTy))
431 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGE,
432 args[0], args[1]);
433
434 if (isa<tosa::GreaterEqualOp>(op) && elementTy.isSignlessInteger())
435 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sge,
436 args[0], args[1]);
437
438 // tosa::EqualOp
439 if (isa<tosa::EqualOp>(op) && isa<FloatType>(elementTy))
440 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OEQ,
441 args[0], args[1]);
442
443 if (isa<tosa::EqualOp>(op) && elementTy.isSignlessInteger())
444 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
445 args[0], args[1]);
446
447 // tosa::SelectOp
448 if (isa<tosa::SelectOp>(op)) {
449 elementTy = cast<ShapedType>(op->getOperand(1).getType()).getElementType();
450 if (isa<FloatType>(elementTy) || isa<IntegerType>(elementTy))
451 return arith::SelectOp::create(rewriter, loc, args[0], args[1], args[2]);
452 }
453
454 // tosa::MaximumOp
455 if (isa<tosa::MaximumOp>(op) && isa<FloatType>(elementTy)) {
456 auto max = arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
457 return materializeBinaryNanCheckIfRequired(llvm::cast<tosa::MaximumOp>(op),
458 rewriter, args[0], args[1], max);
459 }
460
461 if (isa<tosa::MaximumOp>(op) && elementTy.isSignlessInteger()) {
462 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
463 }
464
465 // tosa::MinimumOp
466 if (isa<tosa::MinimumOp>(op) && isa<FloatType>(elementTy)) {
467 auto min = arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
468 return materializeBinaryNanCheckIfRequired(llvm::cast<tosa::MinimumOp>(op),
469 rewriter, args[0], args[1], min);
470 }
471
472 if (isa<tosa::MinimumOp>(op) && elementTy.isSignlessInteger()) {
473 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
474 }
475
476 // tosa::CeilOp
477 if (isa<tosa::CeilOp>(op) && isa<FloatType>(elementTy))
478 return createWithDefaultProperties<math::CeilOp>(rewriter, loc, resultTypes,
479 args);
480
481 // tosa::FloorOp
482 if (isa<tosa::FloorOp>(op) && isa<FloatType>(elementTy))
484 resultTypes, args);
485
486 // tosa::ClampOp
487 if (isa<tosa::ClampOp>(op) && isa<FloatType>(elementTy)) {
488 bool losesInfo = false;
489 auto clampOp = cast<tosa::ClampOp>(op);
490 APFloat minApf = cast<FloatAttr>(clampOp.getMinValAttr()).getValue();
491 APFloat maxApf = cast<FloatAttr>(clampOp.getMaxValAttr()).getValue();
492 minApf.convert(cast<FloatType>(elementTy).getFloatSemantics(),
493 APFloat::rmNearestTiesToEven, &losesInfo);
494 maxApf.convert(cast<FloatType>(elementTy).getFloatSemantics(),
495 APFloat::rmNearestTiesToEven, &losesInfo);
496 auto min = arith::ConstantOp::create(
497 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, minApf));
498 auto max = arith::ConstantOp::create(
499 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, maxApf));
500 auto result = clampFloatHelper(loc, args[0], min, max, rewriter);
501
502 const auto nanMode = clampOp.getNanMode();
503
504 // NaN propagation has no meaning for non floating point types.
505 if (!isa<FloatType>(elementTy))
506 return result;
507
508 // In the case of "PROPAGATE" semantics no compare and selection is
509 // required.
510 if (nanMode == NanPropagationMode::PROPAGATE)
511 return result;
512
513 // In the case of "IGNORE" semantics materialize a comparison
514 // of the current operand to the reduction which will return true for a NaN
515 // argument and then selects between the initial reduction value and the
516 // calculated result based on whether the argument is NaN or not. In pseudo
517 // code:
518 //
519 // reduce<op>(x, init):
520 // result = op(init, x)
521 // return init if x == NaN else result
522
523 // Unordered comparison of NaN against itself will always return true.
524 Value isNaN = arith::CmpFOp::create(
525 rewriter, op->getLoc(), arith::CmpFPredicate::UNO, args[0], args[0]);
526 // TOSA specifies that in "ignore" NaN mode the result is "min" if the input
527 // is NaN.
528 return arith::SelectOp::create(rewriter, op->getLoc(), isNaN, min, result);
529 }
530
531 if (isa<tosa::ClampOp>(op) && isa<IntegerType>(elementTy)) {
532 auto intTy = cast<IntegerType>(elementTy);
533 auto clampOp = cast<tosa::ClampOp>(op);
534 int64_t min =
535 cast<IntegerAttr>(clampOp.getMinValAttr()).getValue().getSExtValue();
536 int64_t max =
537 cast<IntegerAttr>(clampOp.getMaxValAttr()).getValue().getSExtValue();
538
539 int64_t minRepresentable = std::numeric_limits<int64_t>::min();
540 int64_t maxRepresentable = std::numeric_limits<int64_t>::max();
541 if (intTy.isUnsignedInteger()) {
542 minRepresentable = 0;
543 if (intTy.getIntOrFloatBitWidth() <= 63) {
544 maxRepresentable =
545 (int64_t)APInt::getMaxValue(intTy.getIntOrFloatBitWidth())
546 .getZExtValue();
547 }
548 } else if (intTy.getIntOrFloatBitWidth() <= 64) {
549 // Ensure that min & max fit into signed n-bit constants.
550 minRepresentable = APInt::getSignedMinValue(intTy.getIntOrFloatBitWidth())
551 .getSExtValue();
552 maxRepresentable = APInt::getSignedMaxValue(intTy.getIntOrFloatBitWidth())
553 .getSExtValue();
554 }
555 // Ensure that the bounds are representable as n-bit signed/unsigned
556 // integers.
557 min = std::max(min, minRepresentable);
558 max = std::max(max, minRepresentable);
559 min = std::min(min, maxRepresentable);
560 max = std::min(max, maxRepresentable);
561
562 auto minVal = arith::ConstantIntOp::create(rewriter, loc, min,
563 intTy.getIntOrFloatBitWidth());
564 auto maxVal = arith::ConstantIntOp::create(rewriter, loc, max,
565 intTy.getIntOrFloatBitWidth());
566 return clampIntHelper(loc, args[0], minVal, maxVal, rewriter,
567 intTy.isUnsignedInteger());
568 }
569
570 // tosa::SigmoidOp
571 if (isa<tosa::SigmoidOp>(op) && isa<FloatType>(elementTy)) {
572 auto one =
573 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
574 auto negate = arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
575 auto exp = mlir::math::ExpOp::create(rewriter, loc, resultTypes, negate);
576 auto added = arith::AddFOp::create(rewriter, loc, exp, one);
577 return arith::DivFOp::create(rewriter, loc, one, added);
578 }
579
580 // tosa::CastOp
581 if (isa<tosa::CastOp>(op)) {
582 Type srcTy = elementTy;
583 Type dstTy = resultTypes.front();
584 if (!srcTy.isIntOrFloat() || !dstTy.isIntOrFloat()) {
585 (void)rewriter.notifyMatchFailure(op, "unsupported type");
586 return nullptr;
587 }
588
589 bool bitExtend =
591
592 // With `input_unsigned`, the integer input is read as unsigned.
593 bool inputUnsigned = cast<tosa::CastOp>(op).getInputUnsigned();
594
595 if (srcTy == dstTy)
596 return args.front();
597
598 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && bitExtend)
600 resultTypes, args);
601
602 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && !bitExtend)
604 resultTypes, args);
605
606 // 1-bit integers need to be treated as signless.
607 if (srcTy.isInteger(1) && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
609 resultTypes, args);
610
611 if (srcTy.isInteger(1) && isa<IntegerType>(dstTy) && bitExtend)
613 resultTypes, args);
614
615 // Unsigned integers need an unrealized cast so that they can be passed
616 // to UIToFP.
617 if (srcTy.isUnsignedInteger() && isa<FloatType>(dstTy)) {
618 auto unrealizedCast =
619 UnrealizedConversionCastOp::create(
620 rewriter, loc,
621 rewriter.getIntegerType(srcTy.getIntOrFloatBitWidth()), args[0])
622 .getResult(0);
623 return arith::UIToFPOp::create(rewriter, loc, resultTypes[0],
624 unrealizedCast);
625 }
626
627 // Unsigned inputs are converted with UIToFP.
628 if (inputUnsigned && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
630 resultTypes, args);
631
632 // All other si-to-fp conversions should be handled by SIToFP.
633 if (arith::SIToFPOp::areCastCompatible(srcTy, dstTy))
634 return arith::SIToFPOp::create(rewriter, loc, resultTypes, args,
636
637 // Casting to boolean, floats need to only be checked as not-equal to zero.
638 if (isa<FloatType>(srcTy) && dstTy.isInteger(1)) {
639 Value zero = arith::ConstantOp::create(rewriter, loc,
640 rewriter.getFloatAttr(srcTy, 0.0));
641 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::UNE,
642 args.front(), zero);
643 }
644
645 if (arith::FPToSIOp::areCastCompatible(srcTy, dstTy)) {
646 auto rounded = math::RoundEvenOp::create(rewriter, loc, args[0]);
647
648 const auto &fltSemantics = cast<FloatType>(srcTy).getFloatSemantics();
649 // Check whether neither int min nor int max can be represented in the
650 // input floating-point type due to too short exponent range.
651 if (static_cast<int>(dstTy.getIntOrFloatBitWidth()) - 1 >
652 APFloat::semanticsMaxExponent(fltSemantics)) {
653 // Use cmp + select to replace infinites by int min / int max. Other
654 // integral values can be represented in the integer space.
655 auto conv = arith::FPToSIOp::create(rewriter, loc, dstTy, rounded);
656 auto posInf = arith::ConstantOp::create(
657 rewriter, loc,
658 rewriter.getFloatAttr(getElementTypeOrSelf(srcTy),
659 APFloat::getInf(fltSemantics)));
660 auto negInf = arith::ConstantOp::create(
661 rewriter, loc,
662 rewriter.getFloatAttr(
664 APFloat::getInf(fltSemantics, /*Negative=*/true)));
665 auto overflow = arith::CmpFOp::create(
666 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, posInf);
667 auto underflow = arith::CmpFOp::create(
668 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, negInf);
669 auto intMin = arith::ConstantOp::create(
670 rewriter, loc,
671 rewriter.getIntegerAttr(
673 APInt::getSignedMinValue(dstTy.getIntOrFloatBitWidth())));
674 auto intMax = arith::ConstantOp::create(
675 rewriter, loc,
676 rewriter.getIntegerAttr(
678 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())));
679 auto maxClamped =
680 arith::SelectOp::create(rewriter, loc, overflow, intMax, conv);
681 return arith::SelectOp::create(rewriter, loc, underflow, intMin,
682 maxClamped);
683 }
684
685 auto intMinFP = arith::ConstantOp::create(
686 rewriter, loc,
687 rewriter.getFloatAttr(
689 APInt::getSignedMinValue(dstTy.getIntOrFloatBitWidth())
690 .getSExtValue()));
691
692 // Check whether the mantissa has enough bits to represent int max.
693 if (cast<FloatType>(srcTy).getFPMantissaWidth() >=
694 dstTy.getIntOrFloatBitWidth() - 1) {
695 // Int min can also be represented since it is a power of two and thus
696 // consists of a single leading bit. Therefore we can clamp the input
697 // in the floating-point domain.
698
699 auto intMaxFP = arith::ConstantOp::create(
700 rewriter, loc,
701 rewriter.getFloatAttr(
703 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())
704 .getSExtValue()));
705
706 Value clamped =
707 clampFloatHelper(loc, rounded, intMinFP, intMaxFP, rewriter);
708 return arith::FPToSIOp::create(rewriter, loc, dstTy, clamped);
709 }
710
711 // Due to earlier check we know exponant range is big enough to represent
712 // int min. We can therefore rely on int max + 1 being representable as
713 // well because it's just int min with a positive sign. So clamp the min
714 // value and compare against that to select the max int value if needed.
715 auto intMaxPlusOneFP = arith::ConstantOp::create(
716 rewriter, loc,
717 rewriter.getFloatAttr(
719 static_cast<double>(
720 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())
721 .getSExtValue()) +
722 1.0f));
723
724 auto intMax = arith::ConstantOp::create(
725 rewriter, loc,
726 rewriter.getIntegerAttr(
728 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())));
729 auto minClampedFP =
730 arith::MaximumFOp::create(rewriter, loc, rounded, intMinFP);
731 auto minClamped =
732 arith::FPToSIOp::create(rewriter, loc, dstTy, minClampedFP);
733 auto overflow = arith::CmpFOp::create(
734 rewriter, loc, arith::CmpFPredicate::UGE, rounded, intMaxPlusOneFP);
735 return arith::SelectOp::create(rewriter, loc, overflow, intMax,
736 minClamped);
737 }
738
739 // Casting to boolean, integers need to only be checked as not-equal to
740 // zero.
741 if (isa<IntegerType>(srcTy) && dstTy.isInteger(1)) {
742 Value zero = arith::ConstantIntOp::create(rewriter, loc, 0,
743 srcTy.getIntOrFloatBitWidth());
744 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::ne,
745 args.front(), zero);
746 }
747
748 // Unsigned inputs are zero-extended.
749 if (inputUnsigned && isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) &&
750 bitExtend)
752 resultTypes, args);
753
754 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && bitExtend)
755 return arith::ExtSIOp::create(rewriter, loc, resultTypes, args,
757
758 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && !bitExtend) {
759 return arith::TruncIOp::create(rewriter, loc, dstTy, args[0]);
760 }
761 }
762
763 (void)rewriter.notifyMatchFailure(
764 op, "unhandled op for linalg body calculation for elementwise op");
765 return nullptr;
766}
767
768// Emit an 'arith.constant' op for the given index if it has not been created
769// yet, or return an existing constant. This will prevent an excessive creation
770// of redundant constants, easing readability of emitted code for unit tests.
772 IndexPool &indexPool, int64_t index) {
773 auto [it, inserted] = indexPool.try_emplace(index);
774 if (inserted)
775 it->second =
776 arith::ConstantOp::create(rewriter, loc, rewriter.getIndexAttr(index));
777 return it->second;
778}
779
781 IndexPool &indexPool, Value tensor, int64_t index) {
782 auto indexValue = createIndex(rewriter, loc, indexPool, index);
783 return tensor::DimOp::create(rewriter, loc, tensor, indexValue).getResult();
784}
785
787 IndexPool &indexPool, Value tensor,
788 int64_t index) {
789 auto shapedType = dyn_cast<ShapedType>(tensor.getType());
790 assert(shapedType && shapedType.hasRank() && "expected a ranked shaped type");
791 assert(index >= 0 && index < shapedType.getRank() && "index out of bounds");
792 if (shapedType.isDynamicDim(index))
793 return getTensorDim(rewriter, loc, indexPool, tensor, index);
794 return rewriter.getIndexAttr(shapedType.getDimSize(index));
795}
796
797static bool operandsAndResultsRanked(Operation *operation) {
798 auto isRanked = [](Value value) {
799 return isa<RankedTensorType>(value.getType());
800 };
801 return llvm::all_of(operation->getOperands(), isRanked) &&
802 llvm::all_of(operation->getResults(), isRanked);
803}
804
805// Compute the runtime dimension size for dimension 'dim' of the output by
806// inspecting input 'operands', all of which are expected to have the same rank.
807// This function returns a pair {targetSize, masterOperand}.
808//
809// The runtime size of the output dimension is returned either as a statically
810// computed attribute or as a runtime SSA value.
811//
812// If the target size was inferred directly from one dominating operand, that
813// operand is returned in 'masterOperand'. If the target size is inferred from
814// multiple operands, 'masterOperand' is set to nullptr.
815std::pair<OpFoldResult, Value>
817 IndexPool &indexPool, ValueRange operands,
818 int64_t dim) {
819 // If any input operand contains a static size greater than 1 for this
820 // dimension, that is the target size. An occurrence of an additional static
821 // dimension greater than 1 with a different value is undefined behavior.
822 for (auto operand : operands) {
823 auto size = cast<RankedTensorType>(operand.getType()).getDimSize(dim);
824 if (ShapedType::isStatic(size) && size > 1)
825 return {rewriter.getIndexAttr(size), operand};
826 }
827
828 // Filter operands with dynamic dimension
829 auto operandsWithDynamicDim =
830 llvm::filter_to_vector(operands, [&](Value operand) {
831 return cast<RankedTensorType>(operand.getType()).isDynamicDim(dim);
832 });
833
834 // If no operand has a dynamic dimension, it means all sizes were 1
835 if (operandsWithDynamicDim.empty())
836 return {rewriter.getIndexAttr(1), operands.front()};
837
838 // Emit code that computes the runtime size for this dimension. If there is
839 // only one operand with a dynamic dimension, it is considered the master
840 // operand that determines the runtime size of the output dimension.
841 auto targetSize =
842 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[0], dim);
843 if (operandsWithDynamicDim.size() == 1)
844 return {targetSize, operandsWithDynamicDim[0]};
845
846 // Calculate maximum size among all dynamic dimensions
847 for (size_t i = 1; i < operandsWithDynamicDim.size(); i++) {
848 auto nextSize =
849 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[i], dim);
850 targetSize = arith::MaxUIOp::create(rewriter, loc, targetSize, nextSize);
851 }
852 return {targetSize, nullptr};
853}
854
855// Compute the runtime output size for all dimensions. This function returns
856// a pair {targetShape, masterOperands}.
857static std::pair<SmallVector<OpFoldResult>, SmallVector<Value>>
859 IndexPool &indexPool, ValueRange operands) {
860 assert(!operands.empty());
861 auto rank = cast<RankedTensorType>(operands.front().getType()).getRank();
862 SmallVector<OpFoldResult> targetShape;
863 SmallVector<Value> masterOperands;
864 for (auto dim : llvm::seq<int64_t>(0, rank)) {
865 auto [targetSize, masterOperand] =
866 computeTargetSize(rewriter, loc, indexPool, operands, dim);
867 targetShape.push_back(targetSize);
868 masterOperands.push_back(masterOperand);
869 }
870 return {targetShape, masterOperands};
871}
872
874 IndexPool &indexPool, Value operand,
875 int64_t dim, OpFoldResult targetSize,
876 Value masterOperand) {
877 // Nothing to do if this is a static dimension
878 auto rankedTensorType = cast<RankedTensorType>(operand.getType());
879 if (!rankedTensorType.isDynamicDim(dim))
880 return operand;
881
882 // If the target size for this dimension was directly inferred by only taking
883 // this operand into account, there is no need to broadcast. This is an
884 // optimization that will prevent redundant control flow, and constitutes the
885 // main motivation for tracking "master operands".
886 if (operand == masterOperand)
887 return operand;
888
889 // Affine maps for 'linalg.generic' op
890 auto rank = rankedTensorType.getRank();
891 SmallVector<AffineExpr> affineExprs;
892 for (auto index : llvm::seq<int64_t>(0, rank)) {
893 auto affineExpr = index == dim ? rewriter.getAffineConstantExpr(0)
894 : rewriter.getAffineDimExpr(index);
895 affineExprs.push_back(affineExpr);
896 }
897 auto broadcastAffineMap =
898 AffineMap::get(rank, 0, affineExprs, rewriter.getContext());
899 auto identityAffineMap = rewriter.getMultiDimIdentityMap(rank);
900 SmallVector<AffineMap> affineMaps = {broadcastAffineMap, identityAffineMap};
901
902 // Check if broadcast is necessary
903 auto one = createIndex(rewriter, loc, indexPool, 1);
904 auto runtimeSize = getTensorDim(rewriter, loc, indexPool, operand, dim);
905 auto broadcastNecessary = arith::CmpIOp::create(
906 rewriter, loc, arith::CmpIPredicate::eq, runtimeSize, one);
907
908 // Emit 'then' region of 'scf.if'
909 auto emitThenRegion = [&](OpBuilder &opBuilder, Location loc) {
910 // It is not safe to cache constants across regions.
911 // New constants could potentially violate dominance requirements.
912 IndexPool localPool;
913
914 // Emit 'tensor.empty' op
915 SmallVector<OpFoldResult> outputTensorShape;
916 for (auto index : llvm::seq<int64_t>(0, rank)) {
917 auto size = index == dim ? targetSize
918 : getOrFoldTensorDim(rewriter, loc, localPool,
919 operand, index);
920 outputTensorShape.push_back(size);
921 }
922 Value outputTensor = tensor::EmptyOp::create(
923 opBuilder, loc, outputTensorShape, rankedTensorType.getElementType());
924
925 // Emit 'linalg.generic' op
926 auto resultTensor =
927 linalg::GenericOp::create(
928 opBuilder, loc, outputTensor.getType(), operand, outputTensor,
929 affineMaps, getNParallelLoopsAttrs(rank),
930 [&](OpBuilder &opBuilder, Location loc, ValueRange blockArgs) {
931 // Emit 'linalg.yield' op
932 linalg::YieldOp::create(opBuilder, loc, blockArgs.front());
933 })
934 .getResult(0);
935
936 // Cast to original operand type if necessary
937 auto castResultTensor = rewriter.createOrFold<tensor::CastOp>(
938 loc, operand.getType(), resultTensor);
939
940 // Emit 'scf.yield' op
941 scf::YieldOp::create(opBuilder, loc, castResultTensor);
942 };
943
944 // Emit 'else' region of 'scf.if'
945 auto emitElseRegion = [&](OpBuilder &opBuilder, Location loc) {
946 scf::YieldOp::create(opBuilder, loc, operand);
947 };
948
949 // Emit 'scf.if' op
950 auto ifOp = scf::IfOp::create(rewriter, loc, broadcastNecessary,
951 emitThenRegion, emitElseRegion);
952 return ifOp.getResult(0);
953}
954
956 IndexPool &indexPool, Value operand,
957 ArrayRef<OpFoldResult> targetShape,
958 ArrayRef<Value> masterOperands) {
959 int64_t rank = cast<RankedTensorType>(operand.getType()).getRank();
960 assert((int64_t)targetShape.size() == rank);
961 assert((int64_t)masterOperands.size() == rank);
962 for (auto index : llvm::seq<int64_t>(0, rank))
963 operand =
964 broadcastDynamicDimension(rewriter, loc, indexPool, operand, index,
965 targetShape[index], masterOperands[index]);
966 return operand;
967}
968
971 IndexPool &indexPool, ValueRange operands,
972 ArrayRef<OpFoldResult> targetShape,
973 ArrayRef<Value> masterOperands) {
974 // No need to broadcast for unary operations
975 if (operands.size() == 1)
976 return operands;
977
978 // No need to broadcast for static shape
979 bool hasDynamic = false;
980 for (auto op : operands) {
981 const auto tType = dyn_cast<RankedTensorType>(op.getType());
982 if (tType && !tType.hasStaticShape()) {
983 hasDynamic = true;
984 break;
985 }
986 }
987 if (!hasDynamic)
988 return operands;
989
990 // Broadcast dynamic dimensions operand by operand
991 return llvm::map_to_vector(operands, [&](Value operand) {
992 return broadcastDynamicDimensions(rewriter, loc, indexPool, operand,
993 targetShape, masterOperands);
994 });
995}
996
997static LogicalResult emitElementwiseComputation(
998 ConversionPatternRewriter &rewriter, Location loc, Operation *operation,
999 ValueRange operands, ValueRange scalarOperands,
1000 ArrayRef<OpFoldResult> targetShape, const TypeConverter &converter) {
1001 // Generate output tensor
1002 auto resultType = cast_or_null<RankedTensorType>(
1003 converter.convertType(operation->getResultTypes().front()));
1004 if (!resultType) {
1005 return rewriter.notifyMatchFailure(operation, "failed to convert type");
1006 }
1007 Value outputTensor = tensor::EmptyOp::create(rewriter, loc, targetShape,
1008 resultType.getElementType());
1009
1010 // Create affine maps. Input affine maps broadcast static dimensions of size
1011 // 1. The output affine map is an identity map.
1012 //
1013 auto rank = resultType.getRank();
1014 auto affineMaps = llvm::map_to_vector(operands, [&](Value operand) {
1015 auto shape = cast<ShapedType>(operand.getType()).getShape();
1016 SmallVector<AffineExpr> affineExprs;
1017 for (auto it : llvm::enumerate(shape)) {
1018 // Prefer producting identity maps whenever possible (i.e. no broadcasting
1019 // needed) because some transforms (like reshape folding)
1020 // do not support affine constant exprs.
1021 bool requiresBroadcast =
1022 (it.value() == 1 && resultType.getDimSize(it.index()) != 1);
1023 auto affineExpr = requiresBroadcast
1024 ? rewriter.getAffineConstantExpr(0)
1025 : rewriter.getAffineDimExpr(it.index());
1026 affineExprs.push_back(affineExpr);
1027 }
1028 return AffineMap::get(rank, 0, affineExprs, rewriter.getContext());
1029 });
1030 // Scalar operands are single-element tensors: every iteration reads their
1031 // first element.
1032 for (Value scalar : scalarOperands) {
1033 auto scalarRank = cast<ShapedType>(scalar.getType()).getRank();
1034 SmallVector<AffineExpr> zeros(scalarRank,
1035 rewriter.getAffineConstantExpr(0));
1036 affineMaps.push_back(AffineMap::get(rank, 0, zeros, rewriter.getContext()));
1037 }
1038 affineMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
1039
1040 SmallVector<Value> inputs(operands);
1041 llvm::append_range(inputs, scalarOperands);
1042
1043 // Emit 'linalg.generic' op
1044 bool encounteredError = false;
1045 auto linalgOp = linalg::GenericOp::create(
1046 rewriter, loc, outputTensor.getType(), inputs, outputTensor, affineMaps,
1048 [&](OpBuilder &opBuilder, Location loc, ValueRange blockArgs) {
1050 operation, blockArgs.take_front(operation->getNumOperands()),
1051 {resultType.getElementType()}, rewriter);
1052 if (!opResult) {
1053 encounteredError = true;
1054 return;
1055 }
1056 linalg::YieldOp::create(opBuilder, loc, opResult);
1057 });
1058 if (encounteredError)
1059 return rewriter.notifyMatchFailure(
1060 operation, "unable to create linalg.generic body for elementwise op");
1061
1062 // Cast 'linalg.generic' result into original result type if needed
1063 auto castResult = rewriter.createOrFold<tensor::CastOp>(
1064 loc, resultType, linalgOp->getResult(0));
1065 rewriter.replaceOp(operation, castResult);
1066 return success();
1067}
1068
1069// The shift of tosa.mul and the zero points of tosa.negate are single-element
1070// tensors, so they never take part in broadcasting.
1072 ValueRange operands) {
1073 if (isa<tosa::MulOp>(operation))
1074 return operands.take_front(2);
1075 if (isa<tosa::NegateOp>(operation))
1076 return operands.take_front(1);
1077 return operands;
1078}
1079
1080// Returns the single-element operands that the body reads as block arguments:
1081// a non-constant tosa.mul shift, or both tosa.negate zero points when either of
1082// them is non-constant. Constant ones are created in the body instead.
1083static ValueRange getScalarOperands(Operation *operation, ValueRange operands) {
1084 if (isa<tosa::MulOp>(operation)) {
1085 DenseElementsAttr shiftElems;
1086 if (matchPattern(operation->getOperand(2), m_Constant(&shiftElems)))
1087 return {};
1088 return operands.drop_front(2);
1089 }
1090 if (auto negate = dyn_cast<tosa::NegateOp>(operation)) {
1091 if (succeeded(negate.getInput1ZeroPoint()) &&
1092 succeeded(negate.getOutputZeroPoint()))
1093 return {};
1094 return operands.drop_front(1);
1095 }
1096 return {};
1097}
1098
1099static LogicalResult
1101 ConversionPatternRewriter &rewriter,
1102 const TypeConverter &converter) {
1103
1104 // Collect op properties
1105 assert(operation->getNumResults() == 1 && "elementwise op expects 1 result");
1106 assert(operation->getNumOperands() >= 1 &&
1107 "elementwise op expects at least 1 operand");
1108 if (!operandsAndResultsRanked(operation))
1109 return rewriter.notifyMatchFailure(operation,
1110 "Unranked tensors not supported");
1111
1112 // Lower operation
1113 IndexPool indexPool;
1114 auto loc = operation->getLoc();
1115 auto operandsToBroadcast = getBroadcastableOperands(operation, operands);
1116 auto scalarOperands = getScalarOperands(operation, operands);
1117 auto [targetShape, masterOperands] =
1118 computeTargetShape(rewriter, loc, indexPool, operandsToBroadcast);
1119 auto broadcastOperands =
1120 broadcastDynamicDimensions(rewriter, loc, indexPool, operandsToBroadcast,
1121 targetShape, masterOperands);
1122 return emitElementwiseComputation(rewriter, loc, operation, broadcastOperands,
1123 scalarOperands, targetShape, converter);
1124}
1125
1126// Returns the constant initial value for a given reduction operation. The
1127// attribute type varies depending on the element type required.
1128static TypedAttr createInitialValueForReduceOp(Operation *op, Type elementTy,
1129 PatternRewriter &rewriter,
1130 bool allowNonFinites) {
1131 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy))
1132 return rewriter.getFloatAttr(elementTy, 0.0);
1133
1134 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy))
1135 return rewriter.getIntegerAttr(elementTy, 0);
1136
1137 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy))
1138 return rewriter.getFloatAttr(elementTy, 1.0);
1139
1140 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy))
1141 return rewriter.getIntegerAttr(elementTy, 1);
1142
1143 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy))
1144 return rewriter.getFloatAttr(
1145 elementTy,
1146 getFloatMinMaxIdentity(cast<FloatType>(elementTy).getFloatSemantics(),
1147 /*negative=*/false, allowNonFinites));
1148
1149 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy))
1150 return rewriter.getIntegerAttr(
1151 elementTy, APInt::getSignedMaxValue(elementTy.getIntOrFloatBitWidth()));
1152
1153 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy))
1154 return rewriter.getFloatAttr(
1155 elementTy,
1156 getFloatMinMaxIdentity(cast<FloatType>(elementTy).getFloatSemantics(),
1157 /*negative=*/true, allowNonFinites));
1158
1159 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy))
1160 return rewriter.getIntegerAttr(
1161 elementTy, APInt::getSignedMinValue(elementTy.getIntOrFloatBitWidth()));
1162
1163 if (isa<tosa::ReduceAllOp>(op) && elementTy.isInteger(1))
1164 return rewriter.getIntegerAttr(elementTy, APInt::getAllOnes(1));
1165
1166 if (isa<tosa::ReduceAnyOp>(op) && elementTy.isInteger(1))
1167 return rewriter.getIntegerAttr(elementTy, APInt::getZero(1));
1168
1169 if (isa<tosa::ArgMaxOp, tosa::ArgMinOp>(op) && isa<FloatType>(elementTy)) {
1170 const bool isMax = isa<tosa::ArgMaxOp>(op);
1171 const auto nanMode = isMax ? cast<tosa::ArgMaxOp>(op).getNanMode()
1172 : cast<tosa::ArgMinOp>(op).getNanMode();
1173
1174 auto floatTy = dyn_cast<FloatType>(elementTy);
1175 const auto &semantics = floatTy.getFloatSemantics();
1176
1177 const bool useNaN = nanMode == NanPropagationMode::IGNORE &&
1178 APFloat::semanticsHasNaN(semantics);
1179 const auto seed =
1180 useNaN ? APFloat::getQNaN(semantics)
1181 : getFloatMinMaxIdentity(semantics, /*negative=*/isMax,
1182 allowNonFinites);
1183
1184 return rewriter.getFloatAttr(floatTy, seed);
1185 }
1186
1187 if (isa<tosa::ArgMaxOp>(op) && isa<IntegerType>(elementTy))
1188 return rewriter.getIntegerAttr(
1189 elementTy, APInt::getSignedMinValue(elementTy.getIntOrFloatBitWidth()));
1190
1191 if (isa<tosa::ArgMinOp>(op) && isa<IntegerType>(elementTy))
1192 return rewriter.getIntegerAttr(
1193 elementTy, APInt::getSignedMaxValue(elementTy.getIntOrFloatBitWidth()));
1194
1195 return {};
1196}
1197
1198// Creates the body calculation for a reduction. The operations vary depending
1199// on the input type.
1201 ValueRange args,
1202 Type elementTy,
1203 PatternRewriter &rewriter) {
1204 Location loc = op->getLoc();
1205 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy)) {
1207 rewriter, loc, TypeRange{elementTy}, args);
1208 }
1209
1210 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy)) {
1212 rewriter, loc, TypeRange{elementTy}, args);
1213 }
1214
1215 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy)) {
1217 rewriter, loc, TypeRange{elementTy}, args);
1218 }
1219
1220 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy)) {
1222 rewriter, loc, TypeRange{elementTy}, args);
1223 }
1224
1225 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy)) {
1226 return arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
1227 }
1228
1229 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy)) {
1230 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
1231 }
1232
1233 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy)) {
1234 return arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
1235 }
1236
1237 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy)) {
1238 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
1239 }
1240
1241 if (isa<tosa::ReduceAllOp>(op) && elementTy.isInteger(1))
1242 return arith::AndIOp::create(rewriter, loc, args);
1243
1244 if (isa<tosa::ReduceAnyOp>(op) && elementTy.isInteger(1))
1245 return arith::OrIOp::create(rewriter, loc, args);
1246
1247 return {};
1248}
1249
1250// Performs the match and rewrite for reduction operations. This includes
1251// declaring a correctly sized initial value, and the linalg.generic operation
1252// that reduces across the specified axis.
1253template <typename OpTy>
1254static LogicalResult reduceMatchAndRewriteHelper(OpTy op, uint64_t axis,
1255 PatternRewriter &rewriter,
1256 bool allowNonFinites) {
1257 auto loc = op->getLoc();
1258 auto inputTy = dyn_cast<RankedTensorType>(op->getOperand(0).getType());
1259 auto resultTy = dyn_cast<RankedTensorType>(op->getResult(0).getType());
1260 if (!inputTy || !resultTy)
1261 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
1262
1263 auto elementTy = resultTy.getElementType();
1264 Value input = op->getOperand(0);
1265
1266 // Accumulate BF16 sums and products in FP32.
1267 constexpr bool isArithmeticReduction =
1268 std::is_same_v<OpTy, tosa::ReduceSumOp> ||
1269 std::is_same_v<OpTy, tosa::ReduceProductOp>;
1270 Type accTy =
1271 isArithmeticReduction ? getAccumulationType(elementTy) : elementTy;
1272 bool widenAccTy = accTy != elementTy;
1273
1274 SmallVector<int64_t> reduceShape;
1275 SmallVector<Value> dynDims;
1276 for (unsigned i = 0; i < inputTy.getRank(); i++) {
1277 if (axis != i) {
1278 reduceShape.push_back(inputTy.getDimSize(i));
1279 if (inputTy.isDynamicDim(i))
1280 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1281 }
1282 }
1283
1284 SmallVector<Value> inputs, outputs;
1285 inputs.push_back(input);
1286
1287 // First fill the output buffer with the init value.
1288 auto emptyTensor =
1289 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1290 .getResult();
1291
1292 auto fillValueAttr =
1293 createInitialValueForReduceOp(op, accTy, rewriter, allowNonFinites);
1294 if (!fillValueAttr)
1295 return rewriter.notifyMatchFailure(
1296 op, "No initial value found for reduction operation");
1297
1298 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
1299 auto filledTensor =
1300 linalg::FillOp::create(rewriter, loc, ValueRange{fillValue},
1301 ValueRange{emptyTensor})
1302 .result();
1303 outputs.push_back(filledTensor);
1304
1305 bool isNanIgnoreMode = false;
1306 if constexpr (std::is_same_v<OpTy, tosa::ReduceMinOp> ||
1307 std::is_same_v<OpTy, tosa::ReduceMaxOp>) {
1308 // NaN propagation has no meaning for non floating point types.
1309 if (isa<FloatType>(elementTy) &&
1310 op.getNanMode() == NanPropagationMode::IGNORE) {
1311 isNanIgnoreMode = true;
1312 // Because the TOSA spec requires the result be NaN iff all elements in
1313 // the reduction are NaN we can't simply perform a compare and select.
1314 // Additionally we have to keep track of whether we've seen any non-NaN
1315 // values and then do a final select based on this predicate.
1316 auto trueAttr = rewriter.getBoolAttr(true);
1317 auto trueValue = arith::ConstantOp::create(rewriter, loc, trueAttr);
1318 auto emptyBoolTensor =
1319 tensor::EmptyOp::create(rewriter, loc, reduceShape,
1320 trueValue.getType(), dynDims)
1321 .getResult();
1322 auto allResultsNaNTensor =
1323 linalg::FillOp::create(rewriter, loc, ValueRange{trueValue},
1324 ValueRange{emptyBoolTensor})
1325 .result();
1326 // Note that because the linalg::ReduceOp has two variadic arguments
1327 // (inputs and outputs) and it has the SameVariadicOperandSize trait we
1328 // need to have the same number of inputs and outputs.
1329 //
1330 // The second input isn't actually used anywhere since the value used to
1331 // update the NaN flag is calculated inside the body of the reduction and
1332 // then used to update an out value.
1333 // In order to satisfy type constraints we just pass another copy of the
1334 // input here.
1335 inputs.push_back(input);
1336 outputs.push_back(allResultsNaNTensor);
1337 }
1338 }
1339
1340 bool didEncounterError = false;
1341 linalg::LinalgOp linalgOp = linalg::ReduceOp::create(
1342 rewriter, loc, inputs, outputs, axis,
1343 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange blockArgs) {
1344 std::array<Value, 2> binaryArgs{
1345 blockArgs[0], isNanIgnoreMode ? blockArgs[2] : blockArgs[1]};
1346
1347 // If reduction type differs then extend
1348 if (binaryArgs[0].getType() != accTy)
1349 binaryArgs[0] = arith::ExtFOp::create(
1350 nestedBuilder, nestedLoc, TypeRange{accTy},
1351 ValueRange{binaryArgs[0]}, arith::ExtFOp::Properties{});
1352
1353 auto result = createLinalgBodyCalculationForReduceOp(op, binaryArgs,
1354 accTy, rewriter);
1355 if (result)
1356 didEncounterError = true;
1357
1358 SmallVector<Value> resultsToYield;
1359 if (isNanIgnoreMode) {
1360 auto inputValue = blockArgs[0];
1361 auto initialValue = blockArgs[2];
1362 auto oldAllResultsNanFlagValue = blockArgs[3];
1363
1364 // Unordered comparison of NaN against itself will always return true.
1365 Value isNaN = arith::CmpFOp::create(nestedBuilder, op->getLoc(),
1366 arith::CmpFPredicate::UNO,
1367 inputValue, inputValue);
1368 // If we've encountered a NaN, take the non-NaN value.
1369 auto selectOp = arith::SelectOp::create(nestedBuilder, op->getLoc(),
1370 isNaN, initialValue, result);
1371 // Update the flag which keeps track of whether we have seen a non-NaN
1372 // value.
1373 auto newAllResultsNanFlagValue = arith::AndIOp::create(
1374 nestedBuilder, op->getLoc(), oldAllResultsNanFlagValue, isNaN);
1375 resultsToYield.push_back(selectOp);
1376 resultsToYield.push_back(newAllResultsNanFlagValue);
1377 } else {
1378 resultsToYield.push_back(result);
1379 }
1380 linalg::YieldOp::create(nestedBuilder, loc, resultsToYield);
1381 });
1382
1383 if (!didEncounterError)
1384 return rewriter.notifyMatchFailure(
1385 op, "unable to create linalg.generic body for reduce op");
1386
1387 if (isNanIgnoreMode) {
1388 // Materialize a check to see whether we encountered any non-NaN values, if
1389 // we didn't we need to select a tensor of NaNs since the result will just
1390 // be the initial identity value propagated through all the compares and
1391 // selects inside the reduction.
1392
1393 // Create a tensor full of NaNs.
1394 auto nanValueAttr = rewriter.getFloatAttr(
1395 accTy,
1396 APFloat::getNaN(cast<FloatType>(elementTy).getFloatSemantics(), false));
1397 auto nanValue = arith::ConstantOp::create(rewriter, loc, nanValueAttr);
1398 auto emptyNanTensor =
1399 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1400 .getResult();
1401 auto nanFilledTensor =
1402 linalg::FillOp::create(rewriter, loc, ValueRange{nanValue},
1403 ValueRange{emptyNanTensor})
1404 .result();
1405
1406 // Create an empty tensor, non need to fill this since it will be
1407 // overwritten by the select.
1408 auto finalEmptyTensor =
1409 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1410 .getResult();
1411
1412 // Do a selection between the tensors akin to:
1413 // result = NaN if "all results NaN" else result.
1414 SmallVector<Value> ins, outs;
1415 ins.push_back(linalgOp->getOpResult(1));
1416 ins.push_back(nanFilledTensor);
1417 ins.push_back(linalgOp->getResult(0));
1418 outs.push_back(finalEmptyTensor);
1419 auto linalgSelect =
1420 linalg::ElementwiseOp::create(rewriter, op->getLoc(), ins, outs,
1421 mlir::linalg::ElementwiseKind::select);
1422 linalgOp = linalgSelect;
1423 }
1424
1425 // Truncate back to resultTy if needed
1426 Value reducedRes = linalgOp->getResult(0);
1427 if (widenAccTy) {
1428 auto resEmptyOp =
1429 tensor::EmptyOp::create(rewriter, loc, reduceShape, elementTy, dynDims)
1430 .getResult();
1431
1432 const unsigned reducedRank =
1433 cast<ShapedType>(reducedRes.getType()).getRank();
1434 auto identityMap = rewriter.getMultiDimIdentityMap(reducedRank);
1435 reducedRes =
1436 linalg::GenericOp::create(
1437 rewriter, loc, resEmptyOp.getType(), ValueRange{reducedRes},
1438 ValueRange{resEmptyOp},
1439 ArrayRef<AffineMap>{identityMap, identityMap},
1440 getNParallelLoopsAttrs(reducedRank),
1441 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
1442 Value truncf = arith::TruncFOp::create(nestedBuilder, nestedLoc,
1443 elementTy, args[0]);
1444 linalg::YieldOp::create(nestedBuilder, nestedLoc, truncf);
1445 })
1446 .getResults()[0];
1447 }
1448
1449 SmallVector<ReassociationExprs, 4> reassociationMap;
1450 uint64_t expandInputRank = cast<ShapedType>(reducedRes.getType()).getRank();
1451 reassociationMap.resize(expandInputRank);
1452
1453 for (uint64_t i = 0; i < expandInputRank; i++) {
1454 int32_t dimToPush = i > axis ? i + 1 : i;
1455 reassociationMap[i].push_back(rewriter.getAffineDimExpr(dimToPush));
1456 }
1457
1458 if (expandInputRank != 0) {
1459 int32_t expandedDim = axis < expandInputRank ? axis : expandInputRank - 1;
1460 reassociationMap[expandedDim].push_back(
1461 rewriter.getAffineDimExpr(expandedDim + 1));
1462 }
1463
1464 // Lower directly to `tensor::ExpandShapeOp` instead of `tosa::ReshapeOp`,
1465 // since here we know which dimension to expand, and `tosa::ReshapeOp` would
1466 // not have access to such information. This matters when handling dynamically
1467 // sized tensors.
1468 rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(op, resultTy, reducedRes,
1469 reassociationMap);
1470 return success();
1471}
1472
1473// Insert missing leading batch dimensions, taking their sizes from `other`.
1475 Location loc, Value operand,
1476 Value other) {
1477 auto type = cast<RankedTensorType>(operand.getType());
1478 int64_t missingDims =
1479 cast<RankedTensorType>(other.getType()).getRank() - type.getRank();
1480 if (missingDims <= 0)
1481 return operand;
1482
1484 SmallVector<int64_t> dimensions;
1485 for (int64_t dim = 0; dim < missingDims; ++dim) {
1486 shape.push_back(tensor::getMixedSize(rewriter, loc, other, dim));
1487 dimensions.push_back(dim);
1488 }
1489 llvm::append_range(shape, tensor::getMixedSizes(rewriter, loc, operand));
1490 Value empty = tensor::EmptyOp::create(
1491 rewriter, loc, shape, type.getElementType(), type.getEncoding());
1492 return linalg::BroadcastOp::create(rewriter, loc, operand, empty, dimensions)
1493 .getResult()
1494 .front();
1495}
1496
1497// Expand an existing singleton batch dimension to `size`, preserving the rank.
1498// Missing dimensions are handled by broadcastMatMulLeadingDimensions.
1499// linalg.broadcast inserts dimensions, so first remove the singleton dimension
1500// with a rank-reducing slice, then reinsert it at the target size.
1502 Location loc, Value operand,
1503 int64_t dim, OpFoldResult size) {
1504 auto type = cast<RankedTensorType>(operand.getType());
1505 SmallVector<int64_t> sliceShape(type.getShape());
1506 sliceShape.erase(sliceShape.begin() + dim);
1507 auto sliceType = RankedTensorType::get(sliceShape, type.getElementType(),
1508 type.getEncoding());
1510 rewriter, loc, operand, sliceType);
1511
1513 tensor::getMixedSizes(rewriter, loc, operand);
1514 shape[dim] = size;
1515 Value empty = tensor::EmptyOp::create(
1516 rewriter, loc, shape, type.getElementType(), type.getEncoding());
1517 return linalg::BroadcastOp::create(rewriter, loc, slice, empty,
1518 ArrayRef<int64_t>{dim})
1519 .getResult()
1520 .front();
1521}
1522
1523// Align the ranks, then broadcast each shared batch dimension independently.
1524static std::pair<Value, Value>
1526 Value b, int64_t batchRank) {
1527 int64_t aRank = cast<RankedTensorType>(a.getType()).getRank();
1528 int64_t bRank = cast<RankedTensorType>(b.getType()).getRank();
1529 int64_t firstSharedDim = std::max(aRank, bRank) - std::min(aRank, bRank);
1530 a = broadcastMatMulLeadingDimensions(rewriter, loc, a, b);
1531 b = broadcastMatMulLeadingDimensions(rewriter, loc, b, a);
1532
1533 IndexPool indexPool;
1534 // The inserted leading dimensions already match their partner's sizes.
1535 for (int64_t dim = firstSharedDim; dim < batchRank; ++dim) {
1536 auto aType = cast<RankedTensorType>(a.getType());
1537 auto bType = cast<RankedTensorType>(b.getType());
1538 int64_t aSize = aType.getDimSize(dim);
1539 int64_t bSize = bType.getDimSize(dim);
1540 if (aSize == bSize && ShapedType::isStatic(aSize))
1541 continue;
1542
1543 // Compute the shared broadcast target only for batch dimensions.
1544 // The matrix dimensions may differ between A and B.
1545 auto [size, masterOperand] =
1546 computeTargetSize(rewriter, loc, indexPool, ValueRange{a, b}, dim);
1547 if (aSize == 1) {
1548 a = broadcastMatMulSingletonDimension(rewriter, loc, a, dim, size);
1549 continue;
1550 }
1551 if (bSize == 1) {
1552 b = broadcastMatMulSingletonDimension(rewriter, loc, b, dim, size);
1553 continue;
1554 }
1555 a = broadcastDynamicDimension(rewriter, loc, indexPool, a, dim, size,
1556 masterOperand);
1557 b = broadcastDynamicDimension(rewriter, loc, indexPool, b, dim, size,
1558 masterOperand);
1559 }
1560 return {a, b};
1561}
1562
1564 Location loc, Value a,
1565 Value b,
1566 RankedTensorType outputType,
1567 bool transposeB) {
1568 const int64_t outputRank = outputType.getRank();
1569 const int64_t batchRank = outputRank - 2;
1570 auto normalizedOperands =
1571 normalizeMatMulBatchDimensions(rewriter, loc, a, b, batchRank);
1572 a = normalizedOperands.first;
1573 b = normalizedOperands.second;
1574
1575 SmallVector<OpFoldResult> outputShape;
1576 outputShape.reserve(outputRank);
1577 for (int64_t batchDim = 0; batchDim < batchRank; ++batchDim)
1578 outputShape.push_back(tensor::getMixedSize(rewriter, loc, a, batchDim));
1579 outputShape.push_back(tensor::getMixedSize(rewriter, loc, a, outputRank - 2));
1580 outputShape.push_back(
1581 tensor::getMixedSize(rewriter, loc, b, outputRank - 1 - transposeB));
1582 SmallVector<Value> dynamicDims;
1583 for (auto [dim, size] : llvm::enumerate(outputShape))
1584 if (outputType.isDynamicDim(dim))
1585 dynamicDims.push_back(
1586 getValueOrCreateConstantIndexOp(rewriter, loc, size));
1587
1588 Value zero = arith::ConstantOp::create(
1589 rewriter, loc, rewriter.getZeroAttr(outputType.getElementType()));
1590 Value emptyTensor = tensor::EmptyOp::create(rewriter, loc, outputType,
1591 condenseValues(dynamicDims));
1592 Value zeroTensor = linalg::FillOp::create(rewriter, loc, ValueRange{zero},
1593 ValueRange{emptyTensor})
1594 .result();
1595
1596 return {a, b, zeroTensor};
1597}
1598
1600 if (requestedType.isBF16())
1601 return Float32Type::get(requestedType.getContext());
1602 return requestedType;
1603}
1604
1605/// Truncate an FP32 tensor to BF16 without changing shape or encoding.
1607 Value input,
1608 RankedTensorType targetType) {
1609 auto inputType = cast<RankedTensorType>(input.getType());
1610
1611 if (inputType == targetType)
1612 return input;
1613
1614 assert(inputType.getShape() == targetType.getShape() &&
1615 "element conversion must preserve shape");
1616 assert(inputType.getEncoding() == targetType.getEncoding() &&
1617 "element conversion must preserve encoding");
1618
1619 Type targetElementType = targetType.getElementType();
1620
1621 assert(inputType.getElementType().isF32() && targetElementType.isBF16() &&
1622 "expected FP32-to-BF16 truncation");
1623
1624 SmallVector<Value> dynamicDims;
1625 for (int64_t dim = 0; dim < targetType.getRank(); ++dim) {
1626 if (targetType.isDynamicDim(dim))
1627 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, dim));
1628 }
1629
1630 auto empty = tensor::EmptyOp::create(rewriter, loc, targetType, dynamicDims);
1631 auto identityMap = rewriter.getMultiDimIdentityMap(targetType.getRank());
1632
1633 auto converted = linalg::GenericOp::create(
1634 rewriter, loc, targetType, ValueRange{input},
1635 ValueRange{empty.getResult()},
1636 ArrayRef<AffineMap>{identityMap, identityMap},
1637 getNParallelLoopsAttrs(targetType.getRank()),
1638 [&](OpBuilder &builder, Location nestedLoc, ValueRange args) {
1639 Value truncated = arith::TruncFOp::create(builder, nestedLoc,
1640 targetElementType, args[0]);
1641 linalg::YieldOp::create(builder, nestedLoc, truncated);
1642 });
1643
1644 return converted.getResult(0);
1645}
1646
1647namespace {
1648// Linalg has quantized matmul and batch matmul operations, but neither has a
1649// transpose-B variant. Lower nonzero zero points separately to linalg.generic
1650// so the reduction can accumulate (A - aZp) * (B - bZp).
1651class QuantizedMatMulTConverter : public OpConversionPattern<tosa::MatMulTOp> {
1652public:
1653 using OpConversionPattern<tosa::MatMulTOp>::OpConversionPattern;
1654 LogicalResult
1655 matchAndRewrite(tosa::MatMulTOp op, OpAdaptor adaptor,
1656 ConversionPatternRewriter &rewriter) const final {
1657 Location loc = op.getLoc();
1658 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
1659 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
1660 auto outputType = dyn_cast<RankedTensorType>(op.getType());
1661 if (!aType || !bType || !outputType)
1662 return rewriter.notifyMatchFailure(op, "only supports ranked tensors");
1663
1664 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
1665 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
1666 if (failed(maybeAZp))
1667 return rewriter.notifyMatchFailure(
1668 op, "input A zero point cannot be statically determined");
1669 if (failed(maybeBZp))
1670 return rewriter.notifyMatchFailure(
1671 op, "input B zero point cannot be statically determined");
1672
1673 const int64_t aZpVal = *maybeAZp;
1674 const int64_t bZpVal = *maybeBZp;
1675
1676 if (aZpVal == 0 && bZpVal == 0)
1677 return rewriter.notifyMatchFailure(
1678 op, "requires at least one nonzero zero point");
1679
1680 const int64_t outputRank = outputType.getRank();
1681 const int64_t batchRank = outputRank - 2;
1682 auto [a, b, zeroTensor] =
1683 prepareMatMulOperands(rewriter, loc, adaptor.getA(), adaptor.getB(),
1684 outputType, /*transposeB=*/true);
1685 Type outputElementType = outputType.getElementType();
1686
1687 int64_t loopRank = outputRank + 1;
1688 SmallVector<AffineExpr> dimensions =
1689 llvm::map_to_vector(llvm::seq<int64_t>(0, loopRank), [&](int64_t dim) {
1690 return rewriter.getAffineDimExpr(dim);
1691 });
1692 SmallVector<AffineExpr> aMap(dimensions.begin(),
1693 dimensions.begin() + batchRank);
1694 aMap.push_back(dimensions[batchRank]);
1695 aMap.push_back(dimensions[batchRank + 2]);
1696 SmallVector<AffineExpr> bMap(dimensions.begin(),
1697 dimensions.begin() + batchRank);
1698 bMap.push_back(dimensions[batchRank + 1]);
1699 bMap.push_back(dimensions[batchRank + 2]);
1700 SmallVector<AffineExpr> outputMap(dimensions.begin(),
1701 dimensions.begin() + batchRank);
1702 outputMap.push_back(dimensions[batchRank]);
1703 outputMap.push_back(dimensions[batchRank + 1]);
1704 SmallVector<AffineMap> indexingMaps = {
1705 AffineMap::get(loopRank, 0, aMap, rewriter.getContext()),
1706 AffineMap::get(loopRank, 0, bMap, rewriter.getContext()),
1707 AffineMap::get(loopRank, 0, outputMap, rewriter.getContext())};
1708 SmallVector<utils::IteratorType> iteratorTypes(
1709 loopRank, utils::IteratorType::parallel);
1710 iteratorTypes.back() = utils::IteratorType::reduction;
1711
1712 auto generic = linalg::GenericOp::create(
1713 rewriter, loc, outputType, ValueRange{a, b}, zeroTensor, indexingMaps,
1714 iteratorTypes,
1715 [=](OpBuilder &builder, Location nestedLoc, ValueRange args) {
1716 auto extendToOutputType = [&](Value value) {
1717 if (value.getType() == outputElementType)
1718 return value;
1719 return arith::ExtSIOp::create(builder, nestedLoc, outputElementType,
1720 value)
1721 .getResult();
1722 };
1723
1724 Value aValue = extendToOutputType(args[0]);
1725 Value bValue = extendToOutputType(args[1]);
1726 Value aZp = arith::ConstantOp::create(
1727 builder, nestedLoc,
1728 builder.getIntegerAttr(outputElementType, aZpVal));
1729 Value bZp = arith::ConstantOp::create(
1730 builder, nestedLoc,
1731 builder.getIntegerAttr(outputElementType, bZpVal));
1732 Value adjustedA =
1733 arith::SubIOp::create(builder, nestedLoc, aValue, aZp);
1734 Value adjustedB =
1735 arith::SubIOp::create(builder, nestedLoc, bValue, bZp);
1736 Value product =
1737 arith::MulIOp::create(builder, nestedLoc, adjustedA, adjustedB);
1738 Value sum =
1739 arith::AddIOp::create(builder, nestedLoc, args[2], product);
1740 linalg::YieldOp::create(builder, nestedLoc, sum);
1741 });
1742 rewriter.replaceOp(op, generic.getResult(0));
1743 return success();
1744 }
1745};
1746
1747template <typename SrcOp>
1748class PointwiseConverter : public OpConversionPattern<SrcOp> {
1749public:
1750 using OpConversionPattern<SrcOp>::OpConversionPattern;
1751 using typename OpConversionPattern<SrcOp>::OpAdaptor;
1752
1753 LogicalResult
1754 matchAndRewrite(SrcOp op, OpAdaptor operands,
1755 ConversionPatternRewriter &rewriter) const final {
1757 op, operands.getOperands(), rewriter, *this->getTypeConverter());
1758 }
1759};
1760
1761// Collapse tensor<1xiN> into tensor<iN>
1762// E.g. tensor.collapse_shape %arg1 [] : tensor<1xi16> into tensor<i16>
1763static Value collapse1xNTensorToN(PatternRewriter &rewriter, Value input,
1764 Location loc) {
1766 // Create the collapsed type
1767 auto inputType = cast<RankedTensorType>(input.getType());
1768 auto elemType = inputType.getElementType();
1769 auto collapsedType = RankedTensorType::get({}, elemType);
1770 // Emit the collapse op
1771 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType, input,
1772 reassociation);
1773}
1774
1776convertToI8(const llvm::SmallVector<int32_t> &input) {
1778 output.reserve(input.size());
1779
1780 for (auto v : llvm::map_range(
1781 input, [](int32_t val) { return static_cast<int8_t>(val); })) {
1782 output.push_back(v);
1783 }
1784 return output;
1785}
1786
1787// The shift or multiplier may be either constant or non-constant, depending on
1788// whether dynamic extension is enabled.
1789// - If the shift or multiplier is non-constant, add it as an input to
1790// linalg::GenericOp by:
1791// 1. Pushing it into 'genericInputs'.
1792// 2. Appending a corresponding affine map to 'indexingMaps'.
1793// - If the shift or multiplier is constant, set 'constant' instead.
1794static void setupLinalgGenericOpInputAndIndexingMap(
1796 SmallVector<Value, 4> &genericInputs, SmallVector<AffineMap> &indexingMaps,
1797 bool isConstant, tosa::RescaleOp op, Value &constant, int64_t &arg,
1798 bool isShift = false) {
1799
1800 assert(!(isConstant && values.empty()) &&
1801 "constant rescale operand must have values");
1802
1803 auto loc = op.getLoc();
1804 auto inputTy = cast<ShapedType>(op.getInput().getType());
1805 unsigned rank = inputTy.getRank();
1806 SmallVector<AffineExpr, 2> exprs = {rewriter.getAffineDimExpr(rank - 1)};
1807
1808 if (isConstant) {
1809 // If we are rescaling per-channel then we need to store the
1810 // values in a buffer.
1811 if (values.size() == 1) {
1812 IntegerAttr intAttr = isShift
1813 ? rewriter.getI8IntegerAttr(values.front())
1814 : rewriter.getI32IntegerAttr(values.front());
1815 constant = arith::ConstantOp::create(rewriter, loc, intAttr);
1816 } else {
1817 auto elementType =
1818 isShift ? rewriter.getIntegerType(8) : rewriter.getI32Type();
1819 auto tensorType = RankedTensorType::get(
1820 {static_cast<int64_t>(values.size())}, elementType);
1821 DenseIntElementsAttr EltAttr;
1822 if (isShift)
1823 EltAttr = DenseIntElementsAttr::get(tensorType, convertToI8(values));
1824 else
1825 EltAttr = DenseIntElementsAttr::get(tensorType, values);
1826 genericInputs.push_back(
1827 arith::ConstantOp::create(rewriter, loc, EltAttr));
1828 indexingMaps.push_back(AffineMap::get(/*dimCount=*/rank,
1829 /*symbolCount=*/0, exprs,
1830 rewriter.getContext()));
1831 }
1832 } else {
1833 // If we are not rescaling per-channel then we need to collapse 1xN to N
1834 // and push broadcastMap.
1835 auto operand = isShift ? op.getShift() : op.getMultiplier();
1836 auto tensorType = dyn_cast<RankedTensorType>(operand.getType());
1837 if (tensorType && tensorType.hasStaticShape() &&
1838 tensorType.getShape()[0] == 1) {
1839 // broadcastMap = affine_map<(d0, d1) -> ()>
1840 // It would affect as broadcast for scalar values in linalg::GenericOp.
1841 AffineMap broadcastMap =
1842 AffineMap::get(rank, 0, {}, rewriter.getContext());
1843 genericInputs.push_back(collapse1xNTensorToN(rewriter, operand, loc));
1844 indexingMaps.push_back(broadcastMap);
1845 } else {
1846 genericInputs.push_back(operand);
1847 indexingMaps.push_back(AffineMap::get(/*dimCount=*/rank,
1848 /*symbolCount=*/0, exprs,
1849 rewriter.getContext()));
1850 }
1851 }
1852 arg = indexingMaps.size() - 1;
1853}
1854
1855// Return the extended Zp to be used in subsequent arithmetic operations.
1856static Value getExtendZp(OpBuilder &builder, Type valueTy,
1857 FailureOr<int64_t> maybeZp, Location loc,
1858 ValueRange blockArgs, int64_t zpArg,
1859 bool isOutputZp = false) {
1860 Value result;
1861 const int32_t bitwidth = valueTy.getIntOrFloatBitWidth();
1862 const uint32_t attrBitwidth =
1863 isOutputZp ? 32 : (bitwidth > 32 ? bitwidth : 32);
1864 auto extendType = builder.getIntegerType(attrBitwidth);
1865 // The Zp value can be either constant or non-constant, depending on
1866 // whether dynamic extension is enabled.
1867 // If 'maybeZp' fails, it indicates that Zp is non-constant and will
1868 // be passed as an input to linalg::GenericOp.
1869 if (failed(maybeZp)) {
1870 result = blockArgs[zpArg];
1871 auto zpTy = result.getType();
1872 if (zpTy.getIntOrFloatBitWidth() < attrBitwidth) {
1873 // For ExtUIOp, the input must be signless.
1874 // UnrealizedConversionCastOp will cast the input to signless type.
1875 if (zpTy.isUnsignedInteger()) {
1876 result =
1877 UnrealizedConversionCastOp::create(
1878 builder, loc,
1879 builder.getIntegerType(zpTy.getIntOrFloatBitWidth()), result)
1880 .getResult(0);
1881 }
1882 if (zpTy.isUnsignedInteger()) {
1883 return arith::ExtUIOp::create(builder, loc, extendType, result);
1884 } else {
1885 return arith::ExtSIOp::create(builder, loc, extendType, result);
1886 }
1887 }
1888 } else {
1889 return arith::ConstantOp::create(builder, loc,
1890 IntegerAttr::get(extendType, *maybeZp));
1891 }
1892 return result;
1893}
1894
1895class RescaleConverter : public OpRewritePattern<tosa::RescaleOp> {
1896public:
1897 using OpRewritePattern<tosa::RescaleOp>::OpRewritePattern;
1898
1899 LogicalResult matchAndRewrite(tosa::RescaleOp op,
1900 PatternRewriter &rewriter) const final {
1901 auto loc = op.getLoc();
1902 auto input = op.getInput();
1903 auto inputTy = cast<ShapedType>(op.getInput().getType());
1904 auto outputTy = cast<ShapedType>(op.getOutput().getType());
1905 unsigned rank = inputTy.getRank();
1906
1907 // This is an illegal configuration. terminate and log an error
1908 if (op.getRoundingMode() == RoundingMode::INEXACT_ROUND)
1909 return rewriter.notifyMatchFailure(
1910 op, "tosa.rescale with rounding mode = 'INEXACT_ROUND' is not "
1911 "currently supported");
1912 if (op.getRoundingMode() == RoundingMode::DOUBLE_ROUND && !op.getScale32())
1913 return rewriter.notifyMatchFailure(
1914 op, "tosa.rescale requires scale32 for double_round to be true");
1915
1916 if (!isa<IntegerType>(inputTy.getElementType()))
1917 return rewriter.notifyMatchFailure(op, "only support integer type");
1918
1919 // The generic body computes in i32 and saturates to the output type.
1920 auto outputElemTy = dyn_cast<IntegerType>(outputTy.getElementType());
1921 if (!outputElemTy || outputElemTy.getWidth() > 32)
1922 return rewriter.notifyMatchFailure(
1923 op, "only support integer output types up to 32 bits");
1924
1925 // Zero points are already validated by tosa-validate under
1926 // strict-op-spec-alignment, but reject invalid values here as well so
1927 // that conversion without validation fails instead of silently
1928 // generating incorrect arithmetic.
1929 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1930 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1931 return rewriter.notifyMatchFailure(op, "unsupported input zero point");
1932 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1933 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1934 return rewriter.notifyMatchFailure(op, "unsupported output zero point");
1935
1936 SmallVector<Value> dynDims;
1937 for (int i = 0; i < outputTy.getRank(); i++) {
1938 if (outputTy.isDynamicDim(i)) {
1939 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1940 }
1941 }
1942
1943 DenseElementsAttr shiftElems;
1944 bool isShiftConstant = matchPattern(op.getShift(), m_Constant(&shiftElems));
1945 DenseElementsAttr multiplierElems;
1946 bool isMultiplierConstant =
1947 matchPattern(op.getMultiplier(), m_Constant(&multiplierElems));
1948
1949 llvm::SmallVector<int32_t> shiftValues;
1950 llvm::SmallVector<int32_t> multiplierValues;
1951 bool doubleRound;
1952 if (isMultiplierConstant) {
1953 multiplierValues =
1954 llvm::map_to_vector(multiplierElems.getValues<IntegerAttr>(),
1955 [](IntegerAttr attr) -> int32_t {
1956 return static_cast<int32_t>(attr.getInt());
1957 });
1958 }
1959 if (isShiftConstant) {
1960 shiftValues = llvm::map_to_vector(
1961 shiftElems.getValues<IntegerAttr>(), [](IntegerAttr attr) -> int32_t {
1962 return static_cast<int32_t>(attr.getInt());
1963 });
1964 }
1965 if (isMultiplierConstant && isShiftConstant) {
1966 // If we shift by more than the bitwidth, this just sets to 0.
1967 for (int i = 0, s = multiplierValues.size(); i < s; i++) {
1968 if (shiftValues[i] > 63) {
1969 shiftValues[i] = 0;
1970 multiplierValues[i] = 0;
1971 }
1972 }
1973 // Double round only occurs if shift is greater than 31, check that this
1974 // is ever true.
1975 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND &&
1976 llvm::any_of(shiftValues, [](int32_t v) { return v > 31; });
1977 } else
1978 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND;
1979
1980 RoundingMode roundingMode =
1981 doubleRound ? RoundingMode::DOUBLE_ROUND : RoundingMode::SINGLE_ROUND;
1982
1983 SmallVector<AffineMap> indexingMaps = {
1984 rewriter.getMultiDimIdentityMap(rank)};
1985 SmallVector<Value, 4> genericInputs = {input};
1986
1987 // If we are rescaling per-channel then we need to store the multiplier
1988 // values in a buffer.
1989 Value multiplierConstant;
1990 int64_t multiplierArg = 0;
1991 setupLinalgGenericOpInputAndIndexingMap(
1992 rewriter, multiplierValues, genericInputs, indexingMaps,
1993 isMultiplierConstant, op, multiplierConstant, multiplierArg);
1994
1995 // If we are rescaling per-channel then we need to store the shift
1996 // values in a buffer.
1997 Value shiftConstant;
1998 int64_t shiftArg = 0;
1999 setupLinalgGenericOpInputAndIndexingMap(
2000 rewriter, shiftValues, genericInputs, indexingMaps, isShiftConstant, op,
2001 shiftConstant, shiftArg, true);
2002
2003 // broadcastMap = affine_map<(d0, d1) -> ()>
2004 // It would affect as broadcast for scalar values in linalg::GenericOp.
2005 AffineMap broadcastMap = AffineMap::get(rank, 0, {}, rewriter.getContext());
2006 // The inputZp and outputZp may be either constant or non-constant,
2007 // depending on whether dynamic extension is enabled.
2008 // - If the zp's are non-constant, add them as an inputs to
2009 // linalg::GenericOp by:
2010 // 1. Pushing it into 'genericInputs'.
2011 // 2. Appending a corresponding affine map to 'indexingMaps'.
2012 // - If the zp's are constant, they would be generated as arith.constant.
2013 int64_t iZpArg = 0;
2014 if (failed(maybeIZp)) {
2015 genericInputs.push_back(
2016 collapse1xNTensorToN(rewriter, op->getOperand(3), loc));
2017 indexingMaps.push_back(broadcastMap);
2018 iZpArg = indexingMaps.size() - 1;
2019 }
2020 int64_t oZpArg = 0;
2021 if (failed(maybeOZp)) {
2022 genericInputs.push_back(
2023 collapse1xNTensorToN(rewriter, op->getOperand(4), loc));
2024 indexingMaps.push_back(broadcastMap);
2025 oZpArg = indexingMaps.size() - 1;
2026 }
2027
2028 // Indexing maps for output values.
2029 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
2030
2031 // Construct the indexing maps needed for linalg.generic ops.
2032 Value emptyTensor = tensor::EmptyOp::create(
2033 rewriter, loc, outputTy.getShape(), outputTy.getElementType(),
2034 ArrayRef<Value>({dynDims}));
2035
2036 auto linalgOp = linalg::GenericOp::create(
2037 rewriter, loc, outputTy, genericInputs, ValueRange{emptyTensor},
2038 indexingMaps, getNParallelLoopsAttrs(rank),
2039 [&](OpBuilder &nestedBuilder, Location nestedLoc,
2040 ValueRange blockArgs) {
2041 Value value = blockArgs[0];
2042 Type valueTy = value.getType();
2043
2044 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
2045 auto inputZp = getExtendZp(nestedBuilder, valueTy, maybeIZp,
2046 nestedLoc, blockArgs, iZpArg);
2047
2048 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
2049 auto outputZp = getExtendZp(nestedBuilder, valueTy, maybeOZp,
2050 nestedLoc, blockArgs, oZpArg, true);
2051
2052 IntegerType outIntType =
2053 cast<IntegerType>(blockArgs.back().getType());
2054 unsigned outBitWidth = outIntType.getWidth();
2055 assert(outBitWidth <= 32 && "Unexpected output zeropoint bitwidth");
2056
2057 Value multiplier = multiplierConstant ? multiplierConstant
2058 : blockArgs[multiplierArg];
2059 Value shift = shiftConstant ? shiftConstant : blockArgs[shiftArg];
2060
2061 if (valueTy.isUnsignedInteger()) {
2062 value = UnrealizedConversionCastOp::create(
2063 nestedBuilder, nestedLoc,
2064 nestedBuilder.getIntegerType(
2065 valueTy.getIntOrFloatBitWidth()),
2066 value)
2067 .getResult(0);
2068 }
2069 if (valueTy.getIntOrFloatBitWidth() < 32) {
2070 if (op.getInputUnsigned()) {
2071 value = arith::ExtUIOp::create(nestedBuilder, nestedLoc,
2072 nestedBuilder.getI32Type(), value);
2073 } else {
2074 value = arith::ExtSIOp::create(nestedBuilder, nestedLoc,
2075 nestedBuilder.getI32Type(), value);
2076 }
2077 }
2078
2079 value =
2080 arith::SubIOp::create(nestedBuilder, nestedLoc, value, inputZp);
2081
2082 value = tosa::ApplyScaleOp::create(nestedBuilder, loc,
2083 nestedBuilder.getI32Type(), value,
2084 multiplier, shift, roundingMode);
2085
2086 // Move to the new zero-point.
2087 value =
2088 arith::AddIOp::create(nestedBuilder, nestedLoc, value, outputZp);
2089
2090 // Saturate to the output size.
2091 int32_t intMin = APInt::getSignedMinValue(outBitWidth).getSExtValue();
2092 int32_t intMax = APInt::getSignedMaxValue(outBitWidth).getSExtValue();
2093
2094 // Unsigned integers have a difference output value.
2095 if (op.getOutputUnsigned()) {
2096 intMin = 0;
2097 intMax = APInt::getMaxValue(outBitWidth).getZExtValue();
2098 }
2099
2100 auto intMinVal = arith::ConstantOp::create(
2101 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMin));
2102 auto intMaxVal = arith::ConstantOp::create(
2103 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMax));
2104
2105 value = clampIntHelper(nestedLoc, value, intMinVal, intMaxVal,
2106 nestedBuilder, /*isUnsigned=*/false);
2107
2108 if (outIntType.getWidth() < 32) {
2109 value = arith::TruncIOp::create(
2110 nestedBuilder, nestedLoc,
2111 rewriter.getIntegerType(outIntType.getWidth()), value);
2112 }
2113
2114 if (outIntType.isUnsignedInteger()) {
2115 value = UnrealizedConversionCastOp::create(nestedBuilder, nestedLoc,
2116 outIntType, value)
2117 .getResult(0);
2118 }
2119 linalg::YieldOp::create(nestedBuilder, loc, value);
2120 });
2121
2122 rewriter.replaceOp(op, linalgOp->getResults());
2123 return success();
2124 }
2125};
2126
2127// Handle the resize case where the input is a 1x1 image. This case
2128// can entirely avoiding having extract operations which target much
2129// more difficult to optimize away.
2130class ResizeUnaryConverter : public OpRewritePattern<tosa::ResizeOp> {
2131public:
2132 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2133
2134 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2135 PatternRewriter &rewriter) const final {
2136 Location loc = op.getLoc();
2137 ImplicitLocOpBuilder builder(loc, rewriter);
2138 auto input = op.getInput();
2139 auto inputTy = cast<RankedTensorType>(input.getType());
2140 auto resultTy = cast<RankedTensorType>(op.getType());
2141 const bool isBilinear = op.getMode() == ResizeMode::BILINEAR;
2142
2143 auto inputH = inputTy.getDimSize(1);
2144 auto inputW = inputTy.getDimSize(2);
2145 auto outputH = resultTy.getDimSize(1);
2146 auto outputW = resultTy.getDimSize(2);
2147
2148 if (inputH != 1 || inputW != 1 || outputH != 1 || outputW != 1)
2149 return rewriter.notifyMatchFailure(
2150 op, "tosa.resize is not a pure 1x1->1x1 image operation");
2151
2152 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2153 op.getMode() != ResizeMode::BILINEAR)
2154 return rewriter.notifyMatchFailure(
2155 op, "tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2156
2157 if (inputTy == resultTy) {
2158 rewriter.replaceOp(op, input);
2159 return success();
2160 }
2161
2162 SmallVector<int64_t> scale;
2163 if (!tosa::getConstShapeValues(op.getScale().getDefiningOp(), scale)) {
2164 return failure();
2165 }
2166
2167 // Collapse the unit width and height away.
2168 SmallVector<ReassociationExprs, 4> reassociationMap(2);
2169 reassociationMap[0].push_back(builder.getAffineDimExpr(0));
2170 reassociationMap[1].push_back(builder.getAffineDimExpr(1));
2171 reassociationMap[1].push_back(builder.getAffineDimExpr(2));
2172 reassociationMap[1].push_back(builder.getAffineDimExpr(3));
2173
2174 auto collapseTy =
2175 RankedTensorType::get({inputTy.getDimSize(0), inputTy.getDimSize(3)},
2176 inputTy.getElementType());
2177 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy, input,
2178 reassociationMap);
2179
2180 // Get any dynamic shapes that appear in the input format.
2181 llvm::SmallVector<Value> outputDynSize;
2182 if (inputTy.isDynamicDim(0))
2183 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2184 if (inputTy.isDynamicDim(3))
2185 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2186
2187 // Generate the elementwise operation for casting scaling the input value.
2188 auto genericTy = collapseTy.clone(resultTy.getElementType());
2189 Value empty =
2190 tensor::EmptyOp::create(builder, genericTy.getShape(),
2191 resultTy.getElementType(), outputDynSize);
2192 auto genericMap = rewriter.getMultiDimIdentityMap(genericTy.getRank());
2193 SmallVector<utils::IteratorType> iterators(genericTy.getRank(),
2194 utils::IteratorType::parallel);
2195
2196 auto generic = linalg::GenericOp::create(
2197 builder, genericTy, ValueRange{collapse}, ValueRange{empty},
2198 ArrayRef<AffineMap>{genericMap, genericMap}, iterators,
2199 [=](OpBuilder &b, Location loc, ValueRange args) {
2200 Value value = args[0];
2201 // This is the quantized case.
2202 if (inputTy.getElementType() != resultTy.getElementType()) {
2203 value = arith::ExtSIOp::create(b, loc, resultTy.getElementType(),
2204 value);
2205
2206 if (isBilinear && scale[0] != 0) {
2207 Value scaleY = arith::ConstantOp::create(
2208 b, loc, b.getI32IntegerAttr(scale[0]));
2209 value = arith::MulIOp::create(b, loc, value, scaleY);
2210 }
2211
2212 if (isBilinear && scale[2] != 0) {
2213 Value scaleX = arith::ConstantOp::create(
2214 b, loc, b.getI32IntegerAttr(scale[2]));
2215 value = arith::MulIOp::create(b, loc, value, scaleX);
2216 }
2217 }
2218
2219 linalg::YieldOp::create(b, loc, value);
2220 });
2221
2222 rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(
2223 op, resultTy, generic.getResults()[0], reassociationMap);
2224 return success();
2225 }
2226};
2227
2228// TOSA resize with width or height of 1 may be broadcasted to a wider
2229// dimension. This is done by materializing a new tosa.resize without
2230// the broadcasting behavior, and an explicit broadcast afterwards.
2231class MaterializeResizeBroadcast : public OpRewritePattern<tosa::ResizeOp> {
2232public:
2233 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2234
2235 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2236 PatternRewriter &rewriter) const final {
2237 Location loc = op.getLoc();
2238 ImplicitLocOpBuilder builder(loc, rewriter);
2239 auto input = op.getInput();
2240 auto inputTy = dyn_cast<RankedTensorType>(input.getType());
2241 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2242
2243 if (!inputTy || !resultTy)
2244 return rewriter.notifyMatchFailure(op,
2245 "requires ranked input/output types");
2246
2247 auto batch = inputTy.getDimSize(0);
2248 auto channels = inputTy.getDimSize(3);
2249 auto inputH = inputTy.getDimSize(1);
2250 auto inputW = inputTy.getDimSize(2);
2251 auto outputH = resultTy.getDimSize(1);
2252 auto outputW = resultTy.getDimSize(2);
2253
2254 if ((inputH != 1 || outputH == 1) && (inputW != 1 || outputW == 1))
2255 return rewriter.notifyMatchFailure(
2256 op, "tosa.resize has no broadcasting behavior");
2257
2258 // For any dimension that is broadcastable we generate a width of 1
2259 // on the output.
2260 llvm::SmallVector<int64_t> resizeShape;
2261 resizeShape.push_back(batch);
2262 resizeShape.push_back(inputH == 1 ? 1 : outputH);
2263 resizeShape.push_back(inputW == 1 ? 1 : outputW);
2264 resizeShape.push_back(channels);
2265
2266 auto resizeTy = resultTy.clone(resizeShape);
2267 auto resize =
2268 tosa::ResizeOp::create(builder, resizeTy, input, op.getScale(),
2269 op.getOffset(), op.getBorder(), op.getMode());
2270
2271 // Collapse an unit result dims.
2272 SmallVector<ReassociationExprs, 4> reassociationMap(2);
2273 reassociationMap[0].push_back(builder.getAffineDimExpr(0));
2274 reassociationMap.back().push_back(builder.getAffineDimExpr(1));
2275 if (inputH != 1)
2276 reassociationMap.push_back({});
2277 reassociationMap.back().push_back(builder.getAffineDimExpr(2));
2278 if (inputW != 1)
2279 reassociationMap.push_back({});
2280 reassociationMap.back().push_back(builder.getAffineDimExpr(3));
2281
2282 llvm::SmallVector<int64_t> collapseShape = {batch};
2283 if (inputH != 1)
2284 collapseShape.push_back(outputH);
2285 if (inputW != 1)
2286 collapseShape.push_back(outputW);
2287 collapseShape.push_back(channels);
2288
2289 auto collapseTy = resultTy.clone(collapseShape);
2290 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy,
2291 resize, reassociationMap);
2292
2293 // Broadcast the collapsed shape to the output result.
2294 llvm::SmallVector<Value> outputDynSize;
2295 if (inputTy.isDynamicDim(0))
2296 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2297 if (inputTy.isDynamicDim(3))
2298 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2299
2300 SmallVector<utils::IteratorType> iterators(resultTy.getRank(),
2301 utils::IteratorType::parallel);
2302 Value empty = tensor::EmptyOp::create(
2303 builder, resultTy.getShape(), resultTy.getElementType(), outputDynSize);
2304
2305 SmallVector<AffineExpr, 4> inputExprs{rewriter.getAffineDimExpr(0)};
2306 if (inputH != 1)
2307 inputExprs.push_back(rewriter.getAffineDimExpr(1));
2308 if (inputW != 1)
2309 inputExprs.push_back(rewriter.getAffineDimExpr(2));
2310 inputExprs.push_back(rewriter.getAffineDimExpr(3));
2311
2312 auto inputMap = AffineMap::get(resultTy.getRank(), /*symbolCount=*/0,
2313 inputExprs, rewriter.getContext());
2314
2315 auto outputMap = rewriter.getMultiDimIdentityMap(resultTy.getRank());
2316 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
2317 op, resultTy, ValueRange{collapse}, ValueRange{empty},
2318 ArrayRef<AffineMap>{inputMap, outputMap}, iterators,
2319 [=](OpBuilder &b, Location loc, ValueRange args) {
2320 Value value = args[0];
2321 linalg::YieldOp::create(b, loc, value);
2322 });
2323
2324 return success();
2325 }
2326};
2327
2328class GenericResizeConverter : public OpRewritePattern<tosa::ResizeOp> {
2329public:
2330 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2331
2332 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2333 PatternRewriter &rewriter) const final {
2334 Location loc = op.getLoc();
2335 ImplicitLocOpBuilder b(loc, rewriter);
2336 auto input = op.getInput();
2337 auto inputTy = cast<ShapedType>(input.getType());
2338 auto resultTy = cast<ShapedType>(op.getType());
2339 auto resultETy = resultTy.getElementType();
2340
2341 bool floatingPointMode = isa<FloatType>(resultETy);
2342 auto floatTy = resultETy;
2343
2344 auto imageH = inputTy.getShape()[1];
2345 auto imageW = inputTy.getShape()[2];
2346
2347 auto dynamicDimsOr =
2348 checkHasDynamicBatchDims(rewriter, op, {input, op.getOutput()});
2349 if (!dynamicDimsOr.has_value())
2350 return rewriter.notifyMatchFailure(
2351 op, "unable to get dynamic dimensions of tosa.resize");
2352
2353 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2354 op.getMode() != ResizeMode::BILINEAR)
2355 return rewriter.notifyMatchFailure(
2356 op, "tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2357
2358 SmallVector<AffineMap, 2> affineMaps = {
2359 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2360 auto emptyTensor = tensor::EmptyOp::create(b, resultTy.getShape(),
2361 resultETy, *dynamicDimsOr);
2362 auto genericOp = linalg::GenericOp::create(
2363 b, resultTy, ValueRange({}), ValueRange{emptyTensor}, affineMaps,
2364 getNParallelLoopsAttrs(resultTy.getRank()));
2365 Value resize = genericOp.getResult(0);
2366
2367 {
2368 OpBuilder::InsertionGuard regionGuard(b);
2369 b.createBlock(&genericOp.getRegion(), genericOp.getRegion().end(),
2370 TypeRange({resultETy}), loc);
2371 Value batch = linalg::IndexOp::create(b, 0);
2372 Value y = linalg::IndexOp::create(b, 1);
2373 Value x = linalg::IndexOp::create(b, 2);
2374 Value channel = linalg::IndexOp::create(b, 3);
2375
2376 Value zeroI32 =
2377 arith::ConstantOp::create(b, b.getZeroAttr(b.getI32Type()));
2378 Value zeroFp = arith::ConstantOp::create(b, b.getZeroAttr(floatTy));
2379 Value hMax =
2380 arith::ConstantOp::create(b, b.getI32IntegerAttr(imageH - 1));
2381 Value wMax =
2382 arith::ConstantOp::create(b, b.getI32IntegerAttr(imageW - 1));
2383
2384 Value inY = arith::IndexCastOp::create(b, b.getI32Type(), y);
2385 Value inX = arith::IndexCastOp::create(b, b.getI32Type(), x);
2386
2387 SmallVector<int64_t> scale, offset, border;
2388 if (!tosa::getConstShapeValues(op.getScale().getDefiningOp(), scale) ||
2389 !tosa::getConstShapeValues(op.getOffset().getDefiningOp(), offset) ||
2390 !tosa::getConstShapeValues(op.getBorder().getDefiningOp(), border)) {
2391 return rewriter.notifyMatchFailure(
2392 op, "tosa.resize scale/offset/border should have compile time "
2393 "constant values.");
2394 }
2395
2396 Value yScaleN, yScaleD, xScaleN, xScaleD;
2397 yScaleN = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[0]));
2398 yScaleD = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[1]));
2399 xScaleN = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[2]));
2400 xScaleD = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[3]));
2401
2402 Value yOffset, xOffset, yBorder, xBorder;
2403 yOffset = arith::ConstantOp::create(b, b.getI32IntegerAttr(offset[0]));
2404 xOffset = arith::ConstantOp::create(b, b.getI32IntegerAttr(offset[1]));
2405 yBorder = arith::ConstantOp::create(b, b.getI32IntegerAttr(border[0]));
2406 xBorder = arith::ConstantOp::create(b, b.getI32IntegerAttr(border[1]));
2407
2408 // Compute the ix and dx values for both the X and Y dimensions.
2409 auto getIndexAndDeltaFp = [&](Value &index, Value &delta, Value in,
2410 Value scaleN, Value scaleD, Value offset,
2411 int size, ImplicitLocOpBuilder &b) {
2412 if (size == 1) {
2413 index = zeroI32;
2414 delta = zeroFp;
2415 return;
2416 }
2417 // x = x * scale_d + offset;
2418 // ix = floor(x / scale_n)
2419 Value val = arith::MulIOp::create(b, in, scaleD);
2420 val = arith::AddIOp::create(b, val, offset);
2421 index = arith::FloorDivSIOp::create(b, val, scaleN);
2422
2423 // rx = x - ix * scale_n (x % scale_n, if values are positive)
2424 Value scaledIndex = arith::MulIOp::create(b, index, scaleN);
2425 Value r = arith::SubIOp::create(b, val, scaledIndex);
2426 Value rFp = arith::SIToFPOp::create(b, floatTy, r);
2427
2428 // dx = rx / scale_n
2429 Value scaleNfp = arith::UIToFPOp::create(b, floatTy, scaleN);
2430 delta = arith::DivFOp::create(b, rFp, scaleNfp);
2431 };
2432
2433 // Compute the ix and dx values for the X and Y dimensions - int case.
2434 auto getIndexAndDeltaInt = [&](Value &index, Value &delta, Value in,
2435 Value scaleN, Value scaleD, Value offset,
2436 int size, ImplicitLocOpBuilder &b) {
2437 if (size == 1) {
2438 index = zeroI32;
2439 delta = zeroI32;
2440 return;
2441 }
2442 // x = x * scale_d + offset;
2443 // ix = floor(x / scale_n)
2444 // dx = x - ix * scale_n;
2445 Value val = arith::MulIOp::create(b, in, scaleD);
2446 val = arith::AddIOp::create(b, val, offset);
2447 index = arith::FloorDivSIOp::create(b, val, scaleN);
2448 delta = arith::MulIOp::create(b, index, scaleN);
2449 delta = arith::SubIOp::create(b, val, delta);
2450 };
2451
2452 Value ix, iy, dx, dy;
2453 if (floatingPointMode) {
2454 getIndexAndDeltaFp(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH, b);
2455 getIndexAndDeltaFp(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW, b);
2456 } else {
2457 getIndexAndDeltaInt(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH, b);
2458 getIndexAndDeltaInt(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW, b);
2459 }
2460
2461 if (op.getMode() == ResizeMode::NEAREST_NEIGHBOR) {
2462 auto one = arith::ConstantOp::create(b, b.getI32IntegerAttr(1));
2463
2464 auto getNearestIndexAndClamp = [&](Value val, Value dval, Value scale,
2465 Value max, int size,
2466 ImplicitLocOpBuilder &b) -> Value {
2467 if (size == 1) {
2469 }
2470
2471 Value pred;
2472 if (floatingPointMode) {
2473 auto h =
2474 arith::ConstantOp::create(b, b.getFloatAttr(floatTy, 0.5f));
2475 pred = arith::CmpFOp::create(b, arith::CmpFPredicate::OGE, dval, h);
2476 } else {
2477 Value dvalDouble = arith::ShLIOp::create(b, dval, one);
2478 pred = arith::CmpIOp::create(b, arith::CmpIPredicate::sge,
2479 dvalDouble, scale);
2480 }
2481
2482 auto offset = arith::SelectOp::create(b, pred, one, zeroI32);
2483 val = arith::AddIOp::create(b, val, offset);
2484 val = clampIntHelper(loc, val, zeroI32, max, b, /*isUnsigned=*/false);
2485 return arith::IndexCastOp::create(b, b.getIndexType(), val);
2486 };
2487
2488 iy = getNearestIndexAndClamp(iy, dy, yScaleN, hMax, imageH, b);
2489 ix = getNearestIndexAndClamp(ix, dx, xScaleN, wMax, imageW, b);
2490
2491 Value result = tensor::ExtractOp::create(
2492 b, input, ValueRange{batch, iy, ix, channel});
2493
2494 linalg::YieldOp::create(b, result);
2495 } else {
2496 // The mode here must be BILINEAR.
2497 assert(op.getMode() == ResizeMode::BILINEAR);
2498
2499 auto oneVal = arith::ConstantOp::create(b, b.getI32IntegerAttr(1));
2500
2501 auto getClampedIdxs = [&](Value &val0, Value &val1, int size, Value in,
2502 Value max, ImplicitLocOpBuilder &b) {
2503 val0 = in;
2504 val1 = arith::AddIOp::create(b, val0, oneVal);
2505 val0 =
2506 clampIntHelper(loc, val0, zeroI32, max, b, /*isUnsigned=*/false);
2507 val1 =
2508 clampIntHelper(loc, val1, zeroI32, max, b, /*isUnsigned=*/false);
2509 val0 = arith::IndexCastOp::create(b, b.getIndexType(), val0);
2510 val1 = arith::IndexCastOp::create(b, b.getIndexType(), val1);
2511 };
2512
2513 // Linalg equivalent to the section below:
2514 // int16_t iy0 = apply_max(iy, 0);
2515 // int16_t iy1 = apply_min(iy + 1, IH - 1);
2516 // int16_t ix0 = apply_max(ix, 0);
2517 // int16_t ix1 = apply_min(ix + 1, IW - 1);
2518 Value x0, x1, y0, y1;
2519 getClampedIdxs(y0, y1, imageH, iy, hMax, b);
2520 getClampedIdxs(x0, x1, imageW, ix, wMax, b);
2521
2522 Value y0x0 = tensor::ExtractOp::create(
2523 b, input, ValueRange{batch, y0, x0, channel});
2524 Value y0x1 = tensor::ExtractOp::create(
2525 b, input, ValueRange{batch, y0, x1, channel});
2526 Value y1x0 = tensor::ExtractOp::create(
2527 b, input, ValueRange{batch, y1, x0, channel});
2528 Value y1x1 = tensor::ExtractOp::create(
2529 b, input, ValueRange{batch, y1, x1, channel});
2530
2531 if (floatingPointMode) {
2532 auto oneVal =
2533 arith::ConstantOp::create(b, b.getFloatAttr(floatTy, 1.0f));
2534 auto interpolate = [&](Value val0, Value val1, Value delta,
2535 int inputSize,
2536 ImplicitLocOpBuilder &b) -> Value {
2537 if (inputSize == 1)
2538 return val0;
2539 Value oneMinusDelta = arith::SubFOp::create(b, oneVal, delta);
2540 Value mul0 = arith::MulFOp::create(b, val0, oneMinusDelta);
2541 Value mul1 = arith::MulFOp::create(b, val1, delta);
2542 return arith::AddFOp::create(b, mul0, mul1);
2543 };
2544
2545 // Linalg equivalent to the section below:
2546 // topAcc = v00 * (unit_x - dx);
2547 // topAcc += v01 * dx;
2548 Value topAcc = interpolate(y0x0, y0x1, dx, imageW, b);
2549
2550 // Linalg equivalent to the section below:
2551 // bottomAcc = v10 * (unit_x - dx);
2552 // bottomAcc += v11 * dx;
2553 Value bottomAcc = interpolate(y1x0, y1x1, dx, imageW, b);
2554
2555 // Linalg equivalent to the section below:
2556 // result = topAcc * (unit_y - dy) + bottomAcc * dy
2557 Value result = interpolate(topAcc, bottomAcc, dy, imageH, b);
2558 linalg::YieldOp::create(b, result);
2559 } else {
2560 // Perform in quantized space.
2561 y0x0 = arith::ExtSIOp::create(b, resultETy, y0x0);
2562 y0x1 = arith::ExtSIOp::create(b, resultETy, y0x1);
2563 y1x0 = arith::ExtSIOp::create(b, resultETy, y1x0);
2564 y1x1 = arith::ExtSIOp::create(b, resultETy, y1x1);
2565
2566 const int64_t deltaBitwidth = dx.getType().getIntOrFloatBitWidth();
2567 if (resultETy.getIntOrFloatBitWidth() > deltaBitwidth) {
2568 dx = arith::ExtSIOp::create(b, resultETy, dx);
2569 dy = arith::ExtSIOp::create(b, resultETy, dy);
2570 }
2571
2572 Value yScaleNExt = yScaleN;
2573 Value xScaleNExt = xScaleN;
2574
2575 const int64_t scaleBitwidth =
2576 xScaleN.getType().getIntOrFloatBitWidth();
2577 if (resultETy.getIntOrFloatBitWidth() > scaleBitwidth) {
2578 yScaleNExt = arith::ExtSIOp::create(b, resultETy, yScaleN);
2579 xScaleNExt = arith::ExtSIOp::create(b, resultETy, xScaleN);
2580 }
2581
2582 auto interpolate = [](Value val0, Value val1, Value weight1,
2583 Value scale, int inputSize,
2584 ImplicitLocOpBuilder &b) -> Value {
2585 if (inputSize == 1)
2586 return arith::MulIOp::create(b, val0, scale);
2587 Value weight0 = arith::SubIOp::create(b, scale, weight1);
2588 Value mul0 = arith::MulIOp::create(b, val0, weight0);
2589 Value mul1 = arith::MulIOp::create(b, val1, weight1);
2590 return arith::AddIOp::create(b, mul0, mul1);
2591 };
2592
2593 Value topAcc = interpolate(y0x0, y0x1, dx, xScaleNExt, imageW, b);
2594 Value bottomAcc = interpolate(y1x0, y1x1, dx, xScaleNExt, imageW, b);
2595 Value result =
2596 interpolate(topAcc, bottomAcc, dy, yScaleNExt, imageH, b);
2597 linalg::YieldOp::create(b, result);
2598 }
2599 }
2600 }
2601
2602 rewriter.replaceOp(op, resize);
2603 return success();
2604 }
2605};
2606
2607// At the codegen level any identity operations should be removed. Any cases
2608// where identity is load-bearing (e.g. cross device computation) should be
2609// handled before lowering to codegen.
2610template <typename SrcOp>
2611class IdentityNConverter : public OpRewritePattern<SrcOp> {
2612public:
2613 using OpRewritePattern<SrcOp>::OpRewritePattern;
2614
2615 LogicalResult matchAndRewrite(SrcOp op,
2616 PatternRewriter &rewriter) const final {
2617 rewriter.replaceOp(op, op.getOperation()->getOperands());
2618 return success();
2619 }
2620};
2621
2622template <typename SrcOp>
2623class ReduceConverter : public OpRewritePattern<SrcOp> {
2624public:
2625 ReduceConverter(MLIRContext *context, bool allowNonFinites)
2626 : OpRewritePattern<SrcOp>(context), allowNonFinites(allowNonFinites) {}
2627
2628 LogicalResult matchAndRewrite(SrcOp reduceOp,
2629 PatternRewriter &rewriter) const final {
2630 return reduceMatchAndRewriteHelper(reduceOp, reduceOp.getAxis(), rewriter,
2631 allowNonFinites);
2632 }
2633
2634private:
2635 bool allowNonFinites;
2636};
2637
2638class ReverseConverter : public OpRewritePattern<tosa::ReverseOp> {
2639public:
2640 using OpRewritePattern<tosa::ReverseOp>::OpRewritePattern;
2641
2642 LogicalResult matchAndRewrite(tosa::ReverseOp op,
2643 PatternRewriter &rewriter) const final {
2644 auto loc = op.getLoc();
2645 Value input = op.getInput1();
2646 auto inputTy = cast<ShapedType>(input.getType());
2647 auto resultTy = cast<ShapedType>(op.getType());
2648 auto axis = op.getAxis();
2649
2650 SmallVector<Value> dynDims;
2651 for (int i = 0; i < inputTy.getRank(); i++) {
2652 if (inputTy.isDynamicDim(i)) {
2653 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2654 }
2655 }
2656
2657 Value axisDimSize = tensor::DimOp::create(rewriter, loc, input, axis);
2658
2659 // First fill the output buffer with the init value.
2660 auto emptyTensor = tensor::EmptyOp::create(
2661 rewriter, loc, inputTy.getShape(),
2662 inputTy.getElementType(), ArrayRef<Value>({dynDims}))
2663 .getResult();
2664 SmallVector<AffineMap, 2> affineMaps = {
2665 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2666
2667 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
2668 op, resultTy, ArrayRef<Value>({}), ValueRange{emptyTensor}, affineMaps,
2669 getNParallelLoopsAttrs(resultTy.getRank()),
2670 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
2671 llvm::SmallVector<Value> indices;
2672 for (unsigned int i = 0; i < inputTy.getRank(); i++) {
2673 Value index =
2674 linalg::IndexOp::create(rewriter, nestedLoc, i).getResult();
2675 if (i == axis) {
2676 auto one = arith::ConstantIndexOp::create(rewriter, nestedLoc, 1);
2677 auto sizeMinusOne =
2678 arith::SubIOp::create(rewriter, nestedLoc, axisDimSize, one);
2679 index = arith::SubIOp::create(rewriter, nestedLoc, sizeMinusOne,
2680 index);
2681 }
2682
2683 indices.push_back(index);
2684 }
2685
2686 auto extract = tensor::ExtractOp::create(nestedBuilder, nestedLoc,
2687 input, indices);
2688 linalg::YieldOp::create(nestedBuilder, op.getLoc(),
2689 extract.getResult());
2690 });
2691 return success();
2692 }
2693};
2694
2695// This converter translate a tile operation to a reshape, broadcast, reshape.
2696// The first reshape minimally expands each tiled dimension to include a
2697// proceding size-1 dim. This dim is then broadcasted to the appropriate
2698// multiple.
2699struct TileConverter : public OpConversionPattern<tosa::TileOp> {
2700 using OpConversionPattern<tosa::TileOp>::OpConversionPattern;
2701
2702 LogicalResult
2703 matchAndRewrite(tosa::TileOp op, OpAdaptor adaptor,
2704 ConversionPatternRewriter &rewriter) const override {
2705 SmallVector<int64_t> multiples;
2706 if (failed(op.getConstantMultiples(multiples)))
2707 return failure();
2708
2709 // Avoid constructing invalid tensor types when validation is skipped.
2710 // Preserve the existing handling of -1 below.
2711 if (llvm::any_of(multiples, [](int64_t v) { return v <= 0 && v != -1; }))
2712 return rewriter.notifyMatchFailure(op,
2713 "unsupported non-positive multiples");
2714
2715 auto loc = op.getLoc();
2716 auto input = op.getInput1();
2717 auto inputTy = cast<ShapedType>(input.getType());
2718 auto inputShape = inputTy.getShape();
2719 auto resultTy = cast<ShapedType>(op.getType());
2720 auto elementTy = inputTy.getElementType();
2721 int64_t rank = inputTy.getRank();
2722
2723 // Broadcast the newly added dimensions to their appropriate multiple.
2724 SmallVector<int64_t, 2> genericShape;
2725 for (int i = 0; i < rank; i++) {
2726 int64_t dim = multiples[i];
2727 genericShape.push_back(dim == -1 ? ShapedType::kDynamic : dim);
2728 genericShape.push_back(inputShape[i]);
2729 }
2730
2731 SmallVector<Value> dynDims;
2732 for (int i = 0; i < inputTy.getRank(); i++) {
2733 if (inputTy.isDynamicDim(i) || multiples[i] == -1) {
2734 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2735 }
2736 }
2737
2738 auto emptyTensor = tensor::EmptyOp::create(
2739 rewriter, op.getLoc(), genericShape, elementTy, dynDims);
2740
2741 // We needs to map the input shape to the non-broadcasted dimensions.
2742 SmallVector<AffineExpr, 4> dimExprs;
2743 dimExprs.reserve(rank);
2744 for (unsigned i = 0; i < rank; ++i)
2745 dimExprs.push_back(rewriter.getAffineDimExpr(i * 2 + 1));
2746
2747 auto readAffineMap =
2748 AffineMap::get(/*dimCount=*/rank * 2, /*symbolCount=*/0, dimExprs,
2749 rewriter.getContext());
2750
2751 SmallVector<AffineMap, 2> affineMaps = {
2752 readAffineMap, rewriter.getMultiDimIdentityMap(genericShape.size())};
2753
2754 auto genericOp = linalg::GenericOp::create(
2755 rewriter, loc, RankedTensorType::get(genericShape, elementTy), input,
2756 ValueRange{emptyTensor}, affineMaps,
2757 getNParallelLoopsAttrs(genericShape.size()),
2758 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
2759 linalg::YieldOp::create(nestedBuilder, op.getLoc(), *args.begin());
2760 });
2761
2762 auto shapeValue = getTosaConstShape(
2763 rewriter, loc, mlir::tosa::convertFromMlirShape(resultTy.getShape()));
2764 rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
2765 op, resultTy, genericOp.getResult(0), shapeValue);
2766 return success();
2767 }
2768};
2769
2770// Tosa argmin/argmax lowering represents the op as a linalg.generic
2771// op, producing two output buffers.
2772//
2773// The first output buffer contains the index of the found min/max value. It is
2774// initialized to 0 and is resulting integer type.
2775//
2776// The second output buffer contains the min/max value found. It is initialized
2777// to the max/min representable value of the input element type. After being
2778// populated by generic, this buffer is discarded as only the index is
2779// requested.
2780//
2781// The generic op updates both the min/max value and index if the
2782// current value is lower than/exceeds the running min/max.
2783template <typename SrcOp>
2784class ArgMinMaxConverter : public OpRewritePattern<SrcOp> {
2785public:
2786 ArgMinMaxConverter(MLIRContext *context, bool allowNonFinites)
2787 : OpRewritePattern<SrcOp>(context), allowNonFinites(allowNonFinites) {}
2788
2789 LogicalResult matchAndRewrite(SrcOp argOp,
2790 PatternRewriter &rewriter) const final {
2791 constexpr bool isMin = std::is_same_v<SrcOp, tosa::ArgMinOp>;
2792
2793 auto loc = argOp.getLoc();
2794 Value input = argOp.getInput();
2795 auto inputTy = cast<ShapedType>(input.getType());
2796 auto resultTy = cast<ShapedType>(argOp.getOutput().getType());
2797 auto inElementTy = inputTy.getElementType();
2798 auto outElementTy = resultTy.getElementType();
2799 int axis = argOp.getAxis();
2800 auto resultValueTy =
2801 RankedTensorType::get(resultTy.getShape(), inElementTy);
2802
2803 if (!isa<IntegerType>(outElementTy))
2804 return rewriter.notifyMatchFailure(argOp,
2805 "requires integer-like result type");
2806
2807 SmallVector<Value> dynDims;
2808 for (int i = 0; i < inputTy.getRank(); i++) {
2809 if (inputTy.isDynamicDim(i) && i != axis) {
2810 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2811 }
2812 }
2813
2814 // First fill the output buffer for the index.
2815 auto emptyTensorIdx =
2816 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2817 outElementTy, dynDims)
2818 .getResult();
2819 auto fillValueIdx = arith::ConstantOp::create(
2820 rewriter, loc, rewriter.getIntegerAttr(outElementTy, 0));
2821 auto filledTensorIdx =
2822 linalg::FillOp::create(rewriter, loc, ValueRange{fillValueIdx},
2823 ValueRange{emptyTensorIdx})
2824 .result();
2825
2826 // Second fill the output buffer for the running min/max.
2827 auto emptyTensorValue =
2828 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(), inElementTy,
2829 dynDims)
2830 .getResult();
2831 auto fillValueAttr = createInitialValueForReduceOp(
2832 argOp, inElementTy, rewriter, allowNonFinites);
2833
2834 if (!fillValueAttr)
2835 return rewriter.notifyMatchFailure(argOp, "unsupported element type");
2836
2837 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
2838 auto filledTensorValue =
2839 linalg::FillOp::create(rewriter, loc, ValueRange{fillValue},
2840 ValueRange{emptyTensorValue})
2841 .result();
2842
2843 // We need to reduce along the specified axis, with parallel operations
2844 // along the rest.
2845 SmallVector<utils::IteratorType, 4> iteratorTypes;
2846 iteratorTypes.resize(inputTy.getRank(), utils::IteratorType::parallel);
2847 iteratorTypes[axis] = utils::IteratorType::reduction;
2848
2849 SmallVector<AffineExpr, 2> srcExprs;
2850 SmallVector<AffineExpr, 2> dstExprs;
2851 for (int i = 0, rank = inputTy.getRank(); i != rank; ++i) {
2852 srcExprs.push_back(mlir::getAffineDimExpr(i, rewriter.getContext()));
2853 if (axis != i)
2854 dstExprs.push_back(mlir::getAffineDimExpr(i, rewriter.getContext()));
2855 }
2856
2857 bool didEncounterError = false;
2858 auto maps = AffineMap::inferFromExprList({srcExprs, dstExprs, dstExprs},
2859 rewriter.getContext());
2860 auto linalgOp = linalg::GenericOp::create(
2861 rewriter, loc, ArrayRef<Type>({resultTy, resultValueTy}), input,
2862 ValueRange({filledTensorIdx, filledTensorValue}), maps, iteratorTypes,
2863 [&](OpBuilder &nestedBuilder, Location nestedLoc,
2864 ValueRange blockArgs) {
2865 auto newValue = blockArgs[0];
2866 auto oldIndex = blockArgs[1];
2867 auto oldValue = blockArgs[2];
2868
2869 Value newIndex = arith::IndexCastOp::create(
2870 rewriter, nestedLoc, oldIndex.getType(),
2871 linalg::IndexOp::create(rewriter, loc, axis));
2872
2873 Value predicate;
2874 if (isa<FloatType>(inElementTy)) {
2875 if (argOp.getNanMode() == NanPropagationMode::IGNORE) {
2876 // Only update index & value for non NaN values. If all
2877 // values are NaNs, the initial index will be return which is 0.
2878 Value comparison = arith::CmpFOp::create(
2879 rewriter, nestedLoc,
2880 isMin ? arith::CmpFPredicate::ULT : arith::CmpFPredicate::UGT,
2881 newValue, oldValue);
2882 Value newNonNaN = arith::CmpFOp::create(rewriter, nestedLoc,
2883 arith::CmpFPredicate::ORD,
2884 newValue, newValue);
2885 predicate = arith::AndIOp::create(rewriter, nestedLoc,
2886 rewriter.getI1Type(),
2887 comparison, newNonNaN);
2888 } else {
2889 // Update value if either of the following is true:
2890 // - new value is smaller/bigger
2891 // - cur value is not NaN and new value is NaN
2892 Value comparison = arith::CmpFOp::create(
2893 rewriter, nestedLoc,
2894 isMin ? arith::CmpFPredicate::ULT : arith::CmpFPredicate::UGT,
2895 newValue, oldValue);
2896 Value oldNonNaN = arith::CmpFOp::create(rewriter, nestedLoc,
2897 arith::CmpFPredicate::ORD,
2898 oldValue, oldValue);
2899 predicate = arith::AndIOp::create(rewriter, nestedLoc,
2900 rewriter.getI1Type(),
2901 comparison, oldNonNaN);
2902 }
2903 } else if (isa<IntegerType>(inElementTy)) {
2904 predicate = arith::CmpIOp::create(rewriter, nestedLoc,
2905 isMin ? arith::CmpIPredicate::slt
2906 : arith::CmpIPredicate::sgt,
2907 newValue, oldValue);
2908 } else {
2909 didEncounterError = true;
2910 return;
2911 }
2912
2913 auto resultValue = arith::SelectOp::create(
2914 rewriter, nestedLoc, predicate, newValue, oldValue);
2915 auto resultIndex = arith::SelectOp::create(
2916 rewriter, nestedLoc, predicate, newIndex, oldIndex);
2917 linalg::YieldOp::create(nestedBuilder, nestedLoc,
2918 ValueRange({resultIndex, resultValue}));
2919 });
2920
2921 if (didEncounterError)
2922 return rewriter.notifyMatchFailure(argOp, "unsupported element type");
2923
2924 rewriter.replaceOp(argOp, linalgOp.getResult(0));
2925 return success();
2926 }
2927
2928private:
2929 bool allowNonFinites;
2930};
2931
2932class GatherConverter : public OpConversionPattern<tosa::GatherOp> {
2933public:
2934 using OpConversionPattern<tosa::GatherOp>::OpConversionPattern;
2935 LogicalResult
2936 matchAndRewrite(tosa::GatherOp op, OpAdaptor adaptor,
2937 ConversionPatternRewriter &rewriter) const final {
2938 auto input = adaptor.getOperands()[0];
2939 auto indices = adaptor.getOperands()[1];
2940
2941 auto valuesTy = dyn_cast<RankedTensorType>(op.getValues().getType());
2942 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2943 if (!valuesTy || !resultTy)
2944 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
2945
2946 auto dynamicDims = inferDynamicDimsForGather(
2947 rewriter, op.getLoc(), adaptor.getValues(), adaptor.getIndices());
2948
2949 auto resultElementTy = resultTy.getElementType();
2950
2951 auto loc = op.getLoc();
2952 auto emptyTensor =
2953 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2954 resultElementTy, dynamicDims)
2955 .getResult();
2956
2957 SmallVector<AffineMap, 2> affineMaps = {
2959 /*dimCount=*/resultTy.getRank(), /*symbolCount=*/0,
2960 {rewriter.getAffineDimExpr(0), rewriter.getAffineDimExpr(1)},
2961 rewriter.getContext()),
2962 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2963
2964 auto genericOp = linalg::GenericOp::create(
2965 rewriter, loc, ArrayRef<Type>({resultTy}), ValueRange{indices},
2966 ValueRange{emptyTensor}, affineMaps,
2967 getNParallelLoopsAttrs(resultTy.getRank()),
2968 [&](OpBuilder &b, Location loc, ValueRange args) {
2969 auto indexValue = args[0];
2970 auto index0 = linalg::IndexOp::create(rewriter, loc, 0);
2971 Value index1 = arith::IndexCastOp::create(
2972 rewriter, loc, rewriter.getIndexType(), indexValue);
2973 auto index2 = linalg::IndexOp::create(rewriter, loc, 2);
2974 Value extract = tensor::ExtractOp::create(
2975 rewriter, loc, input, ValueRange{index0, index1, index2});
2976 linalg::YieldOp::create(rewriter, loc, extract);
2977 });
2978 rewriter.replaceOp(op, genericOp.getResult(0));
2979 return success();
2980 }
2981
2982 static llvm::SmallVector<Value> inferDynamicDimsForGather(OpBuilder &builder,
2983 Location loc,
2984 Value values,
2985 Value indices) {
2986 llvm::SmallVector<Value> results;
2987
2988 auto addDynamicDimension = [&](Value source, int64_t dim) {
2989 auto sz = tensor::getMixedSize(builder, loc, source, dim);
2990 if (auto dimValue = llvm::dyn_cast_if_present<Value>(sz))
2991 results.push_back(dimValue);
2992 };
2993
2994 addDynamicDimension(values, 0);
2995 addDynamicDimension(indices, 1);
2996 addDynamicDimension(values, 2);
2997 return results;
2998 }
2999};
3000
3001class RowGatherConverter : public OpConversionPattern<tosa::RowGatherOp> {
3002public:
3003 using OpConversionPattern<tosa::RowGatherOp>::OpConversionPattern;
3004 LogicalResult
3005 matchAndRewrite(tosa::RowGatherOp op, OpAdaptor adaptor,
3006 ConversionPatternRewriter &rewriter) const final {
3007 auto valuesTy = dyn_cast<RankedTensorType>(adaptor.getValues().getType());
3008 auto indicesTy = dyn_cast<RankedTensorType>(adaptor.getIndices().getType());
3009 auto rowCountTy =
3010 dyn_cast<RankedTensorType>(adaptor.getRowCount().getType());
3011 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
3012 if (!valuesTy || !indicesTy || !rowCountTy || !resultTy)
3013 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
3014
3015 Location loc = op.getLoc();
3016 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
3017 Value rowCount = tensor::ExtractOp::create(
3018 rewriter, loc, adaptor.getRowCount(), ValueRange{zero});
3019 Value rowCountIndex = arith::IndexCastOp::create(
3020 rewriter, loc, rewriter.getIndexType(), rowCount);
3021
3022 SmallVector<Value> dynamicDims;
3023 if (resultTy.isDynamicDim(0))
3024 dynamicDims.push_back(
3025 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 0));
3026 if (resultTy.isDynamicDim(1)) {
3027 Value indicesWidth =
3028 tensor::DimOp::create(rewriter, loc, adaptor.getIndices(), 1);
3029 dynamicDims.push_back(
3030 arith::MulIOp::create(rewriter, loc, indicesWidth, rowCountIndex));
3031 }
3032 if (resultTy.isDynamicDim(2))
3033 dynamicDims.push_back(
3034 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 2));
3035
3036 Value emptyTensor =
3037 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
3038 resultTy.getElementType(), dynamicDims);
3039 SmallVector<AffineMap> affineMaps = {
3040 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
3041
3042 auto genericOp = linalg::GenericOp::create(
3043 rewriter, loc, ArrayRef<Type>{resultTy}, ValueRange{},
3044 ValueRange{emptyTensor}, affineMaps,
3045 getNParallelLoopsAttrs(resultTy.getRank()),
3046 [&](OpBuilder &builder, Location nestedLoc, ValueRange) {
3047 Value batch = linalg::IndexOp::create(builder, nestedLoc, 0);
3048 Value outputRow = linalg::IndexOp::create(builder, nestedLoc, 1);
3049 Value channel = linalg::IndexOp::create(builder, nestedLoc, 2);
3050 Value indexSlot = arith::DivUIOp::create(builder, nestedLoc,
3051 outputRow, rowCountIndex);
3052 Value rowOffset = arith::RemUIOp::create(builder, nestedLoc,
3053 outputRow, rowCountIndex);
3054 Value index = tensor::ExtractOp::create(builder, nestedLoc,
3055 adaptor.getIndices(),
3056 ValueRange{batch, indexSlot});
3057 Value row = arith::IndexCastOp::create(builder, nestedLoc,
3058 builder.getIndexType(), index);
3059 row = arith::AddIOp::create(builder, nestedLoc, row, rowOffset);
3060 Value result =
3061 tensor::ExtractOp::create(builder, nestedLoc, adaptor.getValues(),
3062 ValueRange{batch, row, channel});
3063 linalg::YieldOp::create(builder, nestedLoc, result);
3064 });
3065 rewriter.replaceOp(op, genericOp.getResult(0));
3066 return success();
3067 }
3068};
3069
3070// Lowerings the TableOp to a series of gathers and numerica operations. This
3071// includes interpolation between the high/low values. For the I8 varient, this
3072// simplifies to a single gather operation.
3073class TableConverter : public OpRewritePattern<tosa::TableOp> {
3074public:
3075 using OpRewritePattern<tosa::TableOp>::OpRewritePattern;
3076
3077 LogicalResult matchAndRewrite(tosa::TableOp op,
3078 PatternRewriter &rewriter) const final {
3079 auto loc = op.getLoc();
3080 Value input = op.getInput1();
3081 Value table = op.getTable();
3082 auto inputTy = cast<ShapedType>(input.getType());
3083 auto tableTy = cast<ShapedType>(table.getType());
3084 auto resultTy = cast<ShapedType>(op.getType());
3085
3086 auto inputElementTy = inputTy.getElementType();
3087 auto tableElementTy = tableTy.getElementType();
3088 auto resultElementTy = resultTy.getElementType();
3089
3090 SmallVector<Value> dynDims;
3091 for (int i = 0; i < resultTy.getRank(); ++i) {
3092 if (inputTy.isDynamicDim(i)) {
3093 dynDims.push_back(
3094 tensor::DimOp::create(rewriter, loc, op.getOperand(0), i));
3095 }
3096 }
3097
3098 auto emptyTensor =
3099 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
3100 resultElementTy, dynDims)
3101 .getResult();
3102
3103 SmallVector<AffineMap, 2> affineMaps = {
3104 rewriter.getMultiDimIdentityMap(resultTy.getRank()),
3105 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
3106
3107 auto genericOp = linalg::GenericOp::create(
3108 rewriter, loc, resultTy, ValueRange({input}), ValueRange{emptyTensor},
3109 affineMaps, getNParallelLoopsAttrs(resultTy.getRank()));
3110 rewriter.replaceOp(op, genericOp.getResult(0));
3111
3112 {
3113 OpBuilder::InsertionGuard regionGuard(rewriter);
3114 Block *block = rewriter.createBlock(
3115 &genericOp.getRegion(), genericOp.getRegion().end(),
3116 TypeRange({inputElementTy, resultElementTy}), {loc, loc});
3117
3118 auto inputValue = block->getArgument(0);
3119 rewriter.setInsertionPointToStart(block);
3120 if (inputElementTy.isInteger(8) && tableElementTy.isInteger(8) &&
3121 resultElementTy.isInteger(8)) {
3122 Value index = arith::IndexCastOp::create(
3123 rewriter, loc, rewriter.getIndexType(), inputValue);
3124 Value offset = arith::ConstantIndexOp::create(rewriter, loc, 128);
3125 index = arith::AddIOp::create(rewriter, loc, rewriter.getIndexType(),
3126 index, offset);
3127 Value extract =
3128 tensor::ExtractOp::create(rewriter, loc, table, ValueRange{index});
3129 linalg::YieldOp::create(rewriter, loc, extract);
3130 return success();
3131 }
3132
3133 if (inputElementTy.isInteger(16) && tableElementTy.isInteger(16) &&
3134 resultElementTy.isInteger(32)) {
3135 Value extend = arith::ExtSIOp::create(
3136 rewriter, loc, rewriter.getI32Type(), inputValue);
3137
3138 auto offset = arith::ConstantOp::create(
3139 rewriter, loc, rewriter.getI32IntegerAttr(32768));
3140 auto seven = arith::ConstantOp::create(rewriter, loc,
3141 rewriter.getI32IntegerAttr(7));
3142 auto one = arith::ConstantOp::create(rewriter, loc,
3143 rewriter.getI32IntegerAttr(1));
3144 auto b1111111 = arith::ConstantOp::create(
3145 rewriter, loc, rewriter.getI32IntegerAttr(127));
3146
3147 // Compute the index and fractional part from the input value:
3148 // value = value + 32768
3149 // index = value >> 7;
3150 // fraction = 0x01111111 & value
3151 auto extendAdd = arith::AddIOp::create(rewriter, loc, extend, offset);
3152 Value index = arith::ShRUIOp::create(rewriter, loc, extendAdd, seven);
3153 Value fraction =
3154 arith::AndIOp::create(rewriter, loc, extendAdd, b1111111);
3155
3156 // Extract the base and next values from the table.
3157 // base = (int32_t) table[index];
3158 // next = (int32_t) table[index + 1];
3159 Value indexPlusOne = arith::AddIOp::create(rewriter, loc, index, one);
3160
3161 index = arith::IndexCastOp::create(rewriter, loc,
3162 rewriter.getIndexType(), index);
3163 indexPlusOne = arith::IndexCastOp::create(
3164 rewriter, loc, rewriter.getIndexType(), indexPlusOne);
3165
3166 Value base =
3167 tensor::ExtractOp::create(rewriter, loc, table, ValueRange{index});
3168 Value next = tensor::ExtractOp::create(rewriter, loc, table,
3169 ValueRange{indexPlusOne});
3170
3171 base =
3172 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), base);
3173 next =
3174 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), next);
3175
3176 // Use the fractional part to interpolate between the input values:
3177 // result = (base << 7) + (next - base) * fraction
3178 Value baseScaled = arith::ShLIOp::create(rewriter, loc, base, seven);
3179 Value diff = arith::SubIOp::create(rewriter, loc, next, base);
3180 Value diffScaled = arith::MulIOp::create(rewriter, loc, diff, fraction);
3181 Value result =
3182 arith::AddIOp::create(rewriter, loc, baseScaled, diffScaled);
3183
3184 linalg::YieldOp::create(rewriter, loc, result);
3185
3186 return success();
3187 }
3188 }
3189
3190 return rewriter.notifyMatchFailure(
3191 op, "unable to create body for tosa.table op");
3192 }
3193};
3194
3195struct RFFT2dConverter final : public OpRewritePattern<RFFT2dOp> {
3196 using OpRewritePattern<RFFT2dOp>::OpRewritePattern;
3197
3198 static bool isRankedTensor(Type type) { return isa<RankedTensorType>(type); }
3199
3200 static OpFoldResult halfPlusOne(OpBuilder &builder, Location loc,
3201 OpFoldResult ofr) {
3202 auto one = arith::ConstantIndexOp::create(builder, loc, 1);
3203 auto two = arith::ConstantIndexOp::create(builder, loc, 2);
3204
3205 auto value = getValueOrCreateConstantIndexOp(builder, loc, ofr);
3206 auto divBy2 = builder.createOrFold<arith::DivUIOp>(loc, value, two);
3207 auto plusOne = builder.createOrFold<arith::AddIOp>(loc, divBy2, one);
3208 return getAsOpFoldResult(plusOne);
3209 }
3210
3211 static RankedTensorType
3212 computeOutputShape(OpBuilder &builder, Location loc, Value input,
3213 llvm::SmallVectorImpl<Value> &dynamicSizes) {
3214 // Get [N, H, W]
3215 auto dims = tensor::getMixedSizes(builder, loc, input);
3216
3217 // Set W = (W / 2) + 1 to account for the half-sized W dimension of the
3218 // output tensors.
3219 dims[2] = halfPlusOne(builder, loc, dims[2]);
3220
3221 llvm::SmallVector<int64_t, 3> staticSizes;
3222 dispatchIndexOpFoldResults(dims, dynamicSizes, staticSizes);
3223
3224 auto elementType = cast<RankedTensorType>(input.getType()).getElementType();
3225 return RankedTensorType::get(staticSizes, elementType);
3226 }
3227
3228 static Value createZeroTensor(PatternRewriter &rewriter, Location loc,
3229 RankedTensorType type,
3230 llvm::ArrayRef<Value> dynamicSizes) {
3231 auto emptyTensor =
3232 tensor::EmptyOp::create(rewriter, loc, type, dynamicSizes);
3233 auto fillValueAttr = rewriter.getZeroAttr(type.getElementType());
3234 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
3235 auto filledTensor =
3236 linalg::FillOp::create(rewriter, loc, ValueRange{fillValue},
3237 ValueRange{emptyTensor})
3238 .result();
3239 return filledTensor;
3240 }
3241
3242 static Value castIndexToFloat(OpBuilder &builder, Location loc,
3243 FloatType type, Value value) {
3244 auto integerVal = arith::IndexCastUIOp::create(
3245 builder, loc,
3246 type.getIntOrFloatBitWidth() > 32 ? builder.getI64Type()
3247 : builder.getI32Type(),
3248 value);
3249
3250 return arith::UIToFPOp::create(builder, loc, type, integerVal);
3251 }
3252
3253 static Value createLinalgIndex(OpBuilder &builder, Location loc,
3254 FloatType type, int64_t index) {
3255 auto indexVal = linalg::IndexOp::create(builder, loc, index);
3256 return castIndexToFloat(builder, loc, type, indexVal);
3257 }
3258
3259 template <typename... Args>
3260 static llvm::SmallVector<AffineExpr, 4> affineDimsExpr(OpBuilder &builder,
3261 Args... args) {
3262 return {builder.getAffineDimExpr(args)...};
3263 }
3264
3265 LogicalResult matchAndRewrite(RFFT2dOp rfft2d,
3266 PatternRewriter &rewriter) const override {
3267 if (!llvm::all_of(rfft2d->getOperandTypes(), isRankedTensor) ||
3268 !llvm::all_of(rfft2d->getResultTypes(), isRankedTensor)) {
3269 return rewriter.notifyMatchFailure(rfft2d,
3270 "only supports ranked tensors");
3271 }
3272
3273 auto loc = rfft2d.getLoc();
3274 auto input = rfft2d.getInputReal();
3275 auto elementType =
3276 dyn_cast<FloatType>(cast<ShapedType>(input.getType()).getElementType());
3277 if (!elementType)
3278 return rewriter.notifyMatchFailure(rfft2d,
3279 "only supports float element types");
3280
3281 // Compute the output type and set of dynamic sizes
3282 llvm::SmallVector<Value> dynamicSizes;
3283 auto outputType = computeOutputShape(rewriter, loc, input, dynamicSizes);
3284
3285 // Iterator types for the linalg.generic implementation
3286 llvm::SmallVector<utils::IteratorType, 5> iteratorTypes = {
3287 utils::IteratorType::parallel, utils::IteratorType::parallel,
3288 utils::IteratorType::parallel, utils::IteratorType::reduction,
3289 utils::IteratorType::reduction};
3290
3291 // Inputs/outputs to the linalg.generic implementation
3292 llvm::SmallVector<Value> genericOpInputs = {input};
3293 llvm::SmallVector<Value> genericOpOutputs = {
3294 createZeroTensor(rewriter, loc, outputType, dynamicSizes),
3295 createZeroTensor(rewriter, loc, outputType, dynamicSizes)};
3296
3297 // Indexing maps for input and output tensors
3298 auto indexingMaps = AffineMap::inferFromExprList(
3299 llvm::ArrayRef{affineDimsExpr(rewriter, 0, 3, 4),
3300 affineDimsExpr(rewriter, 0, 1, 2),
3301 affineDimsExpr(rewriter, 0, 1, 2)},
3302 rewriter.getContext());
3303
3304 // Width and height dimensions of the original input.
3305 auto dimH = rewriter.createOrFold<tensor::DimOp>(loc, input, 1);
3306 auto dimW = rewriter.createOrFold<tensor::DimOp>(loc, input, 2);
3307
3308 // Constants and dimension sizes
3309 auto zeroFloat = arith::ConstantOp::create(
3310 rewriter, loc, rewriter.getZeroAttr(elementType));
3311 auto twoPiAttr = rewriter.getFloatAttr(elementType, 6.283185307179586);
3312 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3313
3314 auto zeroIndex = arith::ConstantIndexOp::create(rewriter, loc, 0);
3315 auto twoIndex = arith::ConstantIndexOp::create(rewriter, loc, 2);
3316
3317 auto constH = castIndexToFloat(rewriter, loc, elementType, dimH);
3318 auto constW = castIndexToFloat(rewriter, loc, elementType, dimW);
3319 auto halfH = index::DivUOp::create(rewriter, loc, dimH, twoIndex);
3320 auto halfW = index::DivUOp::create(rewriter, loc, dimW, twoIndex);
3321
3322 auto buildBody = [&](OpBuilder &builder, Location loc, ValueRange args) {
3323 Value valReal = args[0];
3324 Value sumReal = args[1];
3325 Value sumImag = args[2];
3326
3327 // Indices for angle computation
3328 Value oy = linalg::IndexOp::create(builder, loc, 1);
3329 Value ox = linalg::IndexOp::create(builder, loc, 2);
3330 Value iy = linalg::IndexOp::create(builder, loc, 3);
3331 Value ix = linalg::IndexOp::create(builder, loc, 4);
3332
3333 // Calculating angle without integer parts of components as sin/cos are
3334 // periodic: angle = 2 * pi() * ( ( (iy * oy) % H) / H + ( (ix * ox) % W )
3335 // / W);
3336 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3337 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3338
3339 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3340 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3341
3342 auto iyRemFloat = castIndexToFloat(builder, loc, elementType, iyRem);
3343 auto ixRemFloat = castIndexToFloat(builder, loc, elementType, ixRem);
3344
3345 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3346 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3347 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3348 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3349
3350 // We will check the indices to see if this is a position that should use
3351 // a 0.0 weight for the imaginary value computation following the TOSA
3352 // specification with `tosa_extra_multiplies=true`.
3353 //
3354 // These are the relevant locations: (0,0), (0,W/2), (H/2,0), (H/2, W/2).
3355 auto iyIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3356 iyRem, zeroIndex);
3357 auto iyIsHalfH = arith::CmpIOp::create(
3358 builder, loc, arith::CmpIPredicate::eq, iyRem, halfH);
3359 auto ixIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3360 ixRem, zeroIndex);
3361 auto ixIsHalfW = arith::CmpIOp::create(
3362 builder, loc, arith::CmpIPredicate::eq, ixRem, halfW);
3363
3364 auto iyIsSinSkippable =
3365 arith::OrIOp::create(builder, loc, iyIs0, iyIsHalfH);
3366 auto ixIsSinSkippable =
3367 arith::OrIOp::create(builder, loc, ixIs0, ixIsHalfW);
3368 auto shouldSkipSin = arith::AndIOp::create(builder, loc, iyIsSinSkippable,
3369 ixIsSinSkippable);
3370
3371 // realComponent = valReal * cos(angle)
3372 // imagComponent = valReal * (shouldSkipSin ? 0.0 : sin(angle))
3373 auto cosAngle = math::CosOp::create(builder, loc, angle);
3374 auto sinAngle = math::SinOp::create(builder, loc, angle);
3375 auto imagWeight = arith::SelectOp::create(builder, loc, shouldSkipSin,
3376 zeroFloat, sinAngle);
3377 auto realComponent =
3378 arith::MulFOp::create(builder, loc, valReal, cosAngle);
3379 auto imagComponent =
3380 arith::MulFOp::create(builder, loc, valReal, imagWeight);
3381
3382 // outReal = sumReal + realComponent
3383 // outImag = sumImag - imagComponent
3384 auto outReal =
3385 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3386 auto outImag =
3387 arith::SubFOp::create(builder, loc, sumImag, imagComponent);
3388
3389 linalg::YieldOp::create(builder, loc, ValueRange{outReal, outImag});
3390 };
3391
3392 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
3393 rfft2d, rfft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3394 indexingMaps, iteratorTypes, buildBody);
3395
3396 return success();
3397 }
3398};
3399
3400struct FFT2dConverter final : OpRewritePattern<FFT2dOp> {
3401 using Base::Base;
3402
3403 LogicalResult matchAndRewrite(FFT2dOp fft2d,
3404 PatternRewriter &rewriter) const override {
3405 if (!llvm::all_of(fft2d->getOperandTypes(),
3406 RFFT2dConverter::isRankedTensor) ||
3407 !llvm::all_of(fft2d->getResultTypes(),
3408 RFFT2dConverter::isRankedTensor)) {
3409 return rewriter.notifyMatchFailure(fft2d, "only supports ranked tensors");
3410 }
3411
3412 Location loc = fft2d.getLoc();
3413 Value input_real = fft2d.getInputReal();
3414 Value input_imag = fft2d.getInputImag();
3415 BoolAttr inverse = fft2d.getInverseAttr();
3416
3417 auto real_el_ty = cast<FloatType>(
3418 cast<ShapedType>(input_real.getType()).getElementType());
3419 [[maybe_unused]] auto imag_el_ty = cast<FloatType>(
3420 cast<ShapedType>(input_imag.getType()).getElementType());
3421
3422 assert(real_el_ty == imag_el_ty);
3423
3424 // Compute the output type and set of dynamic sizes
3425 SmallVector<Value> dynamicSizes;
3426
3427 // Get [N, H, W]
3428 auto dims = tensor::getMixedSizes(rewriter, loc, input_real);
3429
3430 SmallVector<int64_t, 3> staticSizes;
3431 dispatchIndexOpFoldResults(dims, dynamicSizes, staticSizes);
3432
3433 auto outputType = RankedTensorType::get(staticSizes, real_el_ty);
3434
3435 // Iterator types for the linalg.generic implementation
3436 SmallVector<utils::IteratorType, 5> iteratorTypes = {
3437 utils::IteratorType::parallel, utils::IteratorType::parallel,
3438 utils::IteratorType::parallel, utils::IteratorType::reduction,
3439 utils::IteratorType::reduction};
3440
3441 // Inputs/outputs to the linalg.generic implementation
3442 SmallVector<Value> genericOpInputs = {input_real, input_imag};
3443 SmallVector<Value> genericOpOutputs = {
3444 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3445 dynamicSizes),
3446 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3447 dynamicSizes)};
3448
3449 // Indexing maps for input and output tensors
3450 auto indexingMaps = AffineMap::inferFromExprList(
3451 ArrayRef{RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3452 RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3453 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2),
3454 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2)},
3455 rewriter.getContext());
3456
3457 // Width and height dimensions of the original input.
3458 auto dimH = rewriter.createOrFold<tensor::DimOp>(loc, input_real, 1);
3459 auto dimW = rewriter.createOrFold<tensor::DimOp>(loc, input_real, 2);
3460
3461 // Constants and dimension sizes
3462 auto twoPiAttr = rewriter.getFloatAttr(real_el_ty, 6.283185307179586);
3463 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3464 Value constH =
3465 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimH);
3466 Value constW =
3467 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimW);
3468
3469 auto buildBody = [&](OpBuilder &builder, Location loc, ValueRange args) {
3470 Value valReal = args[0];
3471 Value valImag = args[1];
3472 Value sumReal = args[2];
3473 Value sumImag = args[3];
3474
3475 // Indices for angle computation
3476 Value oy = linalg::IndexOp::create(builder, loc, 1);
3477 Value ox = linalg::IndexOp::create(builder, loc, 2);
3478 Value iy = linalg::IndexOp::create(builder, loc, 3);
3479 Value ix = linalg::IndexOp::create(builder, loc, 4);
3480
3481 // float_t angle = sign_val * 2 * pi() * ( ( (iy * oy) % H) / H + ( (ix *
3482 // ox) % W ) / W);
3483 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3484 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3485
3486 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3487 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3488
3489 auto iyRemFloat =
3490 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, iyRem);
3491 auto ixRemFloat =
3492 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, ixRem);
3493
3494 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3495 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3496
3497 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3498 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3499
3500 if (inverse.getValue()) {
3501 angle = arith::MulFOp::create(
3502 builder, loc, angle,
3503 arith::ConstantOp::create(rewriter, loc,
3504 rewriter.getFloatAttr(real_el_ty, -1.0)));
3505 }
3506
3507 // realComponent = val_real * cos(a) + val_imag * sin(a);
3508 // imagComponent = -val_real * sin(a) + val_imag * cos(a);
3509 auto cosAngle = math::CosOp::create(builder, loc, angle);
3510 auto sinAngle = math::SinOp::create(builder, loc, angle);
3511
3512 auto rcos = arith::MulFOp::create(builder, loc, valReal, cosAngle);
3513 auto rsin = arith::MulFOp::create(builder, loc, valImag, sinAngle);
3514 auto realComponent = arith::AddFOp::create(builder, loc, rcos, rsin);
3515
3516 auto icos = arith::MulFOp::create(builder, loc, valImag, cosAngle);
3517 auto isin = arith::MulFOp::create(builder, loc, valReal, sinAngle);
3518
3519 auto imagComponent = arith::SubFOp::create(builder, loc, icos, isin);
3520
3521 // outReal = sumReal + realComponent
3522 // outImag = sumImag - imagComponent
3523 auto outReal =
3524 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3525 auto outImag =
3526 arith::AddFOp::create(builder, loc, sumImag, imagComponent);
3527
3528 linalg::YieldOp::create(builder, loc, ValueRange{outReal, outImag});
3529 };
3530
3531 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
3532 fft2d, fft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3533 indexingMaps, iteratorTypes, buildBody);
3534
3535 return success();
3536 }
3537};
3538
3539} // namespace
3540
3542 const TypeConverter &converter, RewritePatternSet *patterns,
3544
3545 // We have multiple resize coverters to handle degenerate cases.
3546 patterns->add<GenericResizeConverter>(patterns->getContext(),
3547 /*benefit=*/100);
3548 patterns->add<ResizeUnaryConverter>(patterns->getContext(),
3549 /*benefit=*/200);
3550 patterns->add<MaterializeResizeBroadcast>(patterns->getContext(),
3551 /*benefit=*/300);
3552
3553 patterns->add<
3554 // clang-format off
3555 PointwiseConverter<tosa::AddOp>,
3556 PointwiseConverter<tosa::SubOp>,
3557 PointwiseConverter<tosa::MulOp>,
3558 PointwiseConverter<tosa::IntDivOp>,
3559 PointwiseConverter<tosa::NegateOp>,
3560 PointwiseConverter<tosa::PowOp>,
3561 PointwiseConverter<tosa::ReciprocalOp>,
3562 PointwiseConverter<tosa::RsqrtOp>,
3563 PointwiseConverter<tosa::LogOp>,
3564 PointwiseConverter<tosa::ExpOp>,
3565 PointwiseConverter<tosa::AbsOp>,
3566 PointwiseConverter<tosa::SinOp>,
3567 PointwiseConverter<tosa::CosOp>,
3568 PointwiseConverter<tosa::TanhOp>,
3569 PointwiseConverter<tosa::ErfOp>,
3570 PointwiseConverter<tosa::BitwiseAndOp>,
3571 PointwiseConverter<tosa::BitwiseOrOp>,
3572 PointwiseConverter<tosa::BitwiseNotOp>,
3573 PointwiseConverter<tosa::BitwiseXorOp>,
3574 PointwiseConverter<tosa::LogicalAndOp>,
3575 PointwiseConverter<tosa::LogicalNotOp>,
3576 PointwiseConverter<tosa::LogicalOrOp>,
3577 PointwiseConverter<tosa::LogicalXorOp>,
3578 PointwiseConverter<tosa::CastOp>,
3579 PointwiseConverter<tosa::LogicalLeftShiftOp>,
3580 PointwiseConverter<tosa::LogicalRightShiftOp>,
3581 PointwiseConverter<tosa::ArithmeticRightShiftOp>,
3582 PointwiseConverter<tosa::ClzOp>,
3583 PointwiseConverter<tosa::SelectOp>,
3584 PointwiseConverter<tosa::GreaterOp>,
3585 PointwiseConverter<tosa::GreaterEqualOp>,
3586 PointwiseConverter<tosa::EqualOp>,
3587 PointwiseConverter<tosa::MaximumOp>,
3588 PointwiseConverter<tosa::MinimumOp>,
3589 PointwiseConverter<tosa::CeilOp>,
3590 PointwiseConverter<tosa::FloorOp>,
3591 PointwiseConverter<tosa::ClampOp>,
3592 PointwiseConverter<tosa::SigmoidOp>
3593 >(converter, patterns->getContext());
3594
3595 patterns->add<QuantizedMatMulTConverter>(converter, patterns->getContext());
3596
3597 patterns->add<
3598 IdentityNConverter<tosa::IdentityOp>,
3599 GatherConverter,
3600 RowGatherConverter,
3601 RescaleConverter,
3602 ReverseConverter,
3603 RFFT2dConverter,
3604 FFT2dConverter,
3605 TableConverter,
3606 TileConverter>(patterns->getContext());
3607
3608 // Reductions seeded with a float min/max identity need to know whether
3609 // non-finite values are available on the target.
3610 patterns->add<
3611 ReduceConverter<tosa::ReduceAllOp>,
3612 ReduceConverter<tosa::ReduceAnyOp>,
3613 ReduceConverter<tosa::ReduceMinOp>,
3614 ReduceConverter<tosa::ReduceMaxOp>,
3615 ReduceConverter<tosa::ReduceSumOp>,
3616 ReduceConverter<tosa::ReduceProductOp>,
3617 ArgMinMaxConverter<tosa::ArgMaxOp>,
3618 ArgMinMaxConverter<tosa::ArgMinOp>>(patterns->getContext(), options.allowNonFinites);
3619 // clang-format on
3620}
return success()
return MutableOperandRange * this
static int64_t product(ArrayRef< int64_t > vals)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static llvm::ManagedStatic< PassManagerOptions > options
static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static TypedAttr createInitialValueForReduceOp(Operation *op, Type elementTy, PatternRewriter &rewriter, bool allowNonFinites)
static OpFoldResult getOrFoldTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static Value createLinalgBodyCalculationForReduceOp(Operation *op, ValueRange args, Type elementTy, PatternRewriter &rewriter)
static std::pair< Value, Value > normalizeMatMulBatchDimensions(PatternRewriter &rewriter, Location loc, Value a, Value b, int64_t batchRank)
static OpTy createWithDefaultProperties(OpBuilder &builder, Location loc, TypeRange resultTypes, ValueRange operands)
static Value broadcastMatMulLeadingDimensions(PatternRewriter &rewriter, Location loc, Value operand, Value other)
static Value getTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static Value createIndex(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, int64_t index)
static LogicalResult reduceMatchAndRewriteHelper(OpTy op, uint64_t axis, PatternRewriter &rewriter, bool allowNonFinites)
static ValueRange getScalarOperands(Operation *operation, ValueRange operands)
static Value broadcastDynamicDimensions(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, ArrayRef< OpFoldResult > targetShape, ArrayRef< Value > masterOperands)
static Value broadcastDynamicDimension(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, int64_t dim, OpFoldResult targetSize, Value masterOperand)
static LogicalResult elementwiseMatchAndRewriteHelper(Operation *operation, ValueRange operands, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
static Value createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args, ArrayRef< Type > resultTypes, ConversionPatternRewriter &rewriter)
static LogicalResult emitElementwiseComputation(ConversionPatternRewriter &rewriter, Location loc, Operation *operation, ValueRange operands, ValueRange scalarOperands, ArrayRef< OpFoldResult > targetShape, const TypeConverter &converter)
static ValueRange getBroadcastableOperands(Operation *operation, ValueRange operands)
static Value materializeBinaryNanCheckIfRequired(OpTy op, PatternRewriter &rewriter, Value lhs, Value rhs, Value result)
static std::pair< SmallVector< OpFoldResult >, SmallVector< Value > > computeTargetShape(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands)
static bool operandsAndResultsRanked(Operation *operation)
static Value broadcastMatMulSingletonDimension(PatternRewriter &rewriter, Location loc, Value operand, int64_t dim, OpFoldResult size)
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
BlockArgument getArgument(unsigned i)
Definition Block.h:154
bool getValue() const
Return the boolean value of this attribute.
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
AffineExpr getAffineConstantExpr(int64_t constant)
Definition Builders.cpp:381
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
MLIRContext * getContext() const
Definition Builders.h:56
IntegerAttr getI8IntegerAttr(int8_t value)
Definition Builders.cpp:230
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.
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
unsigned getNumOperands()
Definition Operation.h:373
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
result_range getResults()
Definition Operation.h:442
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
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,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
bool isBF16() const
Definition Types.cpp:37
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
type_range getType() const
Type front()
Return first type in the range.
Definition TypeRange.h:164
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
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:352
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition TensorOps.cpp:83
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:92
Value clampFloatHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter)
llvm::DenseMap< int64_t, Value > IndexPool
Caches the arith.constant index values created for a set of dimension indices so that broadcasting he...
SmallVector< utils::IteratorType > getNParallelLoopsAttrs(unsigned nParallelLoops)
SmallVector< Value > condenseValues(const SmallVector< Value > &values)
std::optional< SmallVector< Value > > checkHasDynamicBatchDims(PatternRewriter &rewriter, Op op, ArrayRef< Value > params)
Value truncateToOutputType(PatternRewriter &rewriter, Location loc, Value input, RankedTensorType targetType)
Truncate an FP32 tensor to BF16 without changing shape or encoding.
MatMulTOperands prepareMatMulOperands(PatternRewriter &rewriter, Location loc, Value a, Value b, RankedTensorType outputType, bool transposeB)
Broadcast the batch dimensions of the ranked operands and create a zero-filled result tensor for eith...
std::pair< OpFoldResult, Value > computeTargetSize(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands, int64_t dim)
Compute the broadcasted runtime size of dimension dim of an elementwise operation whose operands all ...
APFloat getFloatMinMaxIdentity(const llvm::fltSemantics &semantics, bool negative, bool allowNonFinites)
void populateTosaToLinalgConversionPatterns(const TypeConverter &converter, RewritePatternSet *patterns, const TosaToLinalgOptions &options=TosaToLinalgOptions())
Populates conversion passes from TOSA dialect to Linalg dialect.
Type getAccumulationType(Type requestedType)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
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:311
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...