1 //===- LinalgOps.cpp - Implementation of the linalg operations ------------===//
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 // This file implements the Linalg operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Linalg/IR/Linalg.h"
14 
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
17 #include "mlir/Dialect/Arithmetic/Utils/Utils.h"
18 #include "mlir/Dialect/Complex/IR/Complex.h"
19 #include "mlir/Dialect/Math/IR/Math.h"
20 #include "mlir/Dialect/MemRef/IR/MemRef.h"
21 #include "mlir/Dialect/SCF/SCF.h"
22 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
23 #include "mlir/Dialect/Tensor/IR/Tensor.h"
24 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
25 #include "mlir/Dialect/Utils/StaticValueUtils.h"
26 #include "mlir/IR/AffineExprVisitor.h"
27 #include "mlir/IR/AffineMap.h"
28 #include "mlir/IR/Matchers.h"
29 #include "mlir/IR/OpImplementation.h"
30 #include "mlir/IR/PatternMatch.h"
31 #include "mlir/Interfaces/InferTypeOpInterface.h"
32 #include "mlir/Parser/Parser.h"
33 
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/StringSet.h"
38 #include "llvm/ADT/TypeSwitch.h"
39 #include "llvm/Support/FormatVariadic.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 
43 using namespace mlir;
44 using namespace mlir::linalg;
45 
46 //===----------------------------------------------------------------------===//
47 // Support for named Linalg ops defined in ods-gen.
48 //===----------------------------------------------------------------------===//
49 
50 using RegionBuilderFn = llvm::function_ref<void(ImplicitLocOpBuilder &, Block &,
51                                                 ArrayRef<NamedAttribute>)>;
52 
53 /// Fills the region of a structured operation using the provided
54 /// `regionBuilder`. The method is used by both named structured ops created by
55 /// ods-gen and by manually defined C++ ops. It is called by both builders and
56 /// parsers and creates a block with arguments corresponding to the elemental
57 /// types of `inputTypes` and `outputTypes`. All output types are asserted to be
58 /// ShapedType.
59 static void fillStructuredOpRegion(OpBuilder &opBuilder, Region &region,
60                                    TypeRange inputTypes, TypeRange outputTypes,
61                                    ArrayRef<NamedAttribute> attrs,
62                                    RegionBuilderFn regionBuilder) {
63   assert(llvm::all_of(outputTypes, [](Type t) { return t.isa<ShapedType>(); }));
64 
65   // TODO: atm all operands go through getElementTypeOrSelf,
66   // reconsider when we have evidence we need to.
67   SmallVector<Type, 8> argTypes;
68   SmallVector<Location, 8> argLocs;
69   for (auto containers : {inputTypes, outputTypes}) {
70     for (auto t : containers) {
71       argTypes.push_back(getElementTypeOrSelf(t));
72 
73       // TODO: Pass in a proper location here.
74       argLocs.push_back(opBuilder.getUnknownLoc());
75     }
76   }
77 
78   // RAII.
79   OpBuilder::InsertionGuard guard(opBuilder);
80   Block *body =
81       opBuilder.createBlock(&region, /*insertPt=*/{}, argTypes, argLocs);
82 
83   opBuilder.setInsertionPointToStart(body);
84   ImplicitLocOpBuilder b(opBuilder.getUnknownLoc(), opBuilder);
85   regionBuilder(b, *body, attrs);
86 
87   // indexing_maps is an auto-generated method.
88 
89   // iterator_types is an auto-generated method.
90 }
91 
92 /// Creates a structured operation given `inputs`, `outputs`, and `attributes`.
93 /// The result types are derived automatically if `resultTensorTypes` is none.
94 /// The body of the operation is filled using `regionBuilder`. All ods-gen
95 /// created structured operations use the method to implement their builders.
96 static void buildStructuredOp(OpBuilder &b, OperationState &state,
97                               llvm::Optional<TypeRange> resultTensorTypes,
98                               ValueRange inputs, ValueRange outputs,
99                               ArrayRef<NamedAttribute> attributes,
100                               RegionBuilderFn regionBuilder) {
101   // Derive the result types if needed.
102   SmallVector<Type> derivedResultTypes =
103       resultTensorTypes.getValueOr(TypeRange());
104   if (!resultTensorTypes.hasValue())
105     copy_if(outputs.getTypes(), std::back_inserter(derivedResultTypes),
106             [](Type type) { return type.isa<RankedTensorType>(); });
107 
108   state.addOperands(inputs);
109   state.addOperands(outputs);
110   state.addTypes(derivedResultTypes);
111   state.addAttributes(attributes);
112   state.addAttribute(
113       "operand_segment_sizes",
114       b.getI32VectorAttr({static_cast<int32_t>(inputs.size()),
115                           static_cast<int32_t>(outputs.size())}));
116 
117   // Create and fill the region of the structured operation.
118   Region &region = *state.addRegion();
119   fillStructuredOpRegion(b, region, TypeRange(inputs), TypeRange(outputs),
120                          state.attributes.getAttrs(), regionBuilder);
121 }
122 
123 /// Common parsing used for both named structured ops created by ods-gen and by
124 /// manually defined C++ ops. Does not handle regions.
125 static ParseResult
126 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
127                              SmallVectorImpl<Type> &inputTypes,
128                              SmallVectorImpl<Type> &outputTypes) {
129   SMLoc inputsOperandsLoc, outputsOperandsLoc;
130   SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands,
131       outputsOperands;
132 
133   if (parser.parseOptionalAttrDict(result.attributes))
134     return failure();
135 
136   if (succeeded(parser.parseOptionalKeyword("ins"))) {
137     if (parser.parseLParen())
138       return failure();
139 
140     inputsOperandsLoc = parser.getCurrentLocation();
141     if (parser.parseOperandList(inputsOperands) ||
142         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
143       return failure();
144   }
145 
146   if (succeeded(parser.parseOptionalKeyword("outs"))) {
147     outputsOperandsLoc = parser.getCurrentLocation();
148     if (parser.parseLParen() || parser.parseOperandList(outputsOperands) ||
149         parser.parseColonTypeList(outputTypes) || parser.parseRParen())
150       return failure();
151   }
152 
153   if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
154                              result.operands) ||
155       parser.resolveOperands(outputsOperands, outputTypes, outputsOperandsLoc,
156                              result.operands))
157     return failure();
158 
159   result.addAttribute("operand_segment_sizes",
160                       parser.getBuilder().getI32VectorAttr(
161                           {static_cast<int32_t>(inputsOperands.size()),
162                            static_cast<int32_t>(outputsOperands.size())}));
163   return success();
164 }
165 
166 static void printCommonStructuredOpParts(OpAsmPrinter &p, ValueRange inputs,
167                                          ValueRange outputs) {
168   if (!inputs.empty())
169     p << " ins(" << inputs << " : " << inputs.getTypes() << ")";
170   if (!outputs.empty())
171     p << " outs(" << outputs << " : " << outputs.getTypes() << ")";
172 }
173 
174 //===----------------------------------------------------------------------===//
175 // Specific parsing and printing for named structured ops created by ods-gen.
176 //===----------------------------------------------------------------------===//
177 
178 static ParseResult parseNamedStructuredOpRegion(
179     OpAsmParser &parser, Region &region, unsigned numRegionArgs,
180     TypeRange inputTypes, TypeRange outputTypes, ArrayRef<NamedAttribute> attrs,
181     RegionBuilderFn regionBuilder) {
182   if (numRegionArgs != inputTypes.size() + outputTypes.size()) {
183     return parser.emitError(
184         parser.getCurrentLocation(),
185         llvm::formatv("[parseNamedStructuredOpRegion] ods-gen generated "
186                       "region expects {0} args, got {1}",
187                       numRegionArgs, inputTypes.size() + outputTypes.size()));
188   }
189 
190   OpBuilder opBuilder(parser.getContext());
191   fillStructuredOpRegion(opBuilder, region, inputTypes, outputTypes, attrs,
192                          regionBuilder);
193   return success();
194 }
195 
196 static ParseResult
197 parseNamedStructuredOpResults(OpAsmParser &parser,
198                               SmallVectorImpl<Type> &resultTypes) {
199   if (parser.parseOptionalArrowTypeList(resultTypes))
200     return failure();
201   return success();
202 }
203 
204 static ParseResult parseNamedStructuredOp(OpAsmParser &parser,
205                                           OperationState &result,
206                                           unsigned numRegionArgs,
207                                           RegionBuilderFn regionBuilder) {
208   // TODO: Enable when ods-gen supports captures.
209   SmallVector<Type, 1> inputTypes, outputTypes;
210   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
211     return failure();
212 
213   // TODO: consider merging results parsing into region parsing.
214   // Need to wait for declarative assembly resolution to decide.
215   SmallVector<Type, 1> outputTensorsTypes;
216   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
217     return failure();
218   result.addTypes(outputTensorsTypes);
219 
220   std::unique_ptr<Region> region = std::make_unique<Region>();
221   if (parseNamedStructuredOpRegion(parser, *region, numRegionArgs, inputTypes,
222                                    outputTypes, result.attributes.getAttrs(),
223                                    regionBuilder))
224     return failure();
225   result.addRegion(std::move(region));
226 
227   return success();
228 }
229 
230 static void printNamedStructuredOpResults(OpAsmPrinter &p,
231                                           TypeRange resultTypes) {
232   if (resultTypes.empty())
233     return;
234   p.printOptionalArrowTypeList(resultTypes);
235 }
236 
237 static void printNamedStructuredOp(OpAsmPrinter &p, Operation *op,
238                                    ValueRange inputs, ValueRange outputs) {
239   p.printOptionalAttrDict(
240       op->getAttrs(),
241       /*elidedAttrs=*/{"operand_segment_sizes",
242                        // See generated code in mlir-linalg-yaml-gen.cpp
243                        "linalg.memoized_indexing_maps"});
244 
245   // Printing is shared with generic ops, except for the region and
246   // attributes.
247   printCommonStructuredOpParts(p, inputs, outputs);
248 
249   // Results printing.
250   printNamedStructuredOpResults(p, op->getResultTypes());
251 
252   // Region is elided.
253 }
254 
255 /// This is a common class used for patterns of the form
256 /// ```
257 ///    someop(memrefcast(%src)) -> someop(%src)
258 /// ```
259 /// It folds the source of the memref.cast into the root operation directly.
260 static LogicalResult foldMemRefCast(Operation *op) {
261   bool folded = false;
262   for (OpOperand &operand : op->getOpOperands()) {
263     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
264     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
265       operand.set(castOp.getOperand());
266       folded = true;
267     }
268   }
269   return success(folded);
270 }
271 
272 //===----------------------------------------------------------------------===//
273 // Region builder helper.
274 // TODO: Move this to a utility library.
275 // The public methods on this class are referenced directly from generated code.
276 // Helper build the unary, binary, and type conversion functions defined by the
277 // DSL. See mlir-linalg-ods-yaml-gen.cpp for the code that uses this class.
278 //
279 // Implementations of the math functions must be polymorphic over numeric types,
280 // internally performing necessary casts. If the function application makes no
281 // sense, then the only recourse is to assert and return nullptr. This can be
282 // extended later if it becomes possible to fail construction of the region. The
283 // invariant should be enforced at a higher level.
284 //
285 // TODO: These helpers are currently type polymorphic over the class of integer
286 // and floating point types, but they will not internally cast within bit
287 // widths of a class (mixed precision such as i8->i32) or across classes
288 // (i.e. mixed float and integer). Many such combinations are ambiguous or need
289 // to be handled with care and work is being considered to extend the op
290 // language to make such cases explicit. In the mean-time, violating this will
291 // fail verification, which is deemed acceptable.
292 //===----------------------------------------------------------------------===//
293 
294 namespace {
295 
296 class RegionBuilderHelper {
297 public:
298   RegionBuilderHelper(MLIRContext *context, Block &block)
299       : context(context), block(block) {}
300 
301   // Build the unary functions defined by OpDSL.
302   Value buildUnaryFn(UnaryFn unaryFn, Value arg) {
303     if (!isFloatingPoint(arg))
304       llvm_unreachable("unsupported non numeric type");
305     OpBuilder builder = getBuilder();
306     switch (unaryFn) {
307     case UnaryFn::exp:
308       return builder.create<math::ExpOp>(arg.getLoc(), arg);
309     case UnaryFn::log:
310       return builder.create<math::LogOp>(arg.getLoc(), arg);
311     case UnaryFn::abs:
312       return builder.create<math::AbsOp>(arg.getLoc(), arg);
313     case UnaryFn::ceil:
314       return builder.create<math::CeilOp>(arg.getLoc(), arg);
315     case UnaryFn::floor:
316       return builder.create<math::FloorOp>(arg.getLoc(), arg);
317     case UnaryFn::negf:
318       return builder.create<arith::NegFOp>(arg.getLoc(), arg);
319     }
320     llvm_unreachable("unsupported unary function");
321   }
322 
323   // Build the binary functions defined by OpDSL.
324   Value buildBinaryFn(BinaryFn binaryFn, Value arg0, Value arg1) {
325     bool allComplex = isComplex(arg0) && isComplex(arg1);
326     bool allFloatingPoint = isFloatingPoint(arg0) && isFloatingPoint(arg1);
327     bool allInteger = isInteger(arg0) && isInteger(arg1);
328     if (!allComplex && !allFloatingPoint && !allInteger)
329       llvm_unreachable("unsupported non numeric type");
330     OpBuilder builder = getBuilder();
331     switch (binaryFn) {
332     case BinaryFn::add:
333       if (allComplex)
334         return builder.create<complex::AddOp>(arg0.getLoc(), arg0, arg1);
335       if (allFloatingPoint)
336         return builder.create<arith::AddFOp>(arg0.getLoc(), arg0, arg1);
337       return builder.create<arith::AddIOp>(arg0.getLoc(), arg0, arg1);
338     case BinaryFn::sub:
339       if (allComplex)
340         return builder.create<complex::SubOp>(arg0.getLoc(), arg0, arg1);
341       if (allFloatingPoint)
342         return builder.create<arith::SubFOp>(arg0.getLoc(), arg0, arg1);
343       return builder.create<arith::SubIOp>(arg0.getLoc(), arg0, arg1);
344     case BinaryFn::mul:
345       if (allComplex)
346         return builder.create<complex::MulOp>(arg0.getLoc(), arg0, arg1);
347       if (allFloatingPoint)
348         return builder.create<arith::MulFOp>(arg0.getLoc(), arg0, arg1);
349       return builder.create<arith::MulIOp>(arg0.getLoc(), arg0, arg1);
350     case BinaryFn::max_signed:
351       assert(!allComplex);
352       if (allFloatingPoint)
353         return builder.create<arith::MaxFOp>(arg0.getLoc(), arg0, arg1);
354       return builder.create<arith::MaxSIOp>(arg0.getLoc(), arg0, arg1);
355     case BinaryFn::min_signed:
356       assert(!allComplex);
357       if (allFloatingPoint)
358         return builder.create<arith::MinFOp>(arg0.getLoc(), arg0, arg1);
359       return builder.create<arith::MinSIOp>(arg0.getLoc(), arg0, arg1);
360     case BinaryFn::max_unsigned:
361       assert(!allComplex);
362       if (allFloatingPoint)
363         return builder.create<arith::MaxFOp>(arg0.getLoc(), arg0, arg1);
364       return builder.create<arith::MaxUIOp>(arg0.getLoc(), arg0, arg1);
365     case BinaryFn::min_unsigned:
366       assert(!allComplex);
367       if (allFloatingPoint)
368         return builder.create<arith::MinFOp>(arg0.getLoc(), arg0, arg1);
369       return builder.create<arith::MinUIOp>(arg0.getLoc(), arg0, arg1);
370     }
371     llvm_unreachable("unsupported binary function");
372   }
373 
374   // Build the type functions defined by OpDSL.
375   Value buildTypeFn(TypeFn typeFn, Type toType, Value operand) {
376     switch (typeFn) {
377     case TypeFn::cast_signed:
378       return cast(toType, operand, false);
379     case TypeFn::cast_unsigned:
380       return cast(toType, operand, true);
381     }
382     llvm_unreachable("unsupported type conversion function");
383   }
384 
385   void yieldOutputs(ValueRange values) {
386     OpBuilder builder = getBuilder();
387     Location loc = builder.getUnknownLoc();
388     builder.create<YieldOp>(loc, values);
389   }
390 
391   Value constant(const std::string &value) {
392     OpBuilder builder = getBuilder();
393     Location loc = builder.getUnknownLoc();
394     Attribute valueAttr = parseAttribute(value, builder.getContext());
395     return builder.create<arith::ConstantOp>(loc, valueAttr.getType(),
396                                              valueAttr);
397   }
398 
399   Value index(int64_t dim) {
400     OpBuilder builder = getBuilder();
401     return builder.create<IndexOp>(builder.getUnknownLoc(), dim);
402   }
403 
404   Type getIntegerType(unsigned width) {
405     return IntegerType::get(context, width);
406   }
407 
408   Type getFloat32Type() { return Float32Type::get(context); }
409   Type getFloat64Type() { return Float64Type::get(context); }
410 
411 private:
412   // Generates operations to cast the given operand to a specified type.
413   // If the cast cannot be performed, a warning will be issued and the
414   // operand returned as-is (which will presumably yield a verification
415   // issue downstream).
416   Value cast(Type toType, Value operand, bool isUnsignedCast) {
417     OpBuilder builder = getBuilder();
418     auto loc = operand.getLoc();
419 
420     if (operand.getType() == toType)
421       return operand;
422     if (auto toIntType = toType.dyn_cast<IntegerType>()) {
423       // If operand is floating point, cast directly to the int type.
424       if (operand.getType().isa<FloatType>()) {
425         if (isUnsignedCast)
426           return builder.create<arith::FPToUIOp>(loc, toType, operand);
427         return builder.create<arith::FPToSIOp>(loc, toType, operand);
428       }
429       // Cast index operands directly to the int type.
430       if (operand.getType().isIndex())
431         return builder.create<arith::IndexCastOp>(loc, toType, operand);
432       if (auto fromIntType = operand.getType().dyn_cast<IntegerType>()) {
433         // Either extend or truncate.
434         if (toIntType.getWidth() > fromIntType.getWidth()) {
435           if (isUnsignedCast)
436             return builder.create<arith::ExtUIOp>(loc, toType, operand);
437           return builder.create<arith::ExtSIOp>(loc, toType, operand);
438         }
439         if (toIntType.getWidth() < fromIntType.getWidth())
440           return builder.create<arith::TruncIOp>(loc, toType, operand);
441       }
442     } else if (auto toFloatType = toType.dyn_cast<FloatType>()) {
443       // If operand is integer, cast directly to the float type.
444       // Note that it is unclear how to cast from BF16<->FP16.
445       if (operand.getType().isa<IntegerType>()) {
446         if (isUnsignedCast)
447           return builder.create<arith::UIToFPOp>(loc, toFloatType, operand);
448         return builder.create<arith::SIToFPOp>(loc, toFloatType, operand);
449       }
450       if (auto fromFloatType = operand.getType().dyn_cast<FloatType>()) {
451         if (toFloatType.getWidth() > fromFloatType.getWidth())
452           return builder.create<arith::ExtFOp>(loc, toFloatType, operand);
453         if (toFloatType.getWidth() < fromFloatType.getWidth())
454           return builder.create<arith::TruncFOp>(loc, toFloatType, operand);
455       }
456     }
457 
458     emitWarning(operand.getLoc()) << "could not cast operand of type "
459                                   << operand.getType() << " to " << toType;
460     return operand;
461   }
462 
463   bool isComplex(Value value) { return value.getType().isa<ComplexType>(); }
464   bool isFloatingPoint(Value value) { return value.getType().isa<FloatType>(); }
465   bool isInteger(Value value) { return value.getType().isa<IntegerType>(); }
466 
467   OpBuilder getBuilder() {
468     OpBuilder builder(context);
469     builder.setInsertionPointToEnd(&block);
470     return builder;
471   }
472 
473   MLIRContext *context;
474   Block &block;
475 };
476 
477 } // namespace
478 
479 //===----------------------------------------------------------------------===//
480 // FillOp
481 //===----------------------------------------------------------------------===//
482 
483 namespace {
484 
485 /// Fold linalg.fill -> tensor.expand/collapse_shape chain.
486 ///
487 /// For such op chains, we can create new linalg.fill ops with the result
488 /// type of the tensor.expand/collapse_shape op.
489 template <typename TensorReshapeOp>
490 struct FoldFillWithTensorReshape : OpRewritePattern<TensorReshapeOp> {
491   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
492   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
493                                 PatternRewriter &rewriter) const override {
494     auto oldFill = reshapeOp.src().template getDefiningOp<FillOp>();
495     if (!oldFill)
496       return failure();
497 
498     Location loc = oldFill.getLoc();
499     auto newInit = rewriter.create<TensorReshapeOp>(
500         loc, reshapeOp.getResultType(), oldFill.output(),
501         reshapeOp.reassociation());
502     rewriter.replaceOpWithNewOp<FillOp>(reshapeOp, ValueRange{oldFill.value()},
503                                         ValueRange{newInit});
504 
505     return success();
506   }
507 };
508 
509 /// Fold tensor.pad(linalg.fill) into linalg.fill if the padding value and the
510 /// filling value are the same.
511 struct FoldFillWithPad final : public OpRewritePattern<tensor::PadOp> {
512   using OpRewritePattern::OpRewritePattern;
513 
514   LogicalResult matchAndRewrite(tensor::PadOp padOp,
515                                 PatternRewriter &rewriter) const override {
516     auto fillOp = padOp.source().getDefiningOp<linalg::FillOp>();
517     if (!fillOp)
518       return failure();
519 
520     // We can only fold if the padding value is the same as the original
521     // filling value.
522     Value padValue = padOp.getConstantPaddingValue();
523     if (!padValue || fillOp.value() != padValue)
524       return failure();
525 
526     ReifiedRankedShapedTypeDims reifiedShape;
527     ReifyRankedShapedTypeOpInterface interface =
528         cast<ReifyRankedShapedTypeOpInterface>(padOp.getOperation());
529     if (failed(interface.reifyResultShapes(rewriter, reifiedShape)))
530       return rewriter.notifyMatchFailure(
531           padOp, "failed to reify tensor.pad op result shape");
532 
533     auto oldResultType = padOp.getResultType();
534     SmallVector<int64_t, 4> staticShape(oldResultType.getRank(),
535                                         ShapedType::kDynamicSize);
536     auto newInitOp = rewriter.create<InitTensorOp>(
537         padOp.getLoc(), reifiedShape.front(), staticShape,
538         oldResultType.getElementType());
539     auto newFillOp = rewriter.create<FillOp>(
540         fillOp.getLoc(), ValueRange{padValue}, ValueRange{newInitOp});
541     rewriter.replaceOpWithNewOp<tensor::CastOp>(padOp, oldResultType,
542                                                 newFillOp.result());
543 
544     return success();
545   }
546 };
547 
548 /// Fold tensor.insert_slice(tensor.pad(<input>), linalg.fill) into
549 /// tensor.insert_slice(<input>, linalg.fill) if the padding value and the
550 /// filling value are the same.
551 struct FoldInsertPadIntoFill : public OpRewritePattern<tensor::InsertSliceOp> {
552   using OpRewritePattern::OpRewritePattern;
553 
554   LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
555                                 PatternRewriter &rewriter) const override {
556     auto srcPadOp = insertOp.source().getDefiningOp<tensor::PadOp>();
557     if (!srcPadOp)
558       return failure();
559 
560     if (insertOp.getType().getRank() != insertOp.getSourceType().getRank())
561       return failure();
562 
563     // Walk back the tensor.insert_slice chain and find the first destination
564     // value at the start of the chain.
565     Value firstDest = insertOp.dest();
566     while (auto prevOp = firstDest.getDefiningOp<tensor::InsertSliceOp>()) {
567       if (prevOp.getType().getRank() != prevOp.getSourceType().getRank())
568         return failure();
569 
570       // Make sure the range of values accessed are disjoint. Without this, we
571       // cannot fold tensor.pad away.
572       bool disjoint = false;
573       for (int i = 0, e = prevOp.getType().getRank(); i < e; ++i) {
574         // If the dimension has dynamic offset/size, we cannot guarantee
575         // disjoint. So just skip it.
576         if (insertOp.isDynamicOffset(i) || insertOp.isDynamicSize(i) ||
577             insertOp.isDynamicStride(i) || prevOp.isDynamicOffset(i) ||
578             prevOp.isDynamicSize(i) || prevOp.isDynamicStride(i))
579           continue;
580 
581         // Get the range start and end, inclusively for both.
582         int64_t prevStart = prevOp.getStaticOffset(i);
583         int64_t prevEnd = prevStart + (prevOp.getStaticSize(i) - 1) *
584                                           prevOp.getStaticStride(i);
585         int64_t nextStart = insertOp.getStaticOffset(i);
586         int64_t nextEnd = nextStart + (insertOp.getStaticSize(i) - 1) *
587                                           insertOp.getStaticStride(i);
588         if (prevEnd < nextStart || nextEnd < prevStart) {
589           disjoint = true;
590           break;
591         }
592       }
593 
594       if (!disjoint)
595         break;
596       firstDest = prevOp.dest();
597     }
598 
599     // Check whether the first destination is a fill op. For overlapped cases,
600     // this also cannot be true.
601     auto dstFillOp = firstDest.getDefiningOp<linalg::FillOp>();
602     if (!dstFillOp)
603       return failure();
604 
605     // We can only fold if the padding value is the same as the original
606     // filling value.
607     Value padValue = srcPadOp.getConstantPaddingValue();
608     if (!padValue || dstFillOp.value() != padValue)
609       return failure();
610 
611     SmallVector<OpFoldResult> lowPads = srcPadOp.getMixedLowPad();
612     SmallVector<OpFoldResult> oldOffsets = insertOp.getMixedOffsets();
613 
614     Location loc = insertOp.getLoc();
615     MLIRContext *context = getContext();
616 
617     AffineExpr sym0, sym1;
618     bindSymbols(context, sym0, sym1);
619     auto addMap = AffineMap::get(0, 2, {sym0 + sym1}, context);
620 
621     // Calculate the new offsets for the insert. It should be the old offsets
622     // plus low padding sizes.
623     SmallVector<OpFoldResult, 4> newOffsets;
624     for (const auto &p : llvm::zip(lowPads, oldOffsets)) {
625       Value padValue = getValueOrCreateConstantIndexOp(
626           rewriter, srcPadOp.getLoc(), std::get<0>(p));
627       Value offsetValue = getValueOrCreateConstantIndexOp(
628           rewriter, insertOp.getLoc(), std::get<1>(p));
629       newOffsets.push_back(
630           applyMapToValues(rewriter, loc, addMap, {offsetValue, padValue})[0]);
631     }
632 
633     SmallVector<OpFoldResult, 4> newSizes;
634     for (int i = 0, e = srcPadOp.getSourceType().getRank(); i < e; ++i) {
635       newSizes.push_back(
636           rewriter.create<tensor::DimOp>(loc, srcPadOp.source(), i).result());
637     }
638 
639     rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
640         insertOp, srcPadOp.source(), insertOp.dest(), newOffsets, newSizes,
641         insertOp.getMixedStrides());
642     return success();
643   }
644 };
645 
646 } // namespace
647 
648 void FillOp::getCanonicalizationPatterns(RewritePatternSet &results,
649                                          MLIRContext *context) {
650   results
651       .add<FoldFillWithPad, FoldFillWithTensorReshape<tensor::CollapseShapeOp>,
652            FoldFillWithTensorReshape<tensor::ExpandShapeOp>,
653            FoldInsertPadIntoFill>(context);
654 }
655 
656 //===----------------------------------------------------------------------===//
657 // GenericOps
658 //===----------------------------------------------------------------------===//
659 void GenericOp::build(
660     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
661     ValueRange inputs, ValueRange outputs, ArrayAttr indexingMaps,
662     ArrayAttr iteratorTypes, StringAttr doc, StringAttr libraryCall,
663     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
664     ArrayRef<NamedAttribute> attributes) {
665   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
666         iteratorTypes, doc, libraryCall);
667   result.addAttributes(attributes);
668   if (!bodyBuild)
669     return;
670 
671   SmallVector<Type, 4> blockArgTypes;
672   SmallVector<Location, 4> blockArgLocs;
673   for (ValueRange container : {inputs, outputs}) {
674     for (Value v : container) {
675       blockArgTypes.push_back(getElementTypeOrSelf(v));
676       blockArgLocs.push_back(v.getLoc());
677     }
678   }
679 
680   OpBuilder::InsertionGuard guard(builder);
681   auto &region = *result.regions.front();
682   Block *bodyBlock =
683       builder.createBlock(&region, region.end(), blockArgTypes, blockArgLocs);
684   bodyBuild(builder, result.location, bodyBlock->getArguments());
685 }
686 
687 void GenericOp::build(
688     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
689     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
690     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
691     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
692     ArrayRef<NamedAttribute> attributes) {
693   build(builder, result, resultTensorTypes, inputs, outputs,
694         builder.getAffineMapArrayAttr(indexingMaps),
695         builder.getStrArrayAttr(iteratorTypes),
696         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
697         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
698         bodyBuild, attributes);
699 }
700 
701 void GenericOp::build(
702     OpBuilder &builder, OperationState &result, ValueRange inputs,
703     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
704     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
705     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
706     ArrayRef<NamedAttribute> attributes) {
707   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
708         iteratorTypes, doc, libraryCall, bodyBuild, attributes);
709 }
710 
711 void GenericOp::build(
712     OpBuilder &builder, OperationState &result, ValueRange inputs,
713     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
714     ArrayRef<StringRef> iteratorTypes,
715     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
716     ArrayRef<NamedAttribute> attributes) {
717   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
718         /*doc=*/"",
719         /*libraryCall=*/"", bodyBuild, attributes);
720 }
721 
722 void GenericOp::build(
723     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
724     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
725     ArrayRef<StringRef> iteratorTypes,
726     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
727     ArrayRef<NamedAttribute> attributes) {
728   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
729         iteratorTypes,
730         /*doc=*/"",
731         /*libraryCall=*/"", bodyBuild, attributes);
732 }
733 
734 void GenericOp::print(OpAsmPrinter &p) {
735   p << " ";
736 
737   // Print extra attributes.
738   auto genericAttrNames = linalgTraitAttrNames();
739 
740   llvm::StringSet<> genericAttrNamesSet;
741   genericAttrNamesSet.insert(genericAttrNames.begin(), genericAttrNames.end());
742   SmallVector<NamedAttribute, 8> genericAttrs;
743   for (auto attr : (*this)->getAttrs())
744     if (genericAttrNamesSet.count(attr.getName().strref()) > 0)
745       genericAttrs.push_back(attr);
746   if (!genericAttrs.empty()) {
747     auto genericDictAttr = DictionaryAttr::get(getContext(), genericAttrs);
748     p << genericDictAttr;
749   }
750 
751   // Printing is shared with named ops, except for the region and attributes
752   printCommonStructuredOpParts(p, inputs(), outputs());
753 
754   genericAttrNames.push_back("operand_segment_sizes");
755   genericAttrNamesSet.insert(genericAttrNames.back());
756 
757   bool hasExtraAttrs = false;
758   for (NamedAttribute n : (*this)->getAttrs()) {
759     if ((hasExtraAttrs = !genericAttrNamesSet.contains(n.getName().strref())))
760       break;
761   }
762   if (hasExtraAttrs) {
763     p << " attrs = ";
764     p.printOptionalAttrDict((*this)->getAttrs(),
765                             /*elidedAttrs=*/genericAttrNames);
766   }
767 
768   // Print region.
769   if (!region().empty()) {
770     p << ' ';
771     p.printRegion(region());
772   }
773 
774   // Print results.
775   printNamedStructuredOpResults(p, result_tensors().getTypes());
776 }
777 
778 ParseResult GenericOp::parse(OpAsmParser &parser, OperationState &result) {
779   DictionaryAttr dictAttr;
780   // Parse the core linalg traits that must check into a dictAttr.
781   // The name is unimportant as we will overwrite result.attributes.
782   // The core linalg traits must contain the information necessary to pass the
783   // verifier.
784   if (parser.parseAttribute(dictAttr, "_", result.attributes))
785     return failure();
786   result.attributes.assign(dictAttr.getValue().begin(),
787                            dictAttr.getValue().end());
788 
789   // Parsing is shared with named ops, except for the region.
790   SmallVector<Type, 1> inputTypes, outputTypes;
791   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
792     return failure();
793 
794   // Optional attributes may be added.
795   if (succeeded(parser.parseOptionalKeyword("attrs")))
796     if (failed(parser.parseEqual()) ||
797         failed(parser.parseOptionalAttrDict(result.attributes)))
798       return failure();
799 
800   std::unique_ptr<Region> region = std::make_unique<Region>();
801   if (parser.parseRegion(*region, {}))
802     return failure();
803   result.addRegion(std::move(region));
804 
805   // Generic ops may specify that a subset of its outputs are tensors. Such
806   // outputs are specified in the result type.
807   // TODO: may need to move output parsing before region parsing.
808   // Need to wait for declarative assembly resolution to decide.
809   SmallVector<Type, 1> outputTensorsTypes;
810   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
811     return failure();
812   result.addTypes(outputTensorsTypes);
813 
814   return success();
815 }
816 
817 static void getGenericEffectsImpl(
818     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
819         &effects,
820     ValueRange results, ValueRange inputBuffers, ValueRange outputs) {
821   for (Value value : inputBuffers) {
822     effects.emplace_back(MemoryEffects::Read::get(), value,
823                          SideEffects::DefaultResource::get());
824   }
825   for (Value value : outputs) {
826     effects.emplace_back(MemoryEffects::Read::get(), value,
827                          SideEffects::DefaultResource::get());
828     effects.emplace_back(MemoryEffects::Write::get(), value,
829                          SideEffects::DefaultResource::get());
830   }
831 }
832 
833 void GenericOp::getEffects(
834     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
835         &effects) {
836   SmallVector<Value> inputBuffers = getInputBufferOperands();
837   SmallVector<Value> outputBuffers = getOutputBufferOperands();
838   getGenericEffectsImpl(effects, getOperation()->getResults(), inputBuffers,
839                         outputBuffers);
840 }
841 
842 LogicalResult GenericOp::verify() { return success(); }
843 
844 namespace {
845 
846 struct DeduplicateAndRemoveDeadOperandsAndResults
847     : public OpRewritePattern<GenericOp> {
848   using OpRewritePattern<GenericOp>::OpRewritePattern;
849 
850   LogicalResult matchAndRewrite(GenericOp genericOp,
851                                 PatternRewriter &rewriter) const override {
852     // Create a map from argument position in the original op to the argument
853     // position in the new op. If the argument is dropped it wont have an entry.
854     llvm::SmallDenseMap<unsigned, unsigned> origToNewPos;
855     unsigned numNewArgs = 0;
856     SmallVector<OpOperand *> droppedOpOperands;
857     llvm::SmallDenseSet<unsigned> droppedOutputs;
858 
859     // Information needed to build the new op.
860     SmallVector<Value> newInputOperands, newOutputOperands;
861     SmallVector<AffineMap> newIndexingMaps;
862     SmallVector<Type> newResultTypes;
863 
864     // Input argument can be dropped if
865     // - it has no uses, or,
866     // - there is a duplicate operand which is accessed using the same
867     //   indexing map.
868     llvm::SmallDenseMap<std::pair<Value, AffineMap>, unsigned> dedupedInputs;
869     auto indexingMaps = genericOp.getIndexingMaps();
870     ArrayRef<AffineMap> unprocessedIndexingMaps(indexingMaps);
871     for (OpOperand *inputOpOperand : genericOp.getInputOperands()) {
872       BlockArgument arg = genericOp.getTiedBlockArgument(inputOpOperand);
873       unsigned argNum = arg.getArgNumber();
874       unprocessedIndexingMaps = unprocessedIndexingMaps.drop_front();
875 
876       // Check if operand is dead and if dropping the indexing map makes the
877       // loops to shape computation invalid.
878       if (!genericOp.payloadUsesValueFromOperand(inputOpOperand)) {
879         // Add the current operands to the list of potentially droppable
880         // operands. If it cannot be dropped, this needs to be popped back.
881         droppedOpOperands.push_back(inputOpOperand);
882         if (genericOp.canOpOperandsBeDropped(droppedOpOperands))
883           continue;
884         droppedOpOperands.pop_back();
885       }
886 
887       // Check if this operand is a duplicate.
888       AffineMap indexingMap = genericOp.getTiedIndexingMap(inputOpOperand);
889       auto it = dedupedInputs.find(
890           std::make_pair(inputOpOperand->get(), indexingMap));
891       if (it != dedupedInputs.end()) {
892         origToNewPos[argNum] = it->second;
893         droppedOpOperands.push_back(inputOpOperand);
894         continue;
895       }
896 
897       // This is a preserved argument.
898       origToNewPos[argNum] = numNewArgs;
899       dedupedInputs[{inputOpOperand->get(), indexingMap}] = numNewArgs;
900       newInputOperands.push_back(inputOpOperand->get());
901       newIndexingMaps.push_back(indexingMap);
902       numNewArgs++;
903     }
904 
905     // If the op doesnt have tensor semantics, keep all the outputs as
906     // preserved.
907     if (!genericOp.hasTensorSemantics()) {
908       for (OpOperand *outputOpOperand : genericOp.getOutputOperands()) {
909         unprocessedIndexingMaps = unprocessedIndexingMaps.drop_front();
910         BlockArgument arg = genericOp.getTiedBlockArgument(outputOpOperand);
911         origToNewPos[arg.getArgNumber()] = numNewArgs++;
912         newOutputOperands.push_back(outputOpOperand->get());
913         newIndexingMaps.push_back(
914             genericOp.getTiedIndexingMap(outputOpOperand));
915       }
916     } else {
917       // Output argument can be dropped if the result has
918       // - no users, and
919       // - it is not used in the payload, and
920       // - the corresponding indexing maps are not needed for loop bound
921       //   computation.
922       for (auto outputOpOperand :
923            llvm::enumerate(genericOp.getOutputOperands())) {
924         unprocessedIndexingMaps = unprocessedIndexingMaps.drop_front();
925         Value result = genericOp.getResult(outputOpOperand.index());
926         BlockArgument arg =
927             genericOp.getTiedBlockArgument(outputOpOperand.value());
928         if (result.use_empty() &&
929             !genericOp.payloadUsesValueFromOperand(outputOpOperand.value())) {
930           // Check if the opoperand can be dropped without affecting loop bound
931           // computation. Add the operand to the list of dropped op operand for
932           // checking. If it cannot be dropped, need to pop the value back.
933           droppedOpOperands.push_back(outputOpOperand.value());
934           if (genericOp.canOpOperandsBeDropped(droppedOpOperands)) {
935             droppedOutputs.insert(outputOpOperand.index());
936             continue;
937           }
938           droppedOpOperands.pop_back();
939         }
940 
941         origToNewPos[arg.getArgNumber()] = numNewArgs++;
942         newOutputOperands.push_back(outputOpOperand.value()->get());
943         newIndexingMaps.push_back(
944             genericOp.getTiedIndexingMap(outputOpOperand.value()));
945         newResultTypes.push_back(result.getType());
946       }
947     }
948 
949     // Check if there is any change to operands.
950     if (newInputOperands.size() + newOutputOperands.size() ==
951         static_cast<size_t>(genericOp.getNumInputsAndOutputs()))
952       return failure();
953 
954     // Create the new op with the body being empty.
955     Location loc = genericOp.getLoc();
956     auto newOp = rewriter.create<GenericOp>(
957         loc, newResultTypes, newInputOperands, newOutputOperands,
958         rewriter.getAffineMapArrayAttr(newIndexingMaps),
959         genericOp.iterator_types(), genericOp.docAttr(),
960         genericOp.library_callAttr(),
961         [](OpBuilder & /*builder*/, Location /*loc*/, ValueRange /*args*/) {
962           return;
963         });
964     // Copy over unknown attributes. They might be load bearing for some flow.
965     ArrayRef<StringRef> odsAttrs = genericOp.getAttributeNames();
966     for (NamedAttribute kv : genericOp->getAttrs())
967       if (!llvm::is_contained(odsAttrs, kv.getName().getValue()))
968         newOp->setAttr(kv.getName(), kv.getValue());
969 
970     // Merge the body of the original op with the new op.
971     Block *newOpBlock = &newOp.region().front();
972     Block *origOpBlock = &genericOp.region().front();
973     SmallVector<Value> replacements(origOpBlock->getNumArguments(), nullptr);
974     for (auto argNum : llvm::seq<unsigned>(0, origOpBlock->getNumArguments())) {
975       auto it = origToNewPos.find(argNum);
976       if (it != origToNewPos.end())
977         replacements[argNum] = newOpBlock->getArgument(it->second);
978     }
979     rewriter.mergeBlocks(origOpBlock, newOpBlock, replacements);
980 
981     // Drop the unused yield args.
982     Block *block = &newOp.region().front();
983     if (!droppedOutputs.empty()) {
984       OpBuilder::InsertionGuard g(rewriter);
985       SmallVector<Value> newYieldVals;
986       YieldOp origYieldOp = cast<YieldOp>(block->getTerminator());
987       rewriter.setInsertionPoint(origYieldOp);
988       for (auto yieldOpOperands : llvm::enumerate(origYieldOp.values())) {
989         if (!droppedOutputs.count(yieldOpOperands.index())) {
990           newYieldVals.push_back(yieldOpOperands.value());
991           continue;
992         }
993       }
994       rewriter.replaceOpWithNewOp<YieldOp>(origYieldOp, newYieldVals);
995     }
996 
997     // Replace all live uses of the op.
998     SmallVector<Value> replacementsVals(genericOp->getNumResults(), nullptr);
999     unsigned newResultNum = 0;
1000     for (auto result : llvm::enumerate(genericOp.getResults()))
1001       if (!droppedOutputs.count(result.index()))
1002         replacementsVals[result.index()] = newOp.getResult(newResultNum++);
1003     rewriter.replaceOp(genericOp, replacementsVals);
1004     return success();
1005   }
1006 };
1007 
1008 /// Remove generic operations (on tensors) that are just copying
1009 /// the values from inputs to the results. Requirements are
1010 /// 1) All iterator types are parallel
1011 /// 2) The body contains just a yield operation with the yielded values being
1012 ///    the arguments corresponding to the operands.
1013 struct EraseIdentityGenericOp : public OpRewritePattern<GenericOp> {
1014   using OpRewritePattern<GenericOp>::OpRewritePattern;
1015 
1016   LogicalResult matchAndRewrite(GenericOp genericOp,
1017                                 PatternRewriter &rewriter) const override {
1018     // Check all indexing maps are identity.
1019     if (llvm::any_of(genericOp.getIndexingMaps(),
1020                      [](AffineMap map) { return !map.isIdentity(); }))
1021       return failure();
1022 
1023     // Check that the body of the linalg operation is just a linalg.yield
1024     // operation.
1025     Block &body = genericOp.region().front();
1026     if (!llvm::hasSingleElement(body))
1027       return failure();
1028     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
1029     if (!yieldOp)
1030       return failure();
1031 
1032     // In the buffer case, we need to check exact buffer equality.
1033     if (genericOp.hasBufferSemantics()) {
1034       if (genericOp.getNumInputs() == 1 && genericOp.getNumOutputs() == 1 &&
1035           genericOp.getInputOperand(0)->get() ==
1036               genericOp.getOutputOperand(0)->get()) {
1037         rewriter.eraseOp(genericOp);
1038         return success();
1039       }
1040       return failure();
1041     }
1042 
1043     // Get the argument number of the returned values. That is the operand
1044     // number to use for replacing uses of this operation.
1045     SmallVector<Value> returnedArgs;
1046     for (const auto &yieldVal : llvm::enumerate(yieldOp.values())) {
1047       auto yieldArg = yieldVal.value().dyn_cast<BlockArgument>();
1048       if (!yieldArg || yieldArg.getOwner() != &body)
1049         return failure();
1050       unsigned argumentNumber = yieldArg.getArgNumber();
1051       Value returnedArg = genericOp->getOperand(argumentNumber);
1052       Type resultType = genericOp->getResult(yieldVal.index()).getType();
1053       // The input can have a different type than the result, e.g. a dynamic
1054       // input dimension can be turned into a static output dimension.
1055       Type returnType = returnedArg.getType();
1056       if (returnType != resultType) {
1057         // Distinguish between sparse conversion or dense tensor casting.
1058         // TODO: unify the two ops?
1059         if (sparse_tensor::getSparseTensorEncoding(returnType) ||
1060             sparse_tensor::getSparseTensorEncoding(resultType))
1061           returnedArg = rewriter.create<sparse_tensor::ConvertOp>(
1062               genericOp.getLoc(), resultType, returnedArg);
1063         else {
1064           if (!tensor::CastOp::areCastCompatible(returnedArg.getType(),
1065                                                  resultType))
1066             return failure();
1067           returnedArg = rewriter.create<tensor::CastOp>(
1068               genericOp.getLoc(), resultType, returnedArg);
1069         }
1070       }
1071       returnedArgs.push_back(returnedArg);
1072     }
1073 
1074     if (returnedArgs.size() != genericOp->getNumResults())
1075       return failure();
1076     rewriter.replaceOp(genericOp, returnedArgs);
1077     return success();
1078   }
1079 };
1080 } // namespace
1081 
1082 void GenericOp::getCanonicalizationPatterns(RewritePatternSet &results,
1083                                             MLIRContext *context) {
1084   results
1085       .add<DeduplicateAndRemoveDeadOperandsAndResults, EraseIdentityGenericOp>(
1086           context);
1087 }
1088 
1089 LogicalResult GenericOp::fold(ArrayRef<Attribute>,
1090                               SmallVectorImpl<OpFoldResult> &) {
1091   return foldMemRefCast(*this);
1092 }
1093 
1094 //===----------------------------------------------------------------------===//
1095 // InitTensorOp
1096 //===----------------------------------------------------------------------===//
1097 
1098 void InitTensorOp::build(OpBuilder &b, OperationState &result,
1099                          ArrayRef<OpFoldResult> sizes, Type elementType,
1100                          ArrayRef<NamedAttribute> attrs) {
1101   SmallVector<Value, 4> dynamicSizes;
1102   SmallVector<int64_t, 4> staticSizes;
1103   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1104                              ShapedType::kDynamicSize);
1105   auto resultType = RankedTensorType ::get(staticSizes, elementType);
1106   build(b, result, resultType, dynamicSizes, b.getI64ArrayAttr(staticSizes));
1107   result.addAttributes(attrs);
1108 }
1109 
1110 LogicalResult InitTensorOp::verify() {
1111   RankedTensorType resultType = getType();
1112   SmallVector<int64_t, 4> staticSizes = llvm::to_vector<4>(llvm::map_range(
1113       static_sizes().cast<ArrayAttr>(),
1114       [](Attribute a) -> int64_t { return a.cast<IntegerAttr>().getInt(); }));
1115 
1116   if (failed(verifyListOfOperandsOrIntegers(
1117           *this, "sizes", resultType.getRank(), static_sizes(), sizes(),
1118           ShapedType::isDynamic)))
1119     return failure();
1120 
1121   if (static_sizes().size() != static_cast<unsigned>(resultType.getRank()))
1122     return emitError("expected ") << resultType.getRank() << " sizes values";
1123 
1124   Type expectedType = InitTensorOp::inferResultType(
1125       staticSizes, resultType.getElementType(), resultType.getEncoding());
1126   if (resultType != expectedType) {
1127     return emitError("specified type ")
1128            << resultType << " does not match the inferred type "
1129            << expectedType;
1130   }
1131   return success();
1132 }
1133 
1134 Type InitTensorOp::inferResultType(ArrayRef<int64_t> staticSizes,
1135                                    Type elementType, Attribute encoding) {
1136   return RankedTensorType::get(staticSizes, elementType, encoding);
1137 }
1138 
1139 SmallVector<OpFoldResult> InitTensorOp::getMixedSizes() {
1140   SmallVector<OpFoldResult> mixedSizes;
1141   mixedSizes.reserve(getType().getRank());
1142   unsigned dynamicValIndex = 0;
1143   for (Attribute attr : static_sizes()) {
1144     auto intAttr = attr.cast<IntegerAttr>();
1145     if (!ShapedType::isDynamic(intAttr.getInt())) {
1146       mixedSizes.push_back(intAttr);
1147       continue;
1148     }
1149     mixedSizes.push_back(sizes()[dynamicValIndex++]);
1150   }
1151   return mixedSizes;
1152 }
1153 
1154 namespace {
1155 /// Change the type of the result of a `linalg.init_tensor` by making the result
1156 /// type statically sized along dimension that in the original operation where
1157 /// defined as dynamic, but the size was defined using a `constant` op. For
1158 /// example
1159 ///
1160 ///  %c5 = arith.constant 5: index
1161 ///  %0 = linalg.init_tensor [%arg0, %c5] : tensor<?x?xf32>
1162 ///
1163 ///  to
1164 ///
1165 ///  %0 = linalg.init_tensor [%arg0, 5] : tensor<?x5xf32>
1166 struct ReplaceStaticShapeDims : OpRewritePattern<InitTensorOp> {
1167   using OpRewritePattern<InitTensorOp>::OpRewritePattern;
1168 
1169   LogicalResult matchAndRewrite(InitTensorOp op,
1170                                 PatternRewriter &rewriter) const override {
1171     SmallVector<Value, 4> dynamicSizes;
1172     SmallVector<int64_t, 4> staticSizes;
1173     for (unsigned i = 0, e = op.getType().getRank(); i != e; ++i) {
1174       // If the size is already static, nothing to do.
1175       if (!op.isDynamicSize(i)) {
1176         staticSizes.push_back(op.getStaticSize(i));
1177         continue;
1178       }
1179 
1180       // If the size is dynamic but defined using a `constant` op, get the
1181       // constant value to find the static size to use.
1182       unsigned operandNum = op.getIndexOfDynamicSize(i);
1183       Value sizeOperand = op.getOperand(operandNum);
1184       if (auto constantIndexOp =
1185               sizeOperand.getDefiningOp<arith::ConstantIndexOp>()) {
1186         staticSizes.push_back(constantIndexOp.value());
1187         continue;
1188       }
1189 
1190       // Fallback case. Keep the size dynamic.
1191       dynamicSizes.push_back(sizeOperand);
1192       staticSizes.push_back(ShapedType::kDynamicSize);
1193     }
1194     RankedTensorType newType =
1195         RankedTensorType::get(staticSizes, op.getType().getElementType());
1196     if (newType == op.getType())
1197       return failure();
1198     auto newOp =
1199         rewriter.create<InitTensorOp>(op.getLoc(), newType, dynamicSizes,
1200                                       rewriter.getI64ArrayAttr(staticSizes));
1201     rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
1202     return success();
1203   }
1204 };
1205 } // namespace
1206 
1207 namespace {
1208 /// Since `init_tensor` operation creates a tensor needed only for its shape, a
1209 /// slice of this is also needed only for its shape. The result can be
1210 /// replaced by a new init_tensor operation of the same size as the extract
1211 /// slice op.
1212 struct FoldInitTensorWithExtractSliceOp
1213     : public OpRewritePattern<tensor::ExtractSliceOp> {
1214   using OpRewritePattern<tensor::ExtractSliceOp>::OpRewritePattern;
1215 
1216   LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
1217                                 PatternRewriter &rewriter) const override {
1218     if (!sliceOp.source().getDefiningOp<linalg::InitTensorOp>())
1219       return failure();
1220     // ExtractSliceOp may be rank-reducing; its dynamic sizes must be preserved
1221     // as well as its result type.
1222     rewriter.replaceOpWithNewOp<linalg::InitTensorOp>(
1223         sliceOp, sliceOp.sizes(),
1224         sliceOp.result().getType().cast<RankedTensorType>().getShape(),
1225         sliceOp.getSourceType().getElementType());
1226     return success();
1227   }
1228 };
1229 
1230 template <typename TensorReshapeOp>
1231 struct FoldInitTensorWithTensorReshapeOp
1232     : public OpRewritePattern<TensorReshapeOp> {
1233   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1234 
1235   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1236                                 PatternRewriter &rewriter) const override {
1237     if (!reshapeOp.src().template getDefiningOp<InitTensorOp>())
1238       return failure();
1239     Location loc = reshapeOp.getLoc();
1240     ReifiedRankedShapedTypeDims resultShapes;
1241     ReifyRankedShapedTypeOpInterface reifyShapedTypeInterface =
1242         cast<ReifyRankedShapedTypeOpInterface>(reshapeOp.getOperation());
1243     if (failed(reifyShapedTypeInterface.reifyResultShapes(rewriter,
1244                                                           resultShapes)) ||
1245         !llvm::hasSingleElement(resultShapes))
1246       return failure();
1247     Value initTensor = rewriter.create<InitTensorOp>(
1248         loc, getAsOpFoldResult(resultShapes[0]),
1249         reshapeOp.getResultType().getElementType());
1250     if (initTensor.getType() != reshapeOp.getResultType()) {
1251       rewriter.replaceOpWithNewOp<tensor::CastOp>(
1252           reshapeOp, reshapeOp.getResultType(), initTensor);
1253     } else {
1254       rewriter.replaceOp(reshapeOp, initTensor);
1255     }
1256     return success();
1257   }
1258 };
1259 
1260 struct FoldInitTensorWithDimOp : public OpRewritePattern<tensor::DimOp> {
1261   using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
1262 
1263   LogicalResult matchAndRewrite(tensor::DimOp dimOp,
1264                                 PatternRewriter &rewriter) const override {
1265     Optional<int64_t> maybeConstantIndex = dimOp.getConstantIndex();
1266     auto initTensorOp = dimOp.source().getDefiningOp<linalg::InitTensorOp>();
1267     if (!initTensorOp || !maybeConstantIndex)
1268       return failure();
1269     if (!initTensorOp.isDynamicSize(*maybeConstantIndex))
1270       return failure();
1271     rewriter.replaceOp(dimOp, initTensorOp.getDynamicSize(*maybeConstantIndex));
1272     return success();
1273   }
1274 };
1275 
1276 /// Canonicalize
1277 ///
1278 /// ```mlir
1279 ///   %0 = linalg.init_tensor [%d0, %d1] : tensor<?x?xf32>
1280 ///   %1 = tensor.cast %0 : tensor<?x?xf32> to tensor<4x?xf32>
1281 /// ```
1282 ///
1283 /// into
1284 ///
1285 /// ```mlir
1286 ///   %0 = linalg.init_tensor [4, %d1] : tensor<4x?xf32>
1287 /// ```
1288 ///
1289 /// This assumes the input program is correct in terms of its shape. So it
1290 /// is safe to assume that `%d0` is in fact 4. If that was not the case, the
1291 /// input program is wrong to begin with, so its undefined behavior anyway (i.e.
1292 /// this optimization can still triggering without violating program semantics).
1293 struct FoldInitTensorWithTensorCastOp
1294     : public OpRewritePattern<tensor::CastOp> {
1295   using OpRewritePattern<tensor::CastOp>::OpRewritePattern;
1296 
1297   LogicalResult matchAndRewrite(tensor::CastOp castOp,
1298                                 PatternRewriter &rewriter) const override {
1299     if (!canFoldIntoProducerOp(castOp))
1300       return failure();
1301     auto producer = castOp.source().getDefiningOp<InitTensorOp>();
1302     if (!producer)
1303       return failure();
1304 
1305     auto resultType = castOp->getResult(0).getType().cast<RankedTensorType>();
1306     ArrayRef<int64_t> resultShape = resultType.getShape();
1307     SmallVector<OpFoldResult> currMixedSizes = producer.getMixedSizes();
1308     SmallVector<OpFoldResult> newMixedSizes;
1309     newMixedSizes.reserve(currMixedSizes.size());
1310     assert(resultShape.size() == currMixedSizes.size() &&
1311            "mismatch in result shape and sizes of init_tensor op");
1312     for (auto it : llvm::zip(resultShape, currMixedSizes)) {
1313       int64_t newDim = std::get<0>(it);
1314       OpFoldResult currDim = std::get<1>(it);
1315       // Case 1: The init tensor dim is static. Check that the tensor cast
1316       // result dim matches.
1317       if (auto attr = currDim.dyn_cast<Attribute>()) {
1318         if (ShapedType::isDynamic(newDim) ||
1319             newDim != attr.cast<IntegerAttr>().getInt()) {
1320           // Something is off, the cast result shape cannot be more dynamic than
1321           // the init tensor result shape (enforced by `canFoldIntoProducer`).
1322           // Abort for now.
1323           return rewriter.notifyMatchFailure(
1324               producer, "mismatch in static value of shape of init "
1325                         "tensor result and cast result");
1326         }
1327         newMixedSizes.push_back(attr);
1328         continue;
1329       }
1330 
1331       // Case 2 : The tensor cast shape is static, but init tensor result shape
1332       // is dynamic.
1333       if (!ShapedType::isDynamic(newDim)) {
1334         newMixedSizes.push_back(rewriter.getIndexAttr(newDim));
1335         continue;
1336       }
1337 
1338       // Case 3 : The tensor cast shape is dynamic and init tensor result shape
1339       // is dynamic. Use the dynamic value from the init tensor op.
1340       newMixedSizes.push_back(currDim);
1341     }
1342 
1343     rewriter.replaceOpWithNewOp<InitTensorOp>(castOp, newMixedSizes,
1344                                               resultType.getElementType());
1345     return success();
1346   }
1347 };
1348 
1349 } // namespace
1350 
1351 void InitTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
1352                                                MLIRContext *context) {
1353   results.add<FoldInitTensorWithTensorCastOp, FoldInitTensorWithDimOp,
1354               FoldInitTensorWithExtractSliceOp,
1355               FoldInitTensorWithTensorReshapeOp<tensor::ExpandShapeOp>,
1356               FoldInitTensorWithTensorReshapeOp<tensor::CollapseShapeOp>,
1357               ReplaceStaticShapeDims>(context);
1358 }
1359 
1360 LogicalResult InitTensorOp::reifyResultShapes(
1361     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1362   auto shapes = llvm::to_vector<4>(llvm::map_range(
1363       llvm::seq<int64_t>(0, getType().getRank()), [&](int64_t dim) -> Value {
1364         if (isDynamicSize(dim))
1365           return getDynamicSize(dim);
1366         return builder.create<arith::ConstantIndexOp>(getLoc(),
1367                                                       getStaticSize(dim));
1368       }));
1369   reifiedReturnShapes.emplace_back(std::move(shapes));
1370   return success();
1371 }
1372 
1373 //===----------------------------------------------------------------------===//
1374 // YieldOp
1375 //===----------------------------------------------------------------------===//
1376 
1377 void linalg::YieldOp::print(OpAsmPrinter &p) {
1378   if (getNumOperands() > 0)
1379     p << ' ' << getOperands();
1380   p.printOptionalAttrDict((*this)->getAttrs());
1381   if (getNumOperands() > 0)
1382     p << " : " << getOperandTypes();
1383 }
1384 
1385 ParseResult YieldOp::parse(OpAsmParser &parser, OperationState &result) {
1386   SmallVector<OpAsmParser::UnresolvedOperand, 2> opInfo;
1387   SmallVector<Type, 2> types;
1388   SMLoc loc = parser.getCurrentLocation();
1389   return failure(parser.parseOperandList(opInfo) ||
1390                  parser.parseOptionalAttrDict(result.attributes) ||
1391                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
1392                  parser.resolveOperands(opInfo, types, loc, result.operands));
1393 }
1394 
1395 // Check the operand number and types must match the element types of the
1396 // LinalgOp interface's shaped operands.
1397 static LogicalResult verifyYield(linalg::YieldOp op, LinalgOp linalgOp) {
1398   if (op.getNumOperands() != linalgOp.getNumOutputs())
1399     return op.emitOpError("expected number of yield values (")
1400            << linalgOp.getNumOutputs()
1401            << ") to match the number of operands of the enclosing "
1402            << "LinalgOp (" << op.getNumOperands() << ")";
1403 
1404   for (OpOperand &opOperand : op->getOpOperands()) {
1405     OpOperand *outputOperand =
1406         linalgOp.getOutputOperand(opOperand.getOperandNumber());
1407     Type elementType = getElementTypeOrSelf(outputOperand->get().getType());
1408     if (opOperand.get().getType() != elementType)
1409       return op.emitOpError("type of yield operand ")
1410              << (opOperand.getOperandNumber() + 1) << " ("
1411              << opOperand.get().getType() << ") doesn't match "
1412              << "the element type of the enclosing linalg.generic op ("
1413              << elementType << ")";
1414   }
1415   return success();
1416 }
1417 
1418 LogicalResult linalg::YieldOp::verify() {
1419   auto *parentOp = (*this)->getParentOp();
1420   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
1421     return emitOpError("expected single non-empty parent region");
1422 
1423   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
1424     return verifyYield(*this, linalgOp);
1425 
1426   return emitOpError("expected parent op with LinalgOp interface");
1427 }
1428 
1429 //===----------------------------------------------------------------------===//
1430 // IndexOp
1431 //===----------------------------------------------------------------------===//
1432 
1433 LogicalResult IndexOp::verify() {
1434   auto linalgOp = dyn_cast<LinalgOp>((*this)->getParentOp());
1435   if (!linalgOp)
1436     return emitOpError("expected parent op with LinalgOp interface");
1437   if (linalgOp.getNumLoops() <= dim())
1438     return emitOpError("expected dim (")
1439            << dim() << ") to be lower than the number of loops ("
1440            << linalgOp.getNumLoops() << ") of the enclosing LinalgOp";
1441   return success();
1442 }
1443 
1444 /////// Operations corresponding to library calls defined with Tablegen ////////
1445 
1446 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc"
1447 
1448 #define GET_OP_CLASSES
1449 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
1450 
1451 #define GET_OP_CLASSES
1452 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
1453 
1454 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
1455 /// Assumes `op` is a LinalgOp.
1456 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
1457                                  SmallVectorImpl<unsigned> &res) {
1458   if (!cast<LinalgOp>(op).iterator_types())
1459     return;
1460 
1461   unsigned dim = 0;
1462   for (auto tn :
1463        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
1464     if (tn == iteratorTypeName)
1465       res.push_back(dim);
1466     ++dim;
1467   }
1468 }
1469 
1470 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
1471                                              unsigned rank,
1472                                              MLIRContext *context) {
1473   if (maybeMap)
1474     return maybeMap.getValue();
1475   if (rank == 0)
1476     return AffineMap::get(context);
1477   return AffineMap::getMultiDimIdentityMap(rank, context);
1478 }
1479 
1480 SmallVector<AffineExpr, 4>
1481 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
1482                                  MLIRContext *context) {
1483   SmallVector<AffineExpr, 4> res;
1484   res.reserve(num);
1485   for (unsigned i = 0; i < num; ++i)
1486     res.push_back(getAffineDimExpr(startIdx++, context));
1487   return res;
1488 }
1489 
1490 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
1491                                                 ArrayRef<AffineExpr> b) {
1492   auto rangeA = llvm::make_range(a.begin(), a.end());
1493   auto rangeB = llvm::make_range(b.begin(), b.end());
1494   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
1495   return llvm::to_vector<4>(concatRanges);
1496 }
1497 
1498 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
1499   if (auto memref = t.dyn_cast<MemRefType>()) {
1500     ss << "view";
1501     for (auto size : memref.getShape())
1502       if (size < 0)
1503         ss << "sx";
1504       else
1505         ss << size << "x";
1506     appendMangledType(ss, memref.getElementType());
1507   } else if (auto vec = t.dyn_cast<VectorType>()) {
1508     ss << "vector";
1509     llvm::interleave(
1510         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
1511     appendMangledType(ss, vec.getElementType());
1512   } else if (t.isSignlessIntOrIndexOrFloat()) {
1513     ss << t;
1514   } else {
1515     llvm_unreachable("Invalid type for linalg library name mangling");
1516   }
1517 }
1518 
1519 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
1520   assert(isa<LinalgOp>(op));
1521   std::string name(op->getName().getStringRef().str());
1522   name.reserve(128);
1523   std::replace(name.begin(), name.end(), '.', '_');
1524   llvm::raw_string_ostream ss(name);
1525   ss << "_";
1526   auto types = op->getOperandTypes();
1527   llvm::interleave(
1528       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
1529       [&]() { ss << "_"; });
1530   return ss.str();
1531 }
1532 
1533 //===----------------------------------------------------------------------===//
1534 // Canonicalizers and Folders.
1535 //===----------------------------------------------------------------------===//
1536 
1537 namespace {
1538 struct EraseDeadLinalgOp : public OpInterfaceRewritePattern<LinalgOp> {
1539   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1540 
1541   LogicalResult matchAndRewrite(LinalgOp op,
1542                                 PatternRewriter &rewriter) const override {
1543     for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
1544       // Linalg "inputs" may be either tensor or memref type.
1545       // tensor<0xelt_type> is a convention that may not always mean
1546       // "0 iterations". Only erase in cases we see memref<...x0x...>.
1547       auto mt = opOperand->get().getType().dyn_cast<MemRefType>();
1548       if (!mt)
1549         continue;
1550       if (llvm::is_contained(op.getShape(opOperand), 0)) {
1551         rewriter.eraseOp(op);
1552         return success();
1553       }
1554     }
1555     return failure();
1556   }
1557 };
1558 
1559 struct FoldTensorCastProducerOp : public OpInterfaceRewritePattern<LinalgOp> {
1560   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1561 
1562   LogicalResult matchAndRewrite(LinalgOp op,
1563                                 PatternRewriter &rewriter) const override {
1564     // If no operand comes from a tensor::CastOp and can be folded then fail.
1565     bool hasTensorCastOperand =
1566         llvm::any_of(op.getInputAndOutputOperands(), [&](OpOperand *opOperand) {
1567           if (opOperand->get().isa<BlockArgument>())
1568             return false;
1569           auto castOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1570           return castOp && canFoldIntoConsumerOp(castOp);
1571         });
1572     if (!hasTensorCastOperand)
1573       return failure();
1574 
1575     SmallVector<Type, 4> newResultTypes;
1576     newResultTypes.reserve(op->getNumResults());
1577     SmallVector<Value, 4> newOperands;
1578     newOperands.reserve(op->getNumOperands());
1579     // Inputs may fold.
1580     for (OpOperand *opOperand : op.getInputOperands()) {
1581       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1582       newOperands.push_back(canFoldIntoConsumerOp(tensorCastOp)
1583                                 ? tensorCastOp.source()
1584                                 : opOperand->get());
1585     }
1586     // Init tensors may fold, in which case the resultType must also change.
1587     for (OpOperand *opOperand : op.getOutputOperands()) {
1588       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1589       bool fold = canFoldIntoConsumerOp(tensorCastOp);
1590       newOperands.push_back(fold ? tensorCastOp.getOperand()
1591                                  : opOperand->get());
1592       newResultTypes.push_back(newOperands.back().getType());
1593     }
1594     // Clone op.
1595     Operation *newOp =
1596         op.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
1597     SmallVector<Value, 4> replacements;
1598     replacements.reserve(newOp->getNumResults());
1599     for (auto result : llvm::zip(op->getResults(), newOp->getResults())) {
1600       Value oldResult = std::get<0>(result);
1601       Value newResult = std::get<1>(result);
1602       if (newResult.getType() != oldResult.getType()) {
1603         replacements.push_back(rewriter.create<tensor::CastOp>(
1604             op->getLoc(), oldResult.getType(), newResult));
1605       } else {
1606         replacements.push_back(newResult);
1607       }
1608     }
1609     rewriter.replaceOp(op, replacements);
1610 
1611     return success();
1612   }
1613 };
1614 
1615 /// Fold LinalgOps with `tensor.cast` consumer if the `tensor.cast` has
1616 /// result that is more static than the linalg op.
1617 struct FoldTensorCastConsumerOp : public OpRewritePattern<tensor::CastOp> {
1618   using OpRewritePattern<tensor::CastOp>::OpRewritePattern;
1619 
1620   LogicalResult matchAndRewrite(tensor::CastOp castOp,
1621                                 PatternRewriter &rewriter) const override {
1622     if (!tensor::canFoldIntoProducerOp(castOp))
1623       return failure();
1624     auto linalgOp = castOp.source().getDefiningOp<LinalgOp>();
1625     if (!linalgOp)
1626       return failure();
1627 
1628     OpBuilder::InsertionGuard guard(rewriter);
1629     rewriter.setInsertionPoint(linalgOp);
1630 
1631     Location loc = linalgOp.getLoc();
1632     OpResult resultValue = castOp.source().cast<OpResult>();
1633     unsigned resultNumber = resultValue.getResultNumber();
1634     auto resultType = castOp->getResult(0).getType().cast<RankedTensorType>();
1635     // Replace the `outs` for the result with a `tensor.cast`. This cast is now
1636     // going from a more dynamic shape to a less dynamic shape. If the producer
1637     // for this cast, i.e. producer of the out operand, is also an operation
1638     // that folds with tensor.cast consumer (like this pattern), the cast will
1639     // continue to propagate as far up the stack as it can go.
1640     OpOperand *outOperand = linalgOp.getOutputOperand(resultNumber);
1641     Value newOperand =
1642         rewriter.create<tensor::CastOp>(loc, resultType, outOperand->get());
1643     SmallVector<Value> newOperands = linalgOp.getInputOperands();
1644     SmallVector<Value> outputOperands = linalgOp.getOutputOperands();
1645     outputOperands[resultNumber] = newOperand;
1646     newOperands.append(outputOperands.begin(), outputOperands.end());
1647 
1648     SmallVector<Type> resultTypes(linalgOp->result_type_begin(),
1649                                   linalgOp->result_type_end());
1650     resultTypes[resultNumber] = resultType;
1651     Operation *newOp = linalgOp.clone(rewriter, loc, resultTypes, newOperands);
1652 
1653     // Create a tensor.cast operation back to the original type.
1654     Value castBack = rewriter.create<tensor::CastOp>(
1655         loc, resultValue.getType(), newOp->getResult(resultNumber));
1656 
1657     SmallVector<Value> results(newOp->result_begin(), newOp->result_end());
1658     results[resultNumber] = castBack;
1659     rewriter.replaceOp(linalgOp, results);
1660     rewriter.replaceOp(castOp, newOp->getResult(resultNumber));
1661     return success();
1662   }
1663 };
1664 
1665 /// For each of the operand in `operands` this function maps the static sizes of
1666 /// dimensions to their affine dim expressions.
1667 static void populateMap(LinalgOp linalgOp, ArrayRef<OpOperand *> operands,
1668                         llvm::DenseMap<AffineExpr, int64_t> &affineExprToSize) {
1669   for (OpOperand *opOperand : operands) {
1670     if (linalgOp.isScalar(opOperand))
1671       continue;
1672     Value src = opOperand->get();
1673     auto sourceType = src.getType().cast<RankedTensorType>();
1674     auto sourceMap = linalgOp.getTiedIndexingMap(opOperand);
1675 
1676     // Get the `sourceShape` of the `sourceType`. If the operand is a result of
1677     // `tensor.cast` operation and source of the cast operation has a static
1678     // shape, then assign it to the `sourceShape`.
1679     auto *parentOp = src.getDefiningOp();
1680     ArrayRef<int64_t> sourceShape = sourceType.getShape();
1681     if (parentOp) {
1682       if (auto castOp = dyn_cast<tensor::CastOp>(parentOp)) {
1683         Value castSource = castOp.source();
1684         auto castSourceType = castSource.getType().cast<RankedTensorType>();
1685         if (castSourceType.hasStaticShape())
1686           sourceShape = castSourceType.getShape();
1687       }
1688     }
1689 
1690     // If the source shape's dimension has a static shape, map the affine dim
1691     // expression to the known static size.
1692     for (unsigned i = 0; i < sourceShape.size(); i++) {
1693       if (sourceType.isDynamicDim(i))
1694         continue;
1695       if (auto affineDimExpr = sourceMap.getResult(i).dyn_cast<AffineDimExpr>())
1696         affineExprToSize.try_emplace(affineDimExpr, sourceShape[i]);
1697     }
1698   }
1699 }
1700 
1701 /// Creates new operand w.r.t 'opOperand' of `linalgOp` with static sizes
1702 /// mapped in `affineExprToSize`. New operands are created in `newOperands` and
1703 /// their result types is stored in `resultTypes`. If `opOperand` requires no
1704 /// change then `changeNeeded` is false and same operand is added in the
1705 /// `newOperands` list.
1706 static void createNewOperandWithStaticSizes(
1707     Location loc, PatternRewriter &rewriter, OpOperand *opOperand,
1708     llvm::DenseMap<AffineExpr, int64_t> &affineExprToSize, LinalgOp linalgOp,
1709     SmallVector<Value> &newOperands, SmallVector<Type> &resultTypes,
1710     bool &changeNeeded) {
1711   Value src = opOperand->get();
1712   newOperands.push_back(src);
1713   if (linalgOp.isScalar(opOperand))
1714     return;
1715   auto sourceType = src.getType().cast<RankedTensorType>();
1716   Type resultType = sourceType;
1717   if (sourceType.hasStaticShape() && linalgOp.isOutputTensor(opOperand)) {
1718     resultTypes.push_back(resultType);
1719     return;
1720   }
1721   ArrayRef<int64_t> sourceShape = sourceType.getShape();
1722   AffineMap sourceMap = linalgOp.getTiedIndexingMap(opOperand);
1723   SmallVector<int64_t> newShape;
1724   // If operand is updated with new shape, `newOperandNeeded` will be
1725   // true.
1726   bool newOperandNeeded = false;
1727   for (unsigned i = 0; i < sourceShape.size(); i++) {
1728     int64_t dimShape = sourceShape[i];
1729     AffineExpr dimExpr = sourceMap.getResult(i);
1730     if (affineExprToSize.find(dimExpr) == affineExprToSize.end() ||
1731         !sourceType.isDynamicDim(i)) {
1732       newShape.push_back(dimShape);
1733       continue;
1734     }
1735     // Dimension has a dynamic shape and corresponding affine dim
1736     // expression is present in the map. So assign the size for the
1737     // given affine dim expression to the dimension.
1738     newShape.push_back(affineExprToSize[dimExpr]);
1739     newOperandNeeded = true;
1740   }
1741   resultType = RankedTensorType::get(newShape, sourceType.getElementType());
1742   if (newOperandNeeded) {
1743     changeNeeded = true;
1744     // Get the new operand value given its size and element type by
1745     // casting it.
1746     Value newOperand = rewriter.create<tensor::CastOp>(loc, resultType, src);
1747     unsigned index = opOperand->getOperandNumber();
1748     newOperands[index] = newOperand;
1749   }
1750   if (linalgOp.isOutputTensor(opOperand))
1751     resultTypes.push_back(resultType);
1752 }
1753 
1754 /// Static shapes for the operands can be inferred if any one of the operands
1755 /// have a static shape. This can be done by referring to the affine dim
1756 /// expressions for the operand.
1757 struct InferStaticShapeOfOperands : public OpInterfaceRewritePattern<LinalgOp> {
1758   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1759 
1760   LogicalResult matchAndRewrite(LinalgOp linalgOp,
1761                                 PatternRewriter &rewriter) const override {
1762     if (!linalgOp.hasTensorSemantics())
1763       return failure();
1764 
1765     // Maps must be projected permutations.
1766     if (llvm::any_of(linalgOp.getIndexingMaps(), [](AffineMap map) {
1767           return !map.isProjectedPermutation();
1768         }))
1769       return failure();
1770 
1771     // Maps affine dim expressions to the static size of that dimension.
1772     llvm::DenseMap<AffineExpr, int64_t> affineExprToSize;
1773     Location loc = linalgOp.getLoc();
1774 
1775     // For each of the affine dim expression, check if the size is known. If
1776     // known add that in the map.
1777     populateMap(linalgOp, linalgOp.getInputAndOutputOperands(),
1778                 affineExprToSize);
1779 
1780     SmallVector<Value> newOperands;
1781     SmallVector<Type> resultTypes;
1782 
1783     // `changeNeeded` is `false` if the operands of `linalgOp` require no
1784     // change in their types.
1785     bool changeNeeded = false;
1786     newOperands.reserve(linalgOp.getNumInputsAndOutputs());
1787     resultTypes.reserve(linalgOp.getNumOutputs());
1788 
1789     // Iterate over all the operands and update the static sizes.
1790     for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
1791       createNewOperandWithStaticSizes(loc, rewriter, opOperand,
1792                                       affineExprToSize, linalgOp, newOperands,
1793                                       resultTypes, changeNeeded);
1794     }
1795 
1796     // If the generic op has all the required static information, no
1797     // canonicalization needed.
1798     if (!changeNeeded)
1799       return failure();
1800 
1801     // Clone op.
1802     Operation *newOp =
1803         linalgOp.clone(rewriter, linalgOp->getLoc(), resultTypes, newOperands);
1804     SmallVector<Value> replacements;
1805     replacements.reserve(newOp->getNumResults());
1806     for (auto it : llvm::zip(linalgOp->getResults(), newOp->getResults())) {
1807       Value newResult = std::get<1>(it);
1808       Value oldResult = std::get<0>(it);
1809       Type newType = newResult.getType();
1810       Type oldType = oldResult.getType();
1811       replacements.push_back(
1812           (newType != oldType)
1813               ? rewriter.create<tensor::CastOp>(loc, oldType, newResult)
1814               : newResult);
1815     }
1816     rewriter.replaceOp(linalgOp, replacements);
1817     return success();
1818   }
1819 };
1820 
1821 } // namespace
1822 
1823 // All named ops canonicalizers and folders are auto-generated in the
1824 // .cpp.inc.
1825 
1826 //===----------------------------------------------------------------------===//
1827 // LinalgDialect
1828 //===----------------------------------------------------------------------===//
1829 
1830 void LinalgDialect::getCanonicalizationPatterns(
1831     RewritePatternSet &results) const {
1832   results.add<EraseDeadLinalgOp, FoldTensorCastConsumerOp,
1833               FoldTensorCastProducerOp, InferStaticShapeOfOperands>(
1834       getContext());
1835 }
1836 
1837 Operation *LinalgDialect::materializeConstant(OpBuilder &builder,
1838                                               Attribute value, Type type,
1839                                               Location loc) {
1840   return builder.create<arith::ConstantOp>(loc, type, value);
1841 }
1842