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