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/Tosa/Utils/QuantUtils.h"
18 #include "mlir/IR/StandardTypes.h"
19 #include "mlir/Transforms/FoldUtils.h"
20 #include "mlir/Transforms/InliningUtils.h"
21 #include "mlir/Transforms/RegionUtils.h"
22 
23 using namespace mlir;
24 using namespace mlir::tosa;
25 
26 //===----------------------------------------------------------------------===//
27 // Tosa dialect structs and interface includes.
28 //===----------------------------------------------------------------------===//
29 #include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
30 #include "mlir/Dialect/Tosa/IR/TosaStructs.cpp.inc"
31 
32 namespace {
33 //===----------------------------------------------------------------------===//
34 // Dialect Function Inliner Interface.
35 //===----------------------------------------------------------------------===//
36 struct TosaInlinerInterface : public DialectInlinerInterface {
37   using DialectInlinerInterface::DialectInlinerInterface;
38 
39   //===--------------------------------------------------------------------===//
40   // Analysis Hooks.
41   //===--------------------------------------------------------------------===//
42 
43   /// All operations can be inlined by default.
44   bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
45                        BlockAndValueMapping &map) const final {
46     return true;
47   }
48 
49   /// All regions with If and While parent operators can be inlined.
50   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
51                        BlockAndValueMapping &map) const final {
52     return (isa<tosa::IfOp>(dest->getParentOp()) ||
53             isa<tosa::WhileOp>(dest->getParentOp()));
54   }
55 };
56 } // end anonymous namespace
57 
58 //===----------------------------------------------------------------------===//
59 // TOSA control flow support.
60 //===----------------------------------------------------------------------===//
61 
62 /// Returns the while loop body.
63 Region &tosa::WhileOp::getLoopBody() { return body(); }
64 
65 bool tosa::WhileOp::isDefinedOutsideOfLoop(Value value) {
66   return !body().isAncestor(value.getParentRegion());
67 }
68 
69 LogicalResult WhileOp::moveOutOfLoop(ArrayRef<mlir::Operation *> ops) {
70   if (ops.empty())
71     return success();
72 
73   Operation *tosaWhileOp = this->getOperation();
74   for (auto *op : ops)
75     op->moveBefore(tosaWhileOp);
76 
77   return success();
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // Tosa dialect initialization.
82 //===----------------------------------------------------------------------===//
83 
84 void TosaDialect::initialize() {
85   addOperations<
86 #define GET_OP_LIST
87 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
88       >();
89   addInterfaces<TosaInlinerInterface>();
90 }
91 
92 //===----------------------------------------------------------------------===//
93 // TOSA Operator Verifiers.
94 //===----------------------------------------------------------------------===//
95 
96 template <typename T>
97 static LogicalResult verifyConvOp(T op) {
98   // All TOSA conv ops have an input() and weight().
99   auto inputType = op.input().getType().template dyn_cast<RankedTensorType>();
100   auto weightType = op.weight().getType().template dyn_cast<RankedTensorType>();
101 
102   // Must be ranked tensor types
103   if (!inputType || !weightType)
104     return failure();
105 
106   auto inputQType =
107       inputType.getElementType().template isa<mlir::quant::QuantizedType>();
108   auto weightQType =
109       weightType.getElementType().template isa<mlir::quant::QuantizedType>();
110 
111   // Either both must be quantized or both unquantized.
112   if (inputQType != weightQType)
113     return failure();
114 
115   // Quantized type must have constructed the quantizationattr, and unquantized
116   // types should not have a quantizationattr.
117   if ((inputQType && !op.quantization_info()) ||
118       (!inputQType && op.quantization_info()))
119     return failure();
120 
121   return success();
122 }
123 
124 //===----------------------------------------------------------------------===//
125 // TOSA Operator Quantization Builders.
126 //===----------------------------------------------------------------------===//
127 
128 /// This builder is called on all convolution operators except TransposeConv,
129 /// which has specialized output shape semantics. The builder also defines the
130 /// bitwidth of the output given the bit width of the input & weight content.
131 static void buildConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
132                                      Type outputType, Value input, Value weight,
133                                      Value bias, ArrayAttr pad,
134                                      ArrayAttr stride, ArrayAttr dilation) {
135 
136   result.addOperands({input, weight, bias});
137   result.addAttribute("pad", pad);
138   result.addAttribute("stride", stride);
139   result.addAttribute("dilation", dilation);
140 
141   auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
142   if (quantAttr) {
143     result.addAttribute("quantization_info", quantAttr);
144     result.addTypes(
145         buildConvOpResultTypeInfo(builder, outputType, input, weight));
146   } else {
147     result.addTypes(outputType);
148   }
149 }
150 
151 /// Handles tosa.transpose_conv2d which has outpad and output shape attributes.
152 static void
153 buildTransConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
154                               Type outputType, Value input, Value weight,
155                               Value bias, ArrayAttr outpad, ArrayAttr stride,
156                               ArrayAttr dilation, ArrayAttr outputShape) {
157   result.addOperands({input, weight, bias});
158   result.addAttribute("out_pad", outpad);
159   result.addAttribute("stride", stride);
160   result.addAttribute("dilation", dilation);
161   result.addAttribute("out_shape", outputShape);
162   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
163 
164   if (quantAttr) {
165     result.addAttribute("quantization_info", quantAttr);
166     result.addTypes(
167         buildConvOpResultTypeInfo(builder, outputType, input, weight));
168   } else {
169     result.addTypes(outputType);
170   }
171 }
172 
173 /// The tosa.fully_connected op has its own builder as it does not have
174 /// strides/dilation/padding.
175 static void buildFCOpWithQuantInfo(OpBuilder &builder, OperationState &result,
176                                    Type outputType, Value input, Value weight,
177                                    Value bias) {
178 
179   result.addOperands({input, weight, bias});
180   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
181   if (quantAttr) {
182     result.addAttribute("quantization_info", quantAttr);
183     result.addTypes(
184         buildConvOpResultTypeInfo(builder, outputType, input, weight));
185   } else {
186     result.addTypes(outputType);
187   }
188 }
189 
190 /// The tosa.matmul op is also intended to be generated where a fully_connected
191 /// op must be constructed where the weight is not a constant. In this case,
192 /// the fully_connected op must be expressed using matmul.
193 /// TODO: Add link to the leglization document explaining this.
194 static void buildMatMulOpWithQuantInfo(OpBuilder &builder,
195                                        OperationState &result, Type outputType,
196                                        Value a, Value b) {
197   result.addOperands({a, b});
198   auto quantAttr = ::buildMatMulOpQuantizationAttr(builder, a, b);
199 
200   if (quantAttr) {
201     result.addAttribute("quantization_info", quantAttr);
202 
203     auto inputType = a.getType().dyn_cast<RankedTensorType>();
204     assert(inputType && "Input must be a ranked tensor type!");
205 
206     auto inputQType = inputType.getElementType()
207                           .dyn_cast<mlir::quant::UniformQuantizedType>();
208     assert(inputQType && "Tensor must have quantized datatype!");
209 
210     unsigned inputBits = inputQType.getStorageTypeIntegralWidth();
211 
212     auto outputShapedType = outputType.dyn_cast<RankedTensorType>();
213     assert(outputShapedType && "Output must be a ranked tensor type");
214 
215     auto outputShape = outputShapedType.getShape();
216 
217     IntegerType accElementType;
218     if (inputBits == 16)
219       accElementType = builder.getIntegerType(48);
220     else
221       accElementType = builder.getI32Type();
222     auto accType = RankedTensorType::get(outputShape, accElementType);
223     result.addTypes(accType);
224   } else {
225     result.addTypes(outputType);
226   }
227 }
228 
229 /// Both the tosa.avg_pool2d and unary ops use the same UnaruOpQuantizationAttr
230 /// but avg_pool operator has its own builder as it has additional parameters
231 /// not part of the unary ops.
232 static void buildAvgPool2dOpWithQuantInfo(OpBuilder &builder,
233                                           OperationState &result,
234                                           Type outputType, Value input,
235                                           ArrayAttr kernel, ArrayAttr stride,
236                                           ArrayAttr pad) {
237   result.addOperands(input);
238   result.addAttribute("kernel", kernel);
239   result.addAttribute("stride", stride);
240   result.addAttribute("pad", pad);
241   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
242   if (quantAttr)
243     result.addAttribute("quantization_info", quantAttr);
244   result.types.push_back(outputType);
245 }
246 
247 /// This builder is called on single-parameter unary operators that have scale
248 /// relationship between their input and output, expressed by the
249 /// UnaryOpQuantizationAttr.
250 static void buildUnaryOpWithQuantInfo(OpBuilder &builder,
251                                       OperationState &result, Type outputType,
252                                       Value input) {
253   result.addOperands(input);
254   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
255   if (quantAttr)
256     result.addAttribute("quantization_info", quantAttr);
257   result.types.push_back(outputType);
258 }
259 
260 /// This builder is called on TOSA pad operator that needs to create its own
261 /// OptionalAttr quantization_attr parameter to scale the padding values
262 /// correctly.
263 static void buildPadOpWithQuantInfo(OpBuilder &builder, OperationState &result,
264                                     Type outputType, Value input,
265                                     Value paddings) {
266   result.addOperands({input, paddings});
267   auto quantAttr = buildPadOpQuantizationAttr(builder, input);
268   if (quantAttr)
269     result.addAttribute("quantization_info", quantAttr);
270   result.types.push_back(outputType);
271 }
272 
273 //===----------------------------------------------------------------------===//
274 // TOSA Operator Definitions.
275 //===----------------------------------------------------------------------===//
276 
277 #define GET_OP_CLASSES
278 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
279