1 //===- TosaOps.cpp - MLIR Dialect for TOSA --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // \file
10 // This file implements the TOSA Specification:
11 // https://developer.mlplatform.org/w/tosa/
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "mlir/Dialect/Tosa/IR/TosaOps.h"
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/Dialect/Tensor/IR/Tensor.h"
18 #include "mlir/Dialect/Tosa/Utils/QuantUtils.h"
19 #include "mlir/Dialect/Tosa/Utils/ShapeUtils.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Transforms/FoldUtils.h"
24 #include "mlir/Transforms/InliningUtils.h"
25 #include "mlir/Transforms/RegionUtils.h"
26 #include "llvm/ADT/DenseMap.h"
27 
28 using namespace mlir;
29 using namespace mlir::tosa;
30 
31 #include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
32 
33 //===----------------------------------------------------------------------===//
34 // Tosa dialect structs and interface includes.
35 //===----------------------------------------------------------------------===//
36 #include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
37 #include "mlir/Dialect/Tosa/IR/TosaStructs.cpp.inc"
38 
39 namespace {
40 //===----------------------------------------------------------------------===//
41 // Dialect Function Inliner Interface.
42 //===----------------------------------------------------------------------===//
43 struct TosaInlinerInterface : public DialectInlinerInterface {
44   using DialectInlinerInterface::DialectInlinerInterface;
45 
46   //===--------------------------------------------------------------------===//
47   // Analysis Hooks.
48   //===--------------------------------------------------------------------===//
49 
50   /// All operations can be inlined by default.
51   bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
52                        BlockAndValueMapping &map) const final {
53     return true;
54   }
55 
56   /// All regions with If and While parent operators can be inlined.
57   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
58                        BlockAndValueMapping &map) const final {
59     return (isa<tosa::IfOp>(dest->getParentOp()) ||
60             isa<tosa::WhileOp>(dest->getParentOp()));
61   }
62 };
63 } // end anonymous namespace
64 
65 //===----------------------------------------------------------------------===//
66 // TOSA control flow support.
67 //===----------------------------------------------------------------------===//
68 
69 /// Returns the while loop body.
70 Region &tosa::WhileOp::getLoopBody() { return body(); }
71 
72 bool tosa::WhileOp::isDefinedOutsideOfLoop(Value value) {
73   return !body().isAncestor(value.getParentRegion());
74 }
75 
76 LogicalResult WhileOp::moveOutOfLoop(ArrayRef<mlir::Operation *> ops) {
77   if (ops.empty())
78     return success();
79 
80   Operation *tosaWhileOp = this->getOperation();
81   for (auto *op : ops)
82     op->moveBefore(tosaWhileOp);
83 
84   return success();
85 }
86 
87 //===----------------------------------------------------------------------===//
88 // Tosa dialect initialization.
89 //===----------------------------------------------------------------------===//
90 
91 void TosaDialect::initialize() {
92   addOperations<
93 #define GET_OP_LIST
94 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
95       >();
96   addInterfaces<TosaInlinerInterface>();
97 }
98 
99 Operation *TosaDialect::materializeConstant(OpBuilder &builder, Attribute value,
100                                             Type type, Location loc) {
101   // Tosa dialect constants only support ElementsAttr unlike standard dialect
102   // constant which supports all attributes.
103   if (value.isa<ElementsAttr>())
104     return builder.create<tosa::ConstOp>(loc, type, value.cast<ElementsAttr>());
105   return nullptr;
106 }
107 
108 //===----------------------------------------------------------------------===//
109 // Operator Canonicalizers.
110 //===----------------------------------------------------------------------===//
111 
112 struct ConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
113   using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
114 
115   LogicalResult matchAndRewrite(tosa::ConcatOp op,
116                                 PatternRewriter &rewriter) const override {
117     if (op.input1().size() != 1)
118       return failure();
119     if (op.input1().front().getType() != op.getType()) {
120       rewriter
121           .replaceOpWithNewOp<tensor::CastOp>(op, op.getType(),
122                                               op.input1().front())
123           .getResult();
124       return success();
125     }
126 
127     rewriter.replaceOp(op, op.input1().front());
128     return success();
129   }
130 };
131 
132 void ConcatOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
133                                            MLIRContext *context) {
134   results.insert<ConcatOptimization>(context);
135 }
136 
137 struct ReshapeReshapeOptimization : public OpRewritePattern<tosa::ReshapeOp> {
138   using OpRewritePattern<tosa::ReshapeOp>::OpRewritePattern;
139 
140   LogicalResult matchAndRewrite(tosa::ReshapeOp op,
141                                 PatternRewriter &rewriter) const override {
142     Value input = op.input1();
143     Operation *definingOp = input.getDefiningOp();
144     if (!definingOp)
145       return failure();
146 
147     if (tosa::ReshapeOp reshapeOp = dyn_cast<tosa::ReshapeOp>(definingOp)) {
148       rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
149           op, op.getType(), reshapeOp.input1(), op.new_shape());
150       return success();
151     }
152 
153     return failure();
154   }
155 };
156 
157 struct ReshapeConstOptimization : public OpRewritePattern<tosa::ReshapeOp> {
158   using OpRewritePattern<tosa::ReshapeOp>::OpRewritePattern;
159 
160   LogicalResult matchAndRewrite(tosa::ReshapeOp op,
161                                 PatternRewriter &rewriter) const override {
162     Value input = op.input1();
163     ArrayAttr newShape = op.new_shape();
164 
165     // Check if input is constant
166     DenseElementsAttr inputAttr;
167     if (!matchPattern(input, m_Constant(&inputAttr)))
168       return failure();
169 
170     // Check if has >1 consumer and is not splat
171     if (!input.hasOneUse() && !inputAttr.isSplat())
172       return failure();
173 
174     // Grab the new shape
175     SmallVector<int64_t> newShapeValues = llvm::to_vector<6>(
176         llvm::map_range(newShape.getValue(), [](const Attribute &val) {
177           return val.cast<IntegerAttr>().getValue().getSExtValue();
178         }));
179 
180     // Build new const op with correct output shape
181     ShapedType inputShape = input.getType().cast<ShapedType>();
182     DenseElementsAttr outputAttr =
183         inputAttr.reshape(inputShape.clone(newShapeValues));
184     rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, outputAttr.getType(),
185                                                outputAttr);
186     return success();
187   }
188 };
189 
190 void ReshapeOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
191                                             MLIRContext *context) {
192   results.insert<ReshapeReshapeOptimization>(context);
193   results.insert<ReshapeConstOptimization>(context);
194 }
195 
196 struct ConstantTransposeOptimization
197     : public OpRewritePattern<tosa::TransposeOp> {
198   using OpRewritePattern::OpRewritePattern;
199 
200   LogicalResult matchAndRewrite(tosa::TransposeOp op,
201                                 PatternRewriter &rewriter) const override {
202     auto outputType = op.getType().cast<ShapedType>();
203     ArrayRef<int64_t> outputShape = outputType.getShape();
204     // TOSA supports quantized types.
205     if (!outputType.getElementType().isIntOrIndexOrFloat())
206       return failure();
207 
208     DenseElementsAttr inputValues;
209     if (!matchPattern(op.input1(), m_Constant(&inputValues)))
210       return failure();
211     // Make sure the input is a constant that has a single user.
212     if (!llvm::hasSingleElement(op.input1().getDefiningOp()->getUsers()))
213       return failure();
214 
215     DenseIntElementsAttr permAttr;
216     if (!matchPattern(op.perms(), m_Constant(&permAttr)))
217       return failure();
218     auto permValues = llvm::to_vector<6>(llvm::map_range(
219         // TOSA allows both 32- and 64-bit integer tensors here.
220         permAttr.getValues<APInt>(),
221         [](const APInt &val) { return val.getZExtValue(); }));
222 
223     auto inputType = op.input1().getType().cast<ShapedType>();
224     ArrayRef<int64_t> inputShape = inputType.getShape();
225     int64_t numElements = inputType.getNumElements();
226 
227     SmallVector<Attribute, 4> outputValues;
228     outputValues.resize(numElements);
229 
230     // Transpose the input constant. Because we don't know its rank in advance,
231     // we need to loop over the range [0, element count) and delinearize the
232     // index.
233     for (int srcLinearIndex = 0; srcLinearIndex < numElements;
234          ++srcLinearIndex) {
235       SmallVector<uint64_t, 6> srcIndices(inputType.getRank(), 0);
236       int totalCount = srcLinearIndex;
237       for (int dim = inputType.getRank() - 1; dim >= 0; --dim) {
238         srcIndices[dim] = totalCount % inputShape[dim];
239         totalCount /= inputShape[dim];
240       }
241 
242       SmallVector<uint64_t, 6> dstIndices(outputType.getRank(), 0);
243       for (int dim = outputType.getRank() - 1; dim >= 0; --dim)
244         dstIndices[dim] = srcIndices[permValues[dim]];
245 
246       uint64_t dstLinearIndex = dstIndices.front();
247       for (int dim = 1; dim < outputType.getRank(); ++dim)
248         dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
249 
250       outputValues[dstLinearIndex] = inputValues.getValue(srcIndices);
251     }
252 
253     rewriter.replaceOpWithNewOp<tosa::ConstOp>(
254         op, outputType, DenseElementsAttr::get(outputType, outputValues));
255     return success();
256   }
257 };
258 
259 struct NoOpOptimization : public OpRewritePattern<tosa::TransposeOp> {
260   using OpRewritePattern::OpRewritePattern;
261 
262   LogicalResult matchAndRewrite(tosa::TransposeOp op,
263                                 PatternRewriter &rewriter) const override {
264     auto perm = op.perms();
265 
266     DenseIntElementsAttr permAttr;
267     if (!matchPattern(perm, m_Constant(&permAttr))) {
268       return failure();
269     }
270 
271     SmallVector<int64_t> permValues = llvm::to_vector<6>(
272         llvm::map_range(permAttr.getValues<APInt>(),
273                         [](const APInt &val) { return val.getSExtValue(); }));
274 
275     for (int i = 0, s = permValues.size(); i < s; i++) {
276       if (i != permValues[i]) {
277         return failure();
278       }
279     }
280 
281     rewriter.replaceOp(op, op.input1());
282     return success();
283   }
284 };
285 
286 void TransposeOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
287                                               MLIRContext *context) {
288   results.insert<ConstantTransposeOptimization>(context);
289   results.insert<NoOpOptimization>(context);
290 }
291 
292 //===----------------------------------------------------------------------===//
293 // Operator Folders.
294 //===----------------------------------------------------------------------===//
295 
296 OpFoldResult CastOp::fold(ArrayRef<Attribute> operands) {
297   if (input().getType() == getType())
298     return input();
299   return {};
300 }
301 
302 OpFoldResult ConstOp::fold(ArrayRef<Attribute> operands) {
303   assert(operands.empty() && "constant has no operands");
304   return valueAttr();
305 }
306 
307 #define ReduceFolder(OP)                                                       \
308   OpFoldResult OP::fold(ArrayRef<Attribute> operands) {                        \
309     ShapedType inputTy = input().getType().cast<ShapedType>();                 \
310     if (!inputTy.hasRank())                                                    \
311       return {};                                                               \
312     if (inputTy.getDimSize(axis()) == 1)                                       \
313       return input();                                                          \
314     return {};                                                                 \
315   }
316 
317 ReduceFolder(ReduceAllOp) ReduceFolder(ReduceAnyOp) ReduceFolder(ReduceMaxOp)
318     ReduceFolder(ReduceMinOp) ReduceFolder(ReduceProdOp)
319         ReduceFolder(ReduceSumOp)
320 #undef ReduceFolder
321 
322             OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) {
323   auto inputTy = input1().getType().dyn_cast<RankedTensorType>();
324   auto outputTy = getType().dyn_cast<RankedTensorType>();
325 
326   if (!inputTy || !outputTy || inputTy != outputTy)
327     return {};
328   return input1();
329 }
330 
331 OpFoldResult SliceOp::fold(ArrayRef<Attribute> operands) {
332   auto inputTy = input().getType().dyn_cast<RankedTensorType>();
333   auto outputTy = getType().dyn_cast<RankedTensorType>();
334 
335   if (!inputTy || !outputTy || inputTy != outputTy)
336     return {};
337   if (inputTy.hasStaticShape())
338     return input();
339 
340   return {};
341 }
342 
343 OpFoldResult TileOp::fold(ArrayRef<Attribute> operands) {
344   bool allOnes = true;
345   for (Attribute val : multiples().getValue()) {
346     allOnes = allOnes && val.cast<IntegerAttr>().getValue().getSExtValue() == 1;
347   }
348 
349   if (allOnes && input1().getType() == getType())
350     return input1();
351   return {};
352 }
353 
354 OpFoldResult TransposeOp::fold(ArrayRef<Attribute> operands) {
355   if (!operands[1])
356     return {};
357 
358   // Transposing splat values just means reshaping.
359   if (auto input = operands[0].dyn_cast_or_null<DenseElementsAttr>()) {
360     if (input.isSplat())
361       return input.reshape(getType().cast<ShapedType>());
362   }
363 
364   auto perms = llvm::to_vector<6>(llvm::map_range(
365       operands[1].cast<DenseIntElementsAttr>().getValues<APInt>(),
366       [](const APInt &val) { return val.getSExtValue(); }));
367 
368   if (llvm::equal(llvm::seq<int64_t>(0, perms.size()), perms) &&
369       input1().getType() == getType())
370     return input1();
371   return {};
372 }
373 
374 //===----------------------------------------------------------------------===//
375 // TOSA Operator Verifiers.
376 //===----------------------------------------------------------------------===//
377 
378 template <typename T>
379 static LogicalResult verifyConvOp(T op) {
380   // All TOSA conv ops have an input() and weight().
381   auto inputType = op.input().getType().template dyn_cast<RankedTensorType>();
382   auto weightType = op.weight().getType().template dyn_cast<RankedTensorType>();
383 
384   // Must be ranked tensor types
385   if (!inputType || !weightType)
386     return failure();
387 
388   auto inputEType = inputType.getElementType();
389   auto weightEType = weightType.getElementType();
390 
391   bool inputIsQuant = !inputEType.template isa<FloatType>();
392   bool weightIsQuant = !weightEType.template isa<FloatType>();
393 
394   // Either both must be quantized or both unquantized.
395   if (inputIsQuant != weightIsQuant)
396     return failure();
397 
398   // Quantized type must have constructed the quantizationattr, and unquantized
399   // types should not have a quantizationattr.
400   if ((inputIsQuant && !op.quantization_info()) ||
401       (!inputIsQuant && op.quantization_info()))
402     return failure();
403 
404   return success();
405 }
406 
407 static LogicalResult verifyAveragePoolOp(tosa::AvgPool2dOp op) {
408   auto inputETy = op.input().getType().cast<ShapedType>().getElementType();
409   auto resultETy = op.getType().cast<ShapedType>().getElementType();
410 
411   if (auto quantType = inputETy.dyn_cast<mlir::quant::UniformQuantizedType>())
412     inputETy = quantType.getStorageType();
413 
414   if (auto quantType = resultETy.dyn_cast<mlir::quant::UniformQuantizedType>())
415     resultETy = quantType.getStorageType();
416 
417   if (inputETy.isF32() && resultETy.isF32())
418     return success();
419   if (inputETy.isInteger(8) && resultETy.isInteger(32))
420     return success();
421   if (inputETy.isInteger(16) && resultETy.isInteger(32))
422     return success();
423 
424   return op.emitOpError("input/output element types are incompatible.");
425 }
426 
427 //===----------------------------------------------------------------------===//
428 // TOSA Operator Quantization Builders.
429 //===----------------------------------------------------------------------===//
430 
431 /// This builder is called on all convolution operators except TransposeConv,
432 /// which has specialized output shape semantics. The builder also defines the
433 /// bitwidth of the output given the bit width of the input & weight content.
434 static void buildConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
435                                      Type outputType, Value input, Value weight,
436                                      Value bias, ArrayAttr pad,
437                                      ArrayAttr stride, ArrayAttr dilation) {
438 
439   result.addOperands({input, weight, bias});
440   result.addAttribute("pad", pad);
441   result.addAttribute("stride", stride);
442   result.addAttribute("dilation", dilation);
443 
444   auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
445   if (quantAttr) {
446     result.addAttribute("quantization_info", quantAttr);
447     result.addTypes(
448         buildConvOpResultTypeInfo(builder, outputType, input, weight));
449   } else {
450     result.addTypes(outputType);
451   }
452 }
453 
454 /// Handles tosa.transpose_conv2d which has outpad and output shape attributes.
455 static void
456 buildTransConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
457                               Type outputType, Value input, Value weight,
458                               Value bias, ArrayAttr outpad, ArrayAttr stride,
459                               ArrayAttr dilation, ArrayAttr outputShape) {
460   result.addOperands({input, weight, bias});
461   result.addAttribute("out_pad", outpad);
462   result.addAttribute("stride", stride);
463   result.addAttribute("dilation", dilation);
464   result.addAttribute("out_shape", outputShape);
465   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
466 
467   if (quantAttr) {
468     result.addAttribute("quantization_info", quantAttr);
469     result.addTypes(
470         buildConvOpResultTypeInfo(builder, outputType, input, weight));
471   } else {
472     result.addTypes(outputType);
473   }
474 }
475 
476 /// The tosa.fully_connected op has its own builder as it does not have
477 /// strides/dilation/padding.
478 static void buildFCOpWithQuantInfo(OpBuilder &builder, OperationState &result,
479                                    Type outputType, Value input, Value weight,
480                                    Value bias) {
481 
482   result.addOperands({input, weight, bias});
483   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
484   if (quantAttr) {
485     result.addAttribute("quantization_info", quantAttr);
486     result.addTypes(
487         buildConvOpResultTypeInfo(builder, outputType, input, weight));
488   } else {
489     result.addTypes(outputType);
490   }
491 }
492 
493 /// The tosa.matmul op is also intended to be generated where a fully_connected
494 /// op must be constructed where the weight is not a constant. In this case,
495 /// the fully_connected op must be expressed using matmul.
496 /// TODO: Add link to the leglization document explaining this.
497 static void buildMatMulOpWithQuantInfo(OpBuilder &builder,
498                                        OperationState &result, Type outputType,
499                                        Value a, Value b) {
500   result.addOperands({a, b});
501   auto quantAttr = ::buildMatMulOpQuantizationAttr(builder, a, b);
502 
503   if (quantAttr) {
504     result.addAttribute("quantization_info", quantAttr);
505 
506     auto inputType = a.getType().dyn_cast<ShapedType>();
507     assert(inputType && "Input must be a shaped tensor type!");
508 
509     auto inputQType = inputType.getElementType()
510                           .dyn_cast<mlir::quant::UniformQuantizedType>();
511     assert(inputQType && "Tensor must have quantized datatype!");
512 
513     unsigned inputBits = inputQType.getStorageTypeIntegralWidth();
514 
515     auto outputShapedType = outputType.dyn_cast<ShapedType>();
516     assert(outputShapedType && "Output must be a shaped type");
517 
518     IntegerType accElementType;
519     if (inputBits == 16)
520       accElementType = builder.getIntegerType(48);
521     else
522       accElementType = builder.getI32Type();
523     auto accType = outputShapedType.clone(accElementType);
524     result.addTypes(accType);
525   } else {
526     result.addTypes(outputType);
527   }
528 }
529 
530 /// Both the tosa.avg_pool2d and unary ops use the same UnaruOpQuantizationAttr
531 /// but avg_pool operator has its own builder as it has additional parameters
532 /// not part of the unary ops.
533 static void buildAvgPool2dOpWithQuantInfo(OpBuilder &builder,
534                                           OperationState &result,
535                                           Type outputType, Value input,
536                                           ArrayAttr kernel, ArrayAttr stride,
537                                           ArrayAttr pad) {
538   result.addOperands(input);
539   result.addAttribute("kernel", kernel);
540   result.addAttribute("stride", stride);
541   result.addAttribute("pad", pad);
542   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
543   if (quantAttr)
544     result.addAttribute("quantization_info", quantAttr);
545   result.types.push_back(outputType);
546 }
547 
548 /// This builder is called on single-parameter unary operators that have scale
549 /// relationship between their input and output, expressed by the
550 /// UnaryOpQuantizationAttr.
551 static void buildUnaryOpWithQuantInfo(OpBuilder &builder,
552                                       OperationState &result, Type outputType,
553                                       Value input) {
554   result.addOperands(input);
555   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
556   if (quantAttr)
557     result.addAttribute("quantization_info", quantAttr);
558   result.types.push_back(outputType);
559 }
560 
561 /// This builder is called on TOSA pad operator that needs to create its own
562 /// OptionalAttr quantization_attr parameter to scale the padding values
563 /// correctly.
564 static void buildPadOpWithQuantInfo(OpBuilder &builder, OperationState &result,
565                                     Type outputType, Value input,
566                                     Value paddings) {
567   result.addOperands({input, paddings});
568   auto quantAttr = buildPadOpQuantizationAttr(builder, input);
569   if (quantAttr)
570     result.addAttribute("quantization_info", quantAttr);
571   result.types.push_back(outputType);
572 }
573 
574 //===----------------------------------------------------------------------===//
575 // TOSA Operator Return Type Inference.
576 //===----------------------------------------------------------------------===//
577 
578 static void getI64Values(ArrayAttr arrayAttr, SmallVector<int64_t> &values) {
579   for (auto it : arrayAttr) {
580     values.push_back(it.cast<IntegerAttr>().getValue().getSExtValue());
581   }
582 }
583 
584 static void getF64Values(ArrayAttr arrayAttr, SmallVector<double> &values) {
585   for (auto it : arrayAttr) {
586     values.push_back(it.cast<FloatAttr>().getValueAsDouble());
587   }
588 }
589 
590 LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
591     MLIRContext *context, ::llvm::Optional<Location> location,
592     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
593     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
594   ShapeAdaptor inputShape = operands.getShape(0);
595   IntegerAttr axis = attributes.get("axis").cast<IntegerAttr>();
596   int32_t axisVal = axis.getValue().getSExtValue();
597 
598   if (!inputShape.hasRank()) {
599     inferredReturnShapes.push_back(ShapedTypeComponents());
600     return success();
601   }
602 
603   SmallVector<int64_t> outShape;
604   outShape.reserve(inputShape.getRank() - 1);
605   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
606     if (i == axisVal)
607       continue;
608     outShape.push_back(inputShape.getDimSize(i));
609   }
610 
611   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
612   return success();
613 }
614 
615 LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
616     MLIRContext *context, ::llvm::Optional<Location> location,
617     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
618     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
619   // Infer all dimension sizes by reducing based on inputs.
620   int32_t axis =
621       attributes.get("axis").cast<IntegerAttr>().getValue().getSExtValue();
622   llvm::SmallVector<int64_t> outputShape;
623   bool hasRankedInput = false;
624   for (auto operand : operands) {
625     ShapeAdaptor operandShape = operands.getShape(operand);
626     if (!operandShape.hasRank())
627       continue;
628 
629     // Copy the Operand's rank.
630     if (!hasRankedInput)
631       outputShape.resize(operandShape.getRank(), ShapedType::kDynamicSize);
632 
633     // Copy shapes until the dim is non-dynamic.
634     for (int i = 0, s = operandShape.getRank(); i < s; i++) {
635       if (i == axis || operandShape.isDynamicDim(i))
636         continue;
637       if (outputShape[i] == ShapedType::kDynamicSize)
638         outputShape[i] = operandShape.getDimSize(i);
639       if (outputShape[i] != operandShape.getDimSize(i))
640         return failure();
641     }
642 
643     hasRankedInput = true;
644   }
645 
646   if (!hasRankedInput) {
647     inferredReturnShapes.push_back(ShapedTypeComponents());
648     return success();
649   }
650 
651   // Determine the dimension size along the concatenation axis.
652   int concatDimSize = 0;
653   for (auto operand : operands) {
654     ShapeAdaptor operandShape = operands.getShape(operand);
655 
656     // We need to know the length of the concatenation axis of all inputs to
657     // determine the dimension size of the output shape.
658     if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
659       concatDimSize = ShapedType::kDynamicSize;
660       break;
661     }
662 
663     concatDimSize += operandShape.getDimSize(axis);
664   }
665 
666   outputShape[axis] = concatDimSize;
667 
668   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
669   return success();
670 }
671 
672 LogicalResult tosa::FullyConnectedOp::inferReturnTypeComponents(
673     MLIRContext *context, ::llvm::Optional<Location> location,
674     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
675     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
676   ShapeAdaptor inputShape = operands.getShape(0);
677   ShapeAdaptor weightShape = operands.getShape(1);
678   ShapeAdaptor biasShape = operands.getShape(2);
679 
680   // All shapes are dynamic.
681   SmallVector<int64_t> outShape;
682   outShape.resize(2, ShapedType::kDynamicSize);
683 
684   if (inputShape.hasRank()) {
685     outShape[0] = inputShape.getDimSize(0);
686   }
687 
688   if (weightShape.hasRank()) {
689     outShape[1] = weightShape.getDimSize(0);
690   }
691 
692   if (biasShape.hasRank()) {
693     outShape[1] = outShape[1] == ShapedType::kDynamicSize
694                       ? biasShape.getDimSize(0)
695                       : outShape[1];
696   }
697 
698   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
699   return success();
700 }
701 
702 LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
703     MLIRContext *context, ::llvm::Optional<Location> location,
704     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
705     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
706   ShapeAdaptor lhsShape = operands.getShape(0);
707   ShapeAdaptor rhsShape = operands.getShape(1);
708 
709   // All shapes are dynamic.
710   SmallVector<int64_t> outShape;
711   outShape.resize(3, ShapedType::kDynamicSize);
712 
713   if (lhsShape.hasRank()) {
714     outShape[0] = lhsShape.getDimSize(0);
715     outShape[1] = lhsShape.getDimSize(1);
716   }
717 
718   if (rhsShape.hasRank()) {
719     outShape[0] = outShape[0] == ShapedType::kDynamicSize
720                       ? rhsShape.getDimSize(0)
721                       : outShape[0];
722     outShape[2] = rhsShape.getDimSize(2);
723   }
724 
725   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
726   return success();
727 }
728 
729 LogicalResult tosa::PadOp::inferReturnTypeComponents(
730     MLIRContext *context, ::llvm::Optional<Location> location,
731     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
732     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
733   ShapeAdaptor inputShape = operands.getShape(0);
734   ShapeAdaptor paddingShape = operands.getShape(1);
735   SmallVector<int64_t> outputShape;
736 
737   // If both inputs have unknown shape, we cannot determine the shape of the
738   // output.
739   if (!inputShape.hasRank() && !paddingShape.hasRank()) {
740     inferredReturnShapes.push_back(ShapedTypeComponents());
741     return success();
742   }
743 
744   // If the input rank is unknown we can info the output rank using the padding
745   // shape's first dim.
746   if (!inputShape.hasRank()) {
747     if (paddingShape.isDynamicDim(0)) {
748       inferredReturnShapes.push_back(ShapedTypeComponents());
749       return success();
750     }
751 
752     outputShape.resize(paddingShape.getDimSize(0), ShapedType::kDynamicSize);
753     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
754     return success();
755   }
756 
757   DenseIntElementsAttr paddings;
758   // If the paddings value is not a constant, all dimensions must be dynamic.
759   if (!matchPattern(operands[1], m_Constant(&paddings))) {
760     outputShape.resize(inputShape.getRank(), ShapedType::kDynamicSize);
761     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
762     return success();
763   }
764 
765   SmallVector<int64_t> paddingValues;
766   for (auto val : paddings) {
767     paddingValues.push_back(val.getSExtValue());
768   }
769 
770   outputShape.reserve(inputShape.getRank());
771   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
772     if (inputShape.isDynamicDim(i)) {
773       outputShape.push_back(ShapedType::kDynamicSize);
774       continue;
775     }
776 
777     outputShape.push_back(inputShape.getDimSize(i) + paddingValues[i * 2] +
778                           paddingValues[i * 2 + 1]);
779   }
780 
781   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
782   return success();
783 }
784 
785 LogicalResult tosa::SliceOp::inferReturnTypeComponents(
786     MLIRContext *context, ::llvm::Optional<Location> location,
787     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
788     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
789   ArrayAttr sizes = SliceOpAdaptor(operands, attributes).size();
790   SmallVector<int64_t> outputShape;
791   outputShape.reserve(sizes.size());
792   for (auto val : sizes) {
793     outputShape.push_back(val.cast<IntegerAttr>().getValue().getSExtValue());
794   }
795 
796   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
797   return success();
798 }
799 
800 LogicalResult tosa::TableOp::inferReturnTypeComponents(
801     MLIRContext *context, ::llvm::Optional<Location> location,
802     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
803     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
804   ShapeAdaptor inputShape = operands.getShape(0);
805 
806   if (!inputShape.hasRank()) {
807     inferredReturnShapes.push_back(ShapedTypeComponents());
808     return success();
809   }
810 
811   inferredReturnShapes.resize(1);
812   inputShape.getDims(inferredReturnShapes[0]);
813   return success();
814 }
815 
816 LogicalResult tosa::TileOp::inferReturnTypeComponents(
817     MLIRContext *context, ::llvm::Optional<Location> location,
818     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
819     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
820   TileOpAdaptor adaptor(operands, attributes);
821   ArrayAttr multiples = adaptor.multiples();
822   ShapeAdaptor inputShape = operands.getShape(0);
823   SmallVector<int64_t> outputShape;
824   if (!inputShape.hasRank()) {
825     outputShape.resize(multiples.size(), ShapedType::kDynamicSize);
826     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
827     return success();
828   }
829 
830   // We need the multiple values to determine the output shape.
831   SmallVector<int64_t> multipleValues;
832   multipleValues.reserve(multiples.size());
833   for (auto val : multiples) {
834     multipleValues.push_back(val.cast<IntegerAttr>().getValue().getSExtValue());
835   }
836 
837   // Any non dynamic dimension can be multiplied to a known size.
838   outputShape.reserve(multiples.size());
839   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
840     int dim = inputShape.getDimSize(i);
841     if (dim != ShapedType::kDynamicSize)
842       dim *= multipleValues[i];
843     outputShape.push_back(dim);
844   }
845 
846   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
847   return success();
848 }
849 
850 LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
851     MLIRContext *context, ::llvm::Optional<Location> location,
852     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
853     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
854   ReshapeOpAdaptor adaptor(operands, attributes);
855   ShapeAdaptor inputShape = operands.getShape(0);
856 
857   ArrayAttr newShape = adaptor.new_shape();
858   llvm::SmallVector<int64_t> newShapeValue;
859   getI64Values(newShape, newShapeValue);
860 
861   // We cannot infer from the total number of elements so we must take the
862   // shape attribute as exact.
863   if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
864     inferredReturnShapes.push_back(ShapedTypeComponents(newShapeValue));
865     return success();
866   }
867 
868   // Determine the number of elements covered by the slice of all static
869   // dimensions. This allows us to infer the length of the remaining dynamic
870   // dimension.
871   int64_t numElements = inputShape.getNumElements();
872   int64_t staticMul = 1;
873   for (auto val : newShapeValue) {
874     if (val != ShapedType::kDynamicSize) {
875       staticMul *= val;
876     }
877   }
878 
879   // Determine the length of the dynamic dimension.
880   for (auto &val : newShapeValue) {
881     if (val == ShapedType::kDynamicSize)
882       val = numElements / staticMul;
883   }
884 
885   inferredReturnShapes.push_back(ShapedTypeComponents(newShapeValue));
886   return success();
887 }
888 
889 LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
890     MLIRContext *context, ::llvm::Optional<Location> location,
891     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
892     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
893   ShapeAdaptor inputShape = operands.getShape(0);
894   ShapeAdaptor permsShape = operands.getShape(1);
895 
896   // If input rank and permutation length is unknown, the output rank is
897   // unknown.
898   if (!inputShape.hasRank() || !permsShape.hasRank() ||
899       permsShape.isDynamicDim(0)) {
900     inferredReturnShapes.push_back(ShapedTypeComponents());
901     return success();
902   }
903 
904   // This would imply the number of permutations does not match the rank of the
905   // input which is illegal.
906   if (permsShape.getDimSize(0) != inputShape.getRank()) {
907     return failure();
908   }
909 
910   // Without the input dims we cannot determine the output dim sizes but we
911   // can determine the output rank.
912   SmallVector<int64_t> outputShape;
913   if (!inputShape.hasRank()) {
914     outputShape.resize(permsShape.getDimSize(0), ShapedType::kDynamicSize);
915     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
916     return success();
917   }
918 
919   // Rank-0 means no permutations matter.
920   if (inputShape.getRank() == 0) {
921     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
922     return success();
923   }
924 
925   // Check whether the input dimensions are all the same.
926   bool allTheSame = true;
927   for (int i = 1, s = inputShape.getRank(); i < s; i++) {
928     if (inputShape.getDimSize(0) != inputShape.getDimSize(i)) {
929       allTheSame = false;
930       break;
931     }
932   }
933 
934   // If all of the input dimensions are the same we don't care about the
935   // permutation.
936   if (allTheSame) {
937     outputShape.resize(inputShape.getRank(), inputShape.getDimSize(0));
938     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
939     return success();
940   }
941 
942   outputShape.resize(inputShape.getRank(), ShapedType::kDynamicSize);
943   // If the permuations are a constant we can directly determine the output
944   // shape.
945   if (ShapeAdaptor permShape = operands.getValueAsShape(1)) {
946     outputShape.reserve(inputShape.getRank());
947     for (int i = 0, s = inputShape.getRank(); i < s; i++) {
948       outputShape[i] = inputShape.getDimSize(permShape.getDimSize(i));
949     }
950   }
951 
952   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
953   return success();
954 }
955 
956 LogicalResult tosa::GatherOp::inferReturnTypeComponents(
957     MLIRContext *context, ::llvm::Optional<Location> location,
958     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
959     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
960   llvm::SmallVector<int64_t> outputShape;
961   outputShape.resize(3, ShapedType::kDynamicSize);
962 
963   ShapeAdaptor valuesShape = operands.getShape(0);
964   if (valuesShape.hasRank()) {
965     outputShape[0] = valuesShape.getDimSize(0);
966     outputShape[2] = valuesShape.getDimSize(2);
967   }
968 
969   ShapeAdaptor indicesShape = operands.getShape(1);
970   if (indicesShape.hasRank()) {
971     if (outputShape[0] == ShapedType::kDynamicSize)
972       outputShape[0] = indicesShape.getDimSize(0);
973     if (outputShape[1] == ShapedType::kDynamicSize)
974       outputShape[1] = indicesShape.getDimSize(1);
975   }
976 
977   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
978   return success();
979 }
980 
981 LogicalResult tosa::ResizeOp::inferReturnTypeComponents(
982     MLIRContext *context, ::llvm::Optional<Location> location,
983     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
984     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
985   ResizeOpAdaptor adaptor(operands, attributes);
986   llvm::SmallVector<int64_t, 4> outputShape;
987   outputShape.resize(4, ShapedType::kDynamicSize);
988 
989   int32_t inHeight = ShapedType::kDynamicSize;
990   int32_t inWidth = ShapedType::kDynamicSize;
991 
992   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
993   if (inputShape.hasRank()) {
994     outputShape[0] = inputShape.getDimSize(0);
995     outputShape[3] = inputShape.getDimSize(3);
996 
997     inHeight = inputShape.getDimSize(1);
998     inWidth = inputShape.getDimSize(2);
999   }
1000 
1001   int32_t shift = adaptor.shift().getValue().getSExtValue();
1002   llvm::SmallVector<int64_t> newShape;
1003   getI64Values(adaptor.output_size(), newShape);
1004   outputShape[1] = newShape[0];
1005   outputShape[2] = newShape[1];
1006 
1007   llvm::SmallVector<int64_t> strideInt;
1008   llvm::SmallVector<int64_t> offsetInt;
1009   llvm::SmallVector<double> strideFp;
1010   llvm::SmallVector<double> offsetFp;
1011   getI64Values(adaptor.offset(), offsetInt);
1012   getF64Values(adaptor.offset_fp(), offsetFp);
1013   getI64Values(adaptor.stride(), strideInt);
1014   getF64Values(adaptor.stride_fp(), strideFp);
1015 
1016   // If we have a 0 zero in integers we know that the resize indexing needs to
1017   // be performed in floating point. Use the floating point varient to compute
1018   // the resize shape.
1019   bool fpMode = strideInt[0] == 0;
1020 
1021   // We can compute the output shape if attribute specifies unknown dimensions
1022   // based on the offset and stride. If we perfectly line up to the last index
1023   // we need to round up the size to include it.
1024   if (outputShape[1] == ShapedType::kDynamicSize && inHeight >= 0 && fpMode) {
1025     float sizeFp = (inHeight - offsetFp[0] - 1) / strideFp[0];
1026     float round = std::floor(sizeFp) == sizeFp ? 1 : 0;
1027     outputShape[1] = std::ceil(sizeFp) + round;
1028   }
1029 
1030   if (outputShape[2] == ShapedType::kDynamicSize && inWidth >= 0 && fpMode) {
1031     float sizeFp = (inWidth - offsetFp[1] - 1) / strideFp[1];
1032     float round = std::floor(sizeFp) == sizeFp ? 1 : 0;
1033     outputShape[2] = std::ceil(sizeFp) + round;
1034   }
1035 
1036   if (outputShape[1] == ShapedType::kDynamicSize && inHeight >= 0 && !fpMode) {
1037     int64_t size = (inHeight - 1);
1038     size = ((size << shift) - offsetInt[0]) / strideInt[0];
1039     outputShape[1] = size + 1;
1040   }
1041 
1042   if (outputShape[2] == ShapedType::kDynamicSize && inWidth >= 0 && !fpMode) {
1043     int64_t size = (inWidth - 1);
1044     size = ((size << shift) - offsetInt[1]) / strideInt[1];
1045     outputShape[2] = size + 1;
1046   }
1047 
1048   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1049   return success();
1050 }
1051 
1052 LogicalResult tosa::ScatterOp::inferReturnTypeComponents(
1053     MLIRContext *context, ::llvm::Optional<Location> location,
1054     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1055     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1056   llvm::SmallVector<int64_t> outputShape;
1057   outputShape.resize(3, ShapedType::kDynamicSize);
1058 
1059   ShapeAdaptor valuesInShape = operands.getShape(0);
1060   if (valuesInShape.hasRank()) {
1061     outputShape[0] = valuesInShape.getDimSize(0);
1062     outputShape[1] = valuesInShape.getDimSize(1);
1063     outputShape[2] = valuesInShape.getDimSize(2);
1064   }
1065 
1066   ShapeAdaptor indicesShape = operands.getShape(1);
1067   if (indicesShape.hasRank()) {
1068     if (outputShape[0] == ShapedType::kDynamicSize)
1069       outputShape[0] = indicesShape.getDimSize(0);
1070   }
1071 
1072   ShapeAdaptor inputShape = operands.getShape(2);
1073   if (inputShape.hasRank()) {
1074     if (outputShape[0] == ShapedType::kDynamicSize)
1075       outputShape[0] = inputShape.getDimSize(0);
1076     if (outputShape[2] == ShapedType::kDynamicSize)
1077       outputShape[2] = inputShape.getDimSize(2);
1078   }
1079 
1080   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1081   return success();
1082 }
1083 
1084 static LogicalResult ReduceInferReturnTypes(
1085     ShapeAdaptor operandShape, IntegerAttr axis,
1086     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1087   if (!operandShape.hasRank()) {
1088     inferredReturnShapes.push_back(ShapedTypeComponents());
1089     return success();
1090   }
1091 
1092   SmallVector<int64_t> outputShape;
1093   operandShape.getDims(outputShape);
1094   int64_t axisVal = axis.getValue().getSExtValue();
1095   outputShape[axisVal] = 1;
1096   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1097   return success();
1098 }
1099 
1100 #define REDUCE_SHAPE_INFER(OP)                                                 \
1101   LogicalResult OP::inferReturnTypeComponents(                                 \
1102       MLIRContext *context, ::llvm::Optional<Location> location,               \
1103       ValueShapeRange operands, DictionaryAttr attributes,                     \
1104       RegionRange regions,                                                     \
1105       SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {           \
1106     return ReduceInferReturnTypes(operands.getShape(0),                        \
1107                                   attributes.get("axis").cast<IntegerAttr>(),  \
1108                                   inferredReturnShapes);                       \
1109   }
1110 
1111 REDUCE_SHAPE_INFER(tosa::ReduceAllOp)
1112 REDUCE_SHAPE_INFER(tosa::ReduceAnyOp)
1113 REDUCE_SHAPE_INFER(tosa::ReduceMaxOp)
1114 REDUCE_SHAPE_INFER(tosa::ReduceMinOp)
1115 REDUCE_SHAPE_INFER(tosa::ReduceProdOp)
1116 REDUCE_SHAPE_INFER(tosa::ReduceSumOp)
1117 #undef REDUCE_SHAPE_INFER
1118 
1119 static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands,
1120                                            SmallVector<int64_t> &outShape) {
1121   int64_t outRank = 0;
1122   for (int i = 0, e = operands.size(); i != e; ++i) {
1123     auto shape = operands.getShape(i);
1124     if (!shape.hasRank()) {
1125       return failure();
1126     }
1127     outRank = std::max<int64_t>(outRank, shape.getRank());
1128   }
1129 
1130   outShape.resize(outRank, 1);
1131 
1132   for (int i = 0, e = operands.size(); i != e; ++i) {
1133     auto shape = operands.getShape(i);
1134     auto rankDiff = outShape.size() - shape.getRank();
1135 
1136     for (size_t i = 0, e = shape.getRank(); i < e; ++i) {
1137       auto dim1 = outShape[i + rankDiff];
1138       auto dim2 = shape.getDimSize(i);
1139       auto resolvedDim = dim1;
1140 
1141       if (dim1 == 1) {
1142         resolvedDim = dim2;
1143       } else if (dim2 == 1) {
1144         resolvedDim = dim1;
1145       } else if (dim1 != dim2) {
1146         return failure();
1147       }
1148       outShape[i + rankDiff] = resolvedDim;
1149     }
1150   }
1151 
1152   return success();
1153 }
1154 
1155 static LogicalResult NAryInferReturnTypes(
1156     const ValueShapeRange &operands,
1157     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1158   llvm::SmallVector<int64_t> outShape;
1159   if (resolveBroadcastShape(operands, outShape).failed()) {
1160     inferredReturnShapes.push_back(ShapedTypeComponents());
1161   } else {
1162     inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
1163   }
1164   return success();
1165 }
1166 
1167 #define NARY_SHAPE_INFER(OP)                                                   \
1168   LogicalResult OP::inferReturnTypeComponents(                                 \
1169       MLIRContext *context, ::llvm::Optional<Location> location,               \
1170       ValueShapeRange operands, DictionaryAttr attributes,                     \
1171       RegionRange regions,                                                     \
1172       SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {           \
1173     return NAryInferReturnTypes(operands, inferredReturnShapes);               \
1174   }
1175 
1176 NARY_SHAPE_INFER(tosa::AbsOp)
1177 NARY_SHAPE_INFER(tosa::AddOp)
1178 NARY_SHAPE_INFER(tosa::ArithmeticRightShiftOp)
1179 NARY_SHAPE_INFER(tosa::BitwiseAndOp)
1180 NARY_SHAPE_INFER(tosa::BitwiseOrOp)
1181 NARY_SHAPE_INFER(tosa::BitwiseXorOp)
1182 NARY_SHAPE_INFER(tosa::BitwiseNotOp)
1183 NARY_SHAPE_INFER(tosa::CastOp)
1184 NARY_SHAPE_INFER(tosa::CeilOp)
1185 NARY_SHAPE_INFER(tosa::ClampOp)
1186 NARY_SHAPE_INFER(tosa::ClzOp)
1187 NARY_SHAPE_INFER(tosa::DivOp)
1188 NARY_SHAPE_INFER(tosa::EqualOp)
1189 NARY_SHAPE_INFER(tosa::ExpOp)
1190 NARY_SHAPE_INFER(tosa::FloorOp)
1191 NARY_SHAPE_INFER(tosa::GreaterEqualOp)
1192 NARY_SHAPE_INFER(tosa::GreaterOp)
1193 NARY_SHAPE_INFER(tosa::IdentityOp)
1194 NARY_SHAPE_INFER(tosa::LogOp)
1195 NARY_SHAPE_INFER(tosa::LogicalAndOp)
1196 NARY_SHAPE_INFER(tosa::LogicalLeftShiftOp)
1197 NARY_SHAPE_INFER(tosa::LogicalNotOp)
1198 NARY_SHAPE_INFER(tosa::LogicalOrOp)
1199 NARY_SHAPE_INFER(tosa::LogicalRightShiftOp)
1200 NARY_SHAPE_INFER(tosa::LogicalXorOp)
1201 NARY_SHAPE_INFER(tosa::MaximumOp)
1202 NARY_SHAPE_INFER(tosa::MinimumOp)
1203 NARY_SHAPE_INFER(tosa::MulOp)
1204 NARY_SHAPE_INFER(tosa::NegateOp)
1205 NARY_SHAPE_INFER(tosa::PowOp)
1206 NARY_SHAPE_INFER(tosa::ReciprocalOp)
1207 NARY_SHAPE_INFER(tosa::ReluNOp)
1208 NARY_SHAPE_INFER(tosa::RescaleOp)
1209 NARY_SHAPE_INFER(tosa::ReverseOp)
1210 NARY_SHAPE_INFER(tosa::RsqrtOp)
1211 NARY_SHAPE_INFER(tosa::SelectOp)
1212 NARY_SHAPE_INFER(tosa::SubOp)
1213 NARY_SHAPE_INFER(tosa::TanhOp)
1214 NARY_SHAPE_INFER(tosa::SigmoidOp)
1215 #undef PRED_SHAPE_INFER
1216 
1217 static LogicalResult poolingInferReturnTypes(
1218     const ValueShapeRange &operands, DictionaryAttr attributes,
1219     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1220   ShapeAdaptor inputShape = operands.getShape(0);
1221   llvm::SmallVector<int64_t> outputShape;
1222   outputShape.resize(4, -1);
1223 
1224   // We only know the rank if the input type is unranked.
1225   if (!inputShape) {
1226     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1227     return success();
1228   }
1229 
1230   // Batch and number of channels are identical for pooling layer.
1231   outputShape[0] = inputShape.getDimSize(0);
1232   outputShape[3] = inputShape.getDimSize(3);
1233 
1234   int32_t height = inputShape.getDimSize(1);
1235   int32_t width = inputShape.getDimSize(2);
1236 
1237   llvm::SmallVector<int64_t> kernel;
1238   llvm::SmallVector<int64_t> stride;
1239   llvm::SmallVector<int64_t> pad;
1240 
1241   getI64Values(attributes.get("kernel").cast<ArrayAttr>(), kernel);
1242   getI64Values(attributes.get("stride").cast<ArrayAttr>(), stride);
1243   getI64Values(attributes.get("pad").cast<ArrayAttr>(), pad);
1244 
1245   if (height != -1) {
1246     int32_t padded = height + pad[0] + pad[1] - kernel[0];
1247     outputShape[1] = padded / stride[0] + 1;
1248   }
1249 
1250   if (width != -1) {
1251     int32_t padded = width + pad[2] + pad[3] - kernel[1];
1252     outputShape[2] = padded / stride[1] + 1;
1253   }
1254 
1255   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1256   return success();
1257 }
1258 
1259 LogicalResult Conv2DOp::inferReturnTypeComponents(
1260     MLIRContext *context, ::llvm::Optional<Location> location,
1261     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1262     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1263   llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamicSize);
1264   Conv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1265 
1266   int32_t inputWidth = ShapedType::kDynamicSize;
1267   int32_t inputHeight = ShapedType::kDynamicSize;
1268   int32_t weightWidth = ShapedType::kDynamicSize;
1269   int32_t weightHeight = ShapedType::kDynamicSize;
1270 
1271   // Input shape describes input width/height and batch.
1272 
1273   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1274   if (inputShape.hasRank()) {
1275     outputShape[0] = inputShape.getDimSize(0);
1276     inputHeight = inputShape.getDimSize(1);
1277     inputWidth = inputShape.getDimSize(2);
1278   }
1279 
1280   // Weight shapes describes the filter width/height and the output channels.
1281   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1282   if (weightShape.hasRank()) {
1283     outputShape[3] = weightShape.getDimSize(0);
1284     weightHeight = weightShape.getDimSize(1);
1285     weightWidth = weightShape.getDimSize(2);
1286   }
1287 
1288   // Bias shape can describe the output channels.
1289   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1290   if (biasShape.hasRank()) {
1291     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1292                          ? biasShape.getDimSize(0)
1293                          : outputShape[3];
1294   }
1295 
1296   llvm::SmallVector<int64_t> dilation;
1297   llvm::SmallVector<int64_t> padding;
1298   llvm::SmallVector<int64_t> stride;
1299 
1300   getI64Values(adaptor.dilation(), dilation);
1301   getI64Values(adaptor.pad(), padding);
1302   getI64Values(adaptor.stride(), stride);
1303 
1304   if (!ShapedType::isDynamic(inputHeight) &&
1305       !ShapedType::isDynamic(weightHeight)) {
1306     int32_t inputSize = inputHeight + padding[0] + padding[1];
1307     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1308     int32_t unstridedResult = inputSize - filterSize + 1;
1309     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1310   }
1311 
1312   if (!ShapedType::isDynamic(inputWidth) &&
1313       !ShapedType::isDynamic(weightWidth)) {
1314     int32_t inputSize = inputWidth + padding[2] + padding[3];
1315     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1316     int32_t unstridedResult = inputSize - filterSize + 1;
1317     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1318   }
1319 
1320   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1321   return success();
1322 }
1323 
1324 LogicalResult Conv3DOp::inferReturnTypeComponents(
1325     MLIRContext *context, ::llvm::Optional<Location> location,
1326     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1327     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1328   llvm::SmallVector<int64_t> outputShape(5, ShapedType::kDynamicSize);
1329   Conv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1330 
1331   int32_t inputWidth = ShapedType::kDynamicSize;
1332   int32_t inputHeight = ShapedType::kDynamicSize;
1333   int32_t inputDepth = ShapedType::kDynamicSize;
1334 
1335   int32_t weightWidth = ShapedType::kDynamicSize;
1336   int32_t weightHeight = ShapedType::kDynamicSize;
1337   int32_t weightDepth = ShapedType::kDynamicSize;
1338 
1339   // Input shape describes input width/height and batch.
1340   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1341   if (inputShape.hasRank()) {
1342     outputShape[0] = inputShape.getDimSize(0);
1343     inputHeight = inputShape.getDimSize(1);
1344     inputWidth = inputShape.getDimSize(2);
1345     inputDepth = inputShape.getDimSize(3);
1346   }
1347 
1348   // Weight shapes describes the filter width/height and the output channels.
1349   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1350   if (weightShape.hasRank()) {
1351     outputShape[4] = weightShape.getDimSize(0);
1352     weightHeight = weightShape.getDimSize(1);
1353     weightWidth = weightShape.getDimSize(2);
1354     weightDepth = weightShape.getDimSize(3);
1355   }
1356 
1357   // Bias shape can describe the output channels.
1358   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1359   if (biasShape.hasRank()) {
1360     outputShape[4] =
1361         (outputShape[4] == -1) ? biasShape.getDimSize(0) : outputShape[4];
1362   }
1363 
1364   llvm::SmallVector<int64_t> dilation;
1365   llvm::SmallVector<int64_t> padding;
1366   llvm::SmallVector<int64_t> stride;
1367 
1368   getI64Values(adaptor.dilation(), dilation);
1369   getI64Values(adaptor.pad(), padding);
1370   getI64Values(adaptor.stride(), stride);
1371 
1372   if (!ShapedType::isDynamic(inputHeight) &&
1373       !ShapedType::isDynamic(weightHeight)) {
1374     int32_t inputSize = inputHeight + padding[0] + padding[1];
1375     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1376     int32_t unstridedResult = inputSize - filterSize + 1;
1377     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1378   }
1379 
1380   if (!ShapedType::isDynamic(inputWidth) &&
1381       !ShapedType::isDynamic(weightWidth)) {
1382     int32_t inputSize = inputWidth + padding[2] + padding[3];
1383     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1384     int32_t unstridedResult = inputSize - filterSize + 1;
1385     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1386   }
1387 
1388   if (!ShapedType::isDynamic(inputDepth) &&
1389       !ShapedType::isDynamic(weightDepth)) {
1390     int32_t inputSize = inputDepth + padding[4] + padding[5];
1391     int32_t filterSize = (weightDepth - 1) * dilation[2] + 1;
1392     int32_t unstridedResult = inputSize - filterSize + 1;
1393     outputShape[3] = (unstridedResult - 1) / stride[2] + 1;
1394   }
1395 
1396   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1397   return success();
1398 }
1399 
1400 LogicalResult AvgPool2dOp::inferReturnTypeComponents(
1401     MLIRContext *context, ::llvm::Optional<Location> location,
1402     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1403     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1404   return poolingInferReturnTypes(operands, attributes, inferredReturnShapes);
1405 }
1406 
1407 LogicalResult MaxPool2dOp::inferReturnTypeComponents(
1408     MLIRContext *context, ::llvm::Optional<Location> location,
1409     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1410     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1411   return poolingInferReturnTypes(operands, attributes, inferredReturnShapes);
1412 }
1413 
1414 LogicalResult DepthwiseConv2DOp::inferReturnTypeComponents(
1415     MLIRContext *context, ::llvm::Optional<Location> location,
1416     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1417     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1418   llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamicSize);
1419   DepthwiseConv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1420 
1421   int32_t inputWidth = ShapedType::kDynamicSize;
1422   int32_t inputHeight = ShapedType::kDynamicSize;
1423   int32_t inputChannels = ShapedType::kDynamicSize;
1424 
1425   int32_t weightWidth = ShapedType::kDynamicSize;
1426   int32_t weightHeight = ShapedType::kDynamicSize;
1427   int32_t depthChannels = ShapedType::kDynamicSize;
1428 
1429   // Input shape describes input width/height and batch.
1430   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1431   if (inputShape.hasRank()) {
1432     outputShape[0] = inputShape.getDimSize(0);
1433     inputHeight = inputShape.getDimSize(1);
1434     inputWidth = inputShape.getDimSize(2);
1435     inputChannels = inputShape.getDimSize(3);
1436   }
1437 
1438   // Weight shapes describes the filter width/height and the output channels.
1439   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1440   if (weightShape.hasRank()) {
1441     weightHeight = weightShape.getDimSize(0);
1442     weightWidth = weightShape.getDimSize(1);
1443     inputChannels = ShapedType::isDynamic(inputChannels)
1444                         ? weightShape.getDimSize(2)
1445                         : inputChannels;
1446     depthChannels = weightShape.getDimSize(3);
1447   }
1448 
1449   // If both inputChannels and depthChannels are available we can determine
1450   // the output channels.
1451   if (!ShapedType::isDynamic(inputChannels) &&
1452       !ShapedType::isDynamic(depthChannels)) {
1453     outputShape[3] = inputChannels * depthChannels;
1454   }
1455 
1456   // Bias shape can describe the output channels.
1457   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1458   if (biasShape.hasRank()) {
1459     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1460                          ? biasShape.getDimSize(0)
1461                          : outputShape[3];
1462   }
1463 
1464   llvm::SmallVector<int64_t> dilation;
1465   llvm::SmallVector<int64_t> padding;
1466   llvm::SmallVector<int64_t> stride;
1467 
1468   getI64Values(adaptor.dilation(), dilation);
1469   getI64Values(adaptor.pad(), padding);
1470   getI64Values(adaptor.stride(), stride);
1471 
1472   if (!ShapedType::isDynamic(inputHeight) &&
1473       !ShapedType::isDynamic(weightHeight)) {
1474     int32_t inputSize = inputHeight + padding[0] + padding[1];
1475     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1476     int32_t unstridedResult = inputSize - filterSize + 1;
1477     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1478   }
1479 
1480   if (!ShapedType::isDynamic(inputWidth) &&
1481       !ShapedType::isDynamic(weightWidth)) {
1482     int32_t inputSize = inputWidth + padding[2] + padding[3];
1483     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1484     int32_t unstridedResult = inputSize - filterSize + 1;
1485     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1486   }
1487 
1488   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1489   return success();
1490 }
1491 
1492 LogicalResult TransposeConv2DOp::inferReturnTypeComponents(
1493     MLIRContext *context, ::llvm::Optional<Location> location,
1494     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1495     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1496   TransposeConv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1497   llvm::SmallVector<int64_t> outputShape;
1498   getI64Values(adaptor.out_shape(), outputShape);
1499 
1500   int32_t inputWidth = ShapedType::kDynamicSize;
1501   int32_t inputHeight = ShapedType::kDynamicSize;
1502   int32_t weightWidth = ShapedType::kDynamicSize;
1503   int32_t weightHeight = ShapedType::kDynamicSize;
1504 
1505   // Input shape describes input width/height and batch.
1506   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1507   if (inputShape.hasRank()) {
1508     outputShape[0] = ShapedType::isDynamic(outputShape[0])
1509                          ? inputShape.getDimSize(0)
1510                          : outputShape[0];
1511     inputHeight = inputShape.getDimSize(1);
1512     inputWidth = inputShape.getDimSize(2);
1513   }
1514 
1515   // Weight shapes describes the filter width/height and the output channels.
1516   ShapeAdaptor weightShape = operands.getShape(adaptor.input());
1517   if (weightShape.hasRank()) {
1518     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1519                          ? weightShape.getDimSize(0)
1520                          : outputShape[3];
1521     weightHeight = weightShape.getDimSize(1);
1522     weightWidth = weightShape.getDimSize(2);
1523   }
1524 
1525   // Bias shape can describe the output channels.
1526   ShapeAdaptor biasShape = operands.getShape(adaptor.input());
1527   if (biasShape.hasRank()) {
1528     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1529                          ? biasShape.getDimSize(0)
1530                          : outputShape[3];
1531   }
1532 
1533   llvm::SmallVector<int64_t> dilation;
1534   llvm::SmallVector<int64_t> padding;
1535   llvm::SmallVector<int64_t> stride;
1536 
1537   getI64Values(adaptor.dilation(), dilation);
1538   getI64Values(adaptor.out_pad(), padding);
1539   getI64Values(adaptor.stride(), stride);
1540 
1541   if (!ShapedType::isDynamic(inputHeight) &&
1542       !ShapedType::isDynamic(weightHeight)) {
1543     int32_t dilated = (weightHeight - 1) * dilation[0] + 1;
1544     int32_t calculateSize =
1545         (inputHeight - 1) * stride[0] - padding[0] + dilated;
1546     outputShape[1] = outputShape[1] == -1 ? calculateSize : outputShape[1];
1547   }
1548 
1549   if (!ShapedType::isDynamic(inputWidth) &&
1550       !ShapedType::isDynamic(weightWidth)) {
1551     int32_t dilated = (weightWidth - 1) * dilation[1] + 1;
1552     int32_t calculateSize = (inputWidth - 1) * stride[1] - padding[1] + dilated;
1553     outputShape[2] = outputShape[2] == -1 ? calculateSize : outputShape[2];
1554   }
1555 
1556   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1557   return success();
1558 }
1559 
1560 LogicalResult IfOp::inferReturnTypeComponents(
1561     MLIRContext *context, ::llvm::Optional<Location> location,
1562     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1563     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1564   llvm::SmallVector<tosa::YieldOp> yieldOps;
1565   for (Region *region : regions) {
1566     for (auto &block : *region)
1567       if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
1568         yieldOps.push_back(returnOp);
1569   }
1570 
1571   if (yieldOps.empty())
1572     return failure();
1573 
1574   // Get the initial type information for the yield op.
1575   llvm::SmallVector<ValueKnowledge> resultKnowledge;
1576   resultKnowledge.reserve(yieldOps.front().getNumOperands());
1577   for (auto operand : yieldOps.front().getOperands()) {
1578     resultKnowledge.push_back(
1579         ValueKnowledge::getKnowledgeFromType(operand.getType()));
1580   }
1581 
1582   for (auto yieldOp : yieldOps) {
1583     if (resultKnowledge.size() != yieldOp.getNumOperands())
1584       return failure();
1585 
1586     for (auto it : llvm::enumerate(yieldOp.getOperands())) {
1587       int32_t index = it.index();
1588       auto meet = ValueKnowledge::meet(
1589           resultKnowledge[index],
1590           ValueKnowledge::getKnowledgeFromType(it.value().getType()));
1591       if (!meet)
1592         continue;
1593       resultKnowledge[index] = meet;
1594     }
1595   }
1596 
1597   for (const ValueKnowledge &result : resultKnowledge) {
1598     inferredReturnShapes.push_back(result.getShapedTypeComponents());
1599   }
1600 
1601   return success();
1602 }
1603 
1604 LogicalResult WhileOp::inferReturnTypeComponents(
1605     MLIRContext *context, ::llvm::Optional<Location> location,
1606     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1607     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1608   llvm::SmallVector<tosa::YieldOp> yieldOps;
1609   for (auto &block : *regions[1])
1610     if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
1611       yieldOps.push_back(returnOp);
1612 
1613   // TOSA's while must have a tosa.yield as its terminator. If not found this
1614   // tosa.while is invalid.
1615   if (yieldOps.empty())
1616     return failure();
1617 
1618   // Get the initial type information from the operand types.
1619   llvm::SmallVector<ValueKnowledge> resultKnowledge;
1620   resultKnowledge.reserve(yieldOps.front().getNumOperands());
1621   for (auto operand : yieldOps.front().getOperands()) {
1622     resultKnowledge.push_back(
1623         ValueKnowledge::getKnowledgeFromType(operand.getType()));
1624   }
1625 
1626   for (auto yieldOp : yieldOps) {
1627     if (resultKnowledge.size() != yieldOp.getNumOperands())
1628       return failure();
1629 
1630     for (auto it : llvm::enumerate(yieldOp.getOperands())) {
1631       int32_t index = it.index();
1632       if (auto meet = ValueKnowledge::meet(
1633               resultKnowledge[index],
1634               ValueKnowledge::getKnowledgeFromType(it.value().getType()))) {
1635         resultKnowledge[index] = meet;
1636       };
1637     }
1638   }
1639 
1640   for (const ValueKnowledge &result : resultKnowledge) {
1641     inferredReturnShapes.push_back(result.getShapedTypeComponents());
1642   }
1643 
1644   return success();
1645 }
1646 
1647 //===----------------------------------------------------------------------===//
1648 // TOSA Operator Definitions.
1649 //===----------------------------------------------------------------------===//
1650 
1651 #define GET_OP_CLASSES
1652 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
1653