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