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 (const 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 (const auto &yieldOpOperands :
989            llvm::enumerate(origYieldOp.values())) {
990         if (!droppedOutputs.count(yieldOpOperands.index())) {
991           newYieldVals.push_back(yieldOpOperands.value());
992           continue;
993         }
994       }
995       rewriter.replaceOpWithNewOp<YieldOp>(origYieldOp, newYieldVals);
996     }
997 
998     // Replace all live uses of the op.
999     SmallVector<Value> replacementsVals(genericOp->getNumResults(), nullptr);
1000     unsigned newResultNum = 0;
1001     for (const auto &result : llvm::enumerate(genericOp.getResults()))
1002       if (!droppedOutputs.count(result.index()))
1003         replacementsVals[result.index()] = newOp.getResult(newResultNum++);
1004     rewriter.replaceOp(genericOp, replacementsVals);
1005     return success();
1006   }
1007 };
1008 
1009 /// Remove generic operations (on tensors) that are just copying
1010 /// the values from inputs to the results. Requirements are
1011 /// 1) All iterator types are parallel
1012 /// 2) The body contains just a yield operation with the yielded values being
1013 ///    the arguments corresponding to the operands.
1014 struct EraseIdentityGenericOp : public OpRewritePattern<GenericOp> {
1015   using OpRewritePattern<GenericOp>::OpRewritePattern;
1016 
1017   LogicalResult matchAndRewrite(GenericOp genericOp,
1018                                 PatternRewriter &rewriter) const override {
1019     // Check all indexing maps are identity.
1020     if (llvm::any_of(genericOp.getIndexingMaps(),
1021                      [](AffineMap map) { return !map.isIdentity(); }))
1022       return failure();
1023 
1024     // Check that the body of the linalg operation is just a linalg.yield
1025     // operation.
1026     Block &body = genericOp.region().front();
1027     if (!llvm::hasSingleElement(body))
1028       return failure();
1029     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
1030     if (!yieldOp)
1031       return failure();
1032 
1033     // In the buffer case, we need to check exact buffer equality.
1034     if (genericOp.hasBufferSemantics()) {
1035       if (genericOp.getNumInputs() == 1 && genericOp.getNumOutputs() == 1 &&
1036           genericOp.getInputOperand(0)->get() ==
1037               genericOp.getOutputOperand(0)->get()) {
1038         rewriter.eraseOp(genericOp);
1039         return success();
1040       }
1041       return failure();
1042     }
1043 
1044     // Get the argument number of the returned values. That is the operand
1045     // number to use for replacing uses of this operation.
1046     SmallVector<Value> returnedArgs;
1047     for (const auto &yieldVal : llvm::enumerate(yieldOp.values())) {
1048       auto yieldArg = yieldVal.value().dyn_cast<BlockArgument>();
1049       if (!yieldArg || yieldArg.getOwner() != &body)
1050         return failure();
1051       unsigned argumentNumber = yieldArg.getArgNumber();
1052       Value returnedArg = genericOp->getOperand(argumentNumber);
1053       Type resultType = genericOp->getResult(yieldVal.index()).getType();
1054       // The input can have a different type than the result, e.g. a dynamic
1055       // input dimension can be turned into a static output dimension.
1056       Type returnType = returnedArg.getType();
1057       if (returnType != resultType) {
1058         // Distinguish between sparse conversion or dense tensor casting.
1059         // TODO: unify the two ops?
1060         if (sparse_tensor::getSparseTensorEncoding(returnType) ||
1061             sparse_tensor::getSparseTensorEncoding(resultType))
1062           returnedArg = rewriter.create<sparse_tensor::ConvertOp>(
1063               genericOp.getLoc(), resultType, returnedArg);
1064         else {
1065           if (!tensor::CastOp::areCastCompatible(returnedArg.getType(),
1066                                                  resultType))
1067             return failure();
1068           returnedArg = rewriter.create<tensor::CastOp>(
1069               genericOp.getLoc(), resultType, returnedArg);
1070         }
1071       }
1072       returnedArgs.push_back(returnedArg);
1073     }
1074 
1075     if (returnedArgs.size() != genericOp->getNumResults())
1076       return failure();
1077     rewriter.replaceOp(genericOp, returnedArgs);
1078     return success();
1079   }
1080 };
1081 } // namespace
1082 
1083 void GenericOp::getCanonicalizationPatterns(RewritePatternSet &results,
1084                                             MLIRContext *context) {
1085   results
1086       .add<DeduplicateAndRemoveDeadOperandsAndResults, EraseIdentityGenericOp>(
1087           context);
1088 }
1089 
1090 LogicalResult GenericOp::fold(ArrayRef<Attribute>,
1091                               SmallVectorImpl<OpFoldResult> &) {
1092   return foldMemRefCast(*this);
1093 }
1094 
1095 //===----------------------------------------------------------------------===//
1096 // InitTensorOp
1097 //===----------------------------------------------------------------------===//
1098 
1099 void InitTensorOp::build(OpBuilder &b, OperationState &result,
1100                          ArrayRef<OpFoldResult> sizes, Type elementType,
1101                          ArrayRef<NamedAttribute> attrs) {
1102   SmallVector<Value, 4> dynamicSizes;
1103   SmallVector<int64_t, 4> staticSizes;
1104   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1105                              ShapedType::kDynamicSize);
1106   auto resultType = RankedTensorType ::get(staticSizes, elementType);
1107   build(b, result, resultType, dynamicSizes, b.getI64ArrayAttr(staticSizes));
1108   result.addAttributes(attrs);
1109 }
1110 
1111 LogicalResult InitTensorOp::verify() {
1112   RankedTensorType resultType = getType();
1113   SmallVector<int64_t, 4> staticSizes = llvm::to_vector<4>(llvm::map_range(
1114       static_sizes().cast<ArrayAttr>(),
1115       [](Attribute a) -> int64_t { return a.cast<IntegerAttr>().getInt(); }));
1116 
1117   if (failed(verifyListOfOperandsOrIntegers(
1118           *this, "sizes", resultType.getRank(), static_sizes(), sizes(),
1119           ShapedType::isDynamic)))
1120     return failure();
1121 
1122   if (static_sizes().size() != static_cast<unsigned>(resultType.getRank()))
1123     return emitError("expected ") << resultType.getRank() << " sizes values";
1124 
1125   Type expectedType = InitTensorOp::inferResultType(
1126       staticSizes, resultType.getElementType(), resultType.getEncoding());
1127   if (resultType != expectedType) {
1128     return emitError("specified type ")
1129            << resultType << " does not match the inferred type "
1130            << expectedType;
1131   }
1132   return success();
1133 }
1134 
1135 Type InitTensorOp::inferResultType(ArrayRef<int64_t> staticSizes,
1136                                    Type elementType, Attribute encoding) {
1137   return RankedTensorType::get(staticSizes, elementType, encoding);
1138 }
1139 
1140 SmallVector<OpFoldResult> InitTensorOp::getMixedSizes() {
1141   SmallVector<OpFoldResult> mixedSizes;
1142   mixedSizes.reserve(getType().getRank());
1143   unsigned dynamicValIndex = 0;
1144   for (Attribute attr : static_sizes()) {
1145     auto intAttr = attr.cast<IntegerAttr>();
1146     if (!ShapedType::isDynamic(intAttr.getInt())) {
1147       mixedSizes.push_back(intAttr);
1148       continue;
1149     }
1150     mixedSizes.push_back(sizes()[dynamicValIndex++]);
1151   }
1152   return mixedSizes;
1153 }
1154 
1155 namespace {
1156 /// Change the type of the result of a `linalg.init_tensor` by making the result
1157 /// type statically sized along dimension that in the original operation where
1158 /// defined as dynamic, but the size was defined using a `constant` op. For
1159 /// example
1160 ///
1161 ///  %c5 = arith.constant 5: index
1162 ///  %0 = linalg.init_tensor [%arg0, %c5] : tensor<?x?xf32>
1163 ///
1164 ///  to
1165 ///
1166 ///  %0 = linalg.init_tensor [%arg0, 5] : tensor<?x5xf32>
1167 struct ReplaceStaticShapeDims : OpRewritePattern<InitTensorOp> {
1168   using OpRewritePattern<InitTensorOp>::OpRewritePattern;
1169 
1170   LogicalResult matchAndRewrite(InitTensorOp op,
1171                                 PatternRewriter &rewriter) const override {
1172     SmallVector<Value, 4> dynamicSizes;
1173     SmallVector<int64_t, 4> staticSizes;
1174     for (unsigned i = 0, e = op.getType().getRank(); i != e; ++i) {
1175       // If the size is already static, nothing to do.
1176       if (!op.isDynamicSize(i)) {
1177         staticSizes.push_back(op.getStaticSize(i));
1178         continue;
1179       }
1180 
1181       // If the size is dynamic but defined using a `constant` op, get the
1182       // constant value to find the static size to use.
1183       unsigned operandNum = op.getIndexOfDynamicSize(i);
1184       Value sizeOperand = op.getOperand(operandNum);
1185       if (auto constantIndexOp =
1186               sizeOperand.getDefiningOp<arith::ConstantIndexOp>()) {
1187         staticSizes.push_back(constantIndexOp.value());
1188         continue;
1189       }
1190 
1191       // Fallback case. Keep the size dynamic.
1192       dynamicSizes.push_back(sizeOperand);
1193       staticSizes.push_back(ShapedType::kDynamicSize);
1194     }
1195     RankedTensorType newType =
1196         RankedTensorType::get(staticSizes, op.getType().getElementType());
1197     if (newType == op.getType())
1198       return failure();
1199     auto newOp =
1200         rewriter.create<InitTensorOp>(op.getLoc(), newType, dynamicSizes,
1201                                       rewriter.getI64ArrayAttr(staticSizes));
1202     rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
1203     return success();
1204   }
1205 };
1206 } // namespace
1207 
1208 namespace {
1209 /// Since `init_tensor` operation creates a tensor needed only for its shape, a
1210 /// slice of this is also needed only for its shape. The result can be
1211 /// replaced by a new init_tensor operation of the same size as the extract
1212 /// slice op.
1213 struct FoldInitTensorWithExtractSliceOp
1214     : public OpRewritePattern<tensor::ExtractSliceOp> {
1215   using OpRewritePattern<tensor::ExtractSliceOp>::OpRewritePattern;
1216 
1217   LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
1218                                 PatternRewriter &rewriter) const override {
1219     if (!sliceOp.source().getDefiningOp<linalg::InitTensorOp>())
1220       return failure();
1221     // ExtractSliceOp may be rank-reducing; its dynamic sizes must be preserved
1222     // as well as its result type.
1223     rewriter.replaceOpWithNewOp<linalg::InitTensorOp>(
1224         sliceOp, sliceOp.sizes(),
1225         sliceOp.result().getType().cast<RankedTensorType>().getShape(),
1226         sliceOp.getSourceType().getElementType());
1227     return success();
1228   }
1229 };
1230 
1231 template <typename TensorReshapeOp>
1232 struct FoldInitTensorWithTensorReshapeOp
1233     : public OpRewritePattern<TensorReshapeOp> {
1234   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1235 
1236   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1237                                 PatternRewriter &rewriter) const override {
1238     if (!reshapeOp.src().template getDefiningOp<InitTensorOp>())
1239       return failure();
1240     Location loc = reshapeOp.getLoc();
1241     ReifiedRankedShapedTypeDims resultShapes;
1242     ReifyRankedShapedTypeOpInterface reifyShapedTypeInterface =
1243         cast<ReifyRankedShapedTypeOpInterface>(reshapeOp.getOperation());
1244     if (failed(reifyShapedTypeInterface.reifyResultShapes(rewriter,
1245                                                           resultShapes)) ||
1246         !llvm::hasSingleElement(resultShapes))
1247       return failure();
1248     Value initTensor = rewriter.create<InitTensorOp>(
1249         loc, getAsOpFoldResult(resultShapes[0]),
1250         reshapeOp.getResultType().getElementType());
1251     if (initTensor.getType() != reshapeOp.getResultType()) {
1252       rewriter.replaceOpWithNewOp<tensor::CastOp>(
1253           reshapeOp, reshapeOp.getResultType(), initTensor);
1254     } else {
1255       rewriter.replaceOp(reshapeOp, initTensor);
1256     }
1257     return success();
1258   }
1259 };
1260 
1261 struct FoldInitTensorWithDimOp : public OpRewritePattern<tensor::DimOp> {
1262   using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
1263 
1264   LogicalResult matchAndRewrite(tensor::DimOp dimOp,
1265                                 PatternRewriter &rewriter) const override {
1266     Optional<int64_t> maybeConstantIndex = dimOp.getConstantIndex();
1267     auto initTensorOp = dimOp.source().getDefiningOp<linalg::InitTensorOp>();
1268     if (!initTensorOp || !maybeConstantIndex)
1269       return failure();
1270     if (!initTensorOp.isDynamicSize(*maybeConstantIndex))
1271       return failure();
1272     rewriter.replaceOp(dimOp, initTensorOp.getDynamicSize(*maybeConstantIndex));
1273     return success();
1274   }
1275 };
1276 
1277 /// Canonicalize
1278 ///
1279 /// ```mlir
1280 ///   %0 = linalg.init_tensor [%d0, %d1] : tensor<?x?xf32>
1281 ///   %1 = tensor.cast %0 : tensor<?x?xf32> to tensor<4x?xf32>
1282 /// ```
1283 ///
1284 /// into
1285 ///
1286 /// ```mlir
1287 ///   %0 = linalg.init_tensor [4, %d1] : tensor<4x?xf32>
1288 /// ```
1289 ///
1290 /// This assumes the input program is correct in terms of its shape. So it
1291 /// is safe to assume that `%d0` is in fact 4. If that was not the case, the
1292 /// input program is wrong to begin with, so its undefined behavior anyway (i.e.
1293 /// this optimization can still triggering without violating program semantics).
1294 struct FoldInitTensorWithTensorCastOp
1295     : public OpRewritePattern<tensor::CastOp> {
1296   using OpRewritePattern<tensor::CastOp>::OpRewritePattern;
1297 
1298   LogicalResult matchAndRewrite(tensor::CastOp castOp,
1299                                 PatternRewriter &rewriter) const override {
1300     if (!canFoldIntoProducerOp(castOp))
1301       return failure();
1302     auto producer = castOp.source().getDefiningOp<InitTensorOp>();
1303     if (!producer)
1304       return failure();
1305 
1306     auto resultType = castOp->getResult(0).getType().cast<RankedTensorType>();
1307     ArrayRef<int64_t> resultShape = resultType.getShape();
1308     SmallVector<OpFoldResult> currMixedSizes = producer.getMixedSizes();
1309     SmallVector<OpFoldResult> newMixedSizes;
1310     newMixedSizes.reserve(currMixedSizes.size());
1311     assert(resultShape.size() == currMixedSizes.size() &&
1312            "mismatch in result shape and sizes of init_tensor op");
1313     for (auto it : llvm::zip(resultShape, currMixedSizes)) {
1314       int64_t newDim = std::get<0>(it);
1315       OpFoldResult currDim = std::get<1>(it);
1316       // Case 1: The init tensor dim is static. Check that the tensor cast
1317       // result dim matches.
1318       if (auto attr = currDim.dyn_cast<Attribute>()) {
1319         if (ShapedType::isDynamic(newDim) ||
1320             newDim != attr.cast<IntegerAttr>().getInt()) {
1321           // Something is off, the cast result shape cannot be more dynamic than
1322           // the init tensor result shape (enforced by `canFoldIntoProducer`).
1323           // Abort for now.
1324           return rewriter.notifyMatchFailure(
1325               producer, "mismatch in static value of shape of init "
1326                         "tensor result and cast result");
1327         }
1328         newMixedSizes.push_back(attr);
1329         continue;
1330       }
1331 
1332       // Case 2 : The tensor cast shape is static, but init tensor result shape
1333       // is dynamic.
1334       if (!ShapedType::isDynamic(newDim)) {
1335         newMixedSizes.push_back(rewriter.getIndexAttr(newDim));
1336         continue;
1337       }
1338 
1339       // Case 3 : The tensor cast shape is dynamic and init tensor result shape
1340       // is dynamic. Use the dynamic value from the init tensor op.
1341       newMixedSizes.push_back(currDim);
1342     }
1343 
1344     rewriter.replaceOpWithNewOp<InitTensorOp>(castOp, newMixedSizes,
1345                                               resultType.getElementType());
1346     return success();
1347   }
1348 };
1349 
1350 } // namespace
1351 
1352 void InitTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
1353                                                MLIRContext *context) {
1354   results.add<FoldInitTensorWithTensorCastOp, FoldInitTensorWithDimOp,
1355               FoldInitTensorWithExtractSliceOp,
1356               FoldInitTensorWithTensorReshapeOp<tensor::ExpandShapeOp>,
1357               FoldInitTensorWithTensorReshapeOp<tensor::CollapseShapeOp>,
1358               ReplaceStaticShapeDims>(context);
1359 }
1360 
1361 LogicalResult InitTensorOp::reifyResultShapes(
1362     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1363   auto shapes = llvm::to_vector<4>(llvm::map_range(
1364       llvm::seq<int64_t>(0, getType().getRank()), [&](int64_t dim) -> Value {
1365         if (isDynamicSize(dim))
1366           return getDynamicSize(dim);
1367         return builder.create<arith::ConstantIndexOp>(getLoc(),
1368                                                       getStaticSize(dim));
1369       }));
1370   reifiedReturnShapes.emplace_back(std::move(shapes));
1371   return success();
1372 }
1373 
1374 //===----------------------------------------------------------------------===//
1375 // YieldOp
1376 //===----------------------------------------------------------------------===//
1377 
1378 void linalg::YieldOp::print(OpAsmPrinter &p) {
1379   if (getNumOperands() > 0)
1380     p << ' ' << getOperands();
1381   p.printOptionalAttrDict((*this)->getAttrs());
1382   if (getNumOperands() > 0)
1383     p << " : " << getOperandTypes();
1384 }
1385 
1386 ParseResult YieldOp::parse(OpAsmParser &parser, OperationState &result) {
1387   SmallVector<OpAsmParser::UnresolvedOperand, 2> opInfo;
1388   SmallVector<Type, 2> types;
1389   SMLoc loc = parser.getCurrentLocation();
1390   return failure(parser.parseOperandList(opInfo) ||
1391                  parser.parseOptionalAttrDict(result.attributes) ||
1392                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
1393                  parser.resolveOperands(opInfo, types, loc, result.operands));
1394 }
1395 
1396 // Check the operand number and types must match the element types of the
1397 // LinalgOp interface's shaped operands.
1398 static LogicalResult verifyYield(linalg::YieldOp op, LinalgOp linalgOp) {
1399   if (op.getNumOperands() != linalgOp.getNumOutputs())
1400     return op.emitOpError("expected number of yield values (")
1401            << linalgOp.getNumOutputs()
1402            << ") to match the number of operands of the enclosing "
1403            << "LinalgOp (" << op.getNumOperands() << ")";
1404 
1405   for (OpOperand &opOperand : op->getOpOperands()) {
1406     OpOperand *outputOperand =
1407         linalgOp.getOutputOperand(opOperand.getOperandNumber());
1408     Type elementType = getElementTypeOrSelf(outputOperand->get().getType());
1409     if (opOperand.get().getType() != elementType)
1410       return op.emitOpError("type of yield operand ")
1411              << (opOperand.getOperandNumber() + 1) << " ("
1412              << opOperand.get().getType() << ") doesn't match "
1413              << "the element type of the enclosing linalg.generic op ("
1414              << elementType << ")";
1415   }
1416   return success();
1417 }
1418 
1419 LogicalResult linalg::YieldOp::verify() {
1420   auto *parentOp = (*this)->getParentOp();
1421   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
1422     return emitOpError("expected single non-empty parent region");
1423 
1424   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
1425     return verifyYield(*this, linalgOp);
1426 
1427   return emitOpError("expected parent op with LinalgOp interface");
1428 }
1429 
1430 //===----------------------------------------------------------------------===//
1431 // IndexOp
1432 //===----------------------------------------------------------------------===//
1433 
1434 LogicalResult IndexOp::verify() {
1435   auto linalgOp = dyn_cast<LinalgOp>((*this)->getParentOp());
1436   if (!linalgOp)
1437     return emitOpError("expected parent op with LinalgOp interface");
1438   if (linalgOp.getNumLoops() <= dim())
1439     return emitOpError("expected dim (")
1440            << dim() << ") to be lower than the number of loops ("
1441            << linalgOp.getNumLoops() << ") of the enclosing LinalgOp";
1442   return success();
1443 }
1444 
1445 /////// Operations corresponding to library calls defined with Tablegen ////////
1446 
1447 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc"
1448 
1449 #define GET_OP_CLASSES
1450 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
1451 
1452 #define GET_OP_CLASSES
1453 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
1454 
1455 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
1456 /// Assumes `op` is a LinalgOp.
1457 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
1458                                  SmallVectorImpl<unsigned> &res) {
1459   if (!cast<LinalgOp>(op).iterator_types())
1460     return;
1461 
1462   unsigned dim = 0;
1463   for (auto tn :
1464        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
1465     if (tn == iteratorTypeName)
1466       res.push_back(dim);
1467     ++dim;
1468   }
1469 }
1470 
1471 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
1472                                              unsigned rank,
1473                                              MLIRContext *context) {
1474   if (maybeMap)
1475     return maybeMap.getValue();
1476   if (rank == 0)
1477     return AffineMap::get(context);
1478   return AffineMap::getMultiDimIdentityMap(rank, context);
1479 }
1480 
1481 SmallVector<AffineExpr, 4>
1482 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
1483                                  MLIRContext *context) {
1484   SmallVector<AffineExpr, 4> res;
1485   res.reserve(num);
1486   for (unsigned i = 0; i < num; ++i)
1487     res.push_back(getAffineDimExpr(startIdx++, context));
1488   return res;
1489 }
1490 
1491 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
1492                                                 ArrayRef<AffineExpr> b) {
1493   auto rangeA = llvm::make_range(a.begin(), a.end());
1494   auto rangeB = llvm::make_range(b.begin(), b.end());
1495   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
1496   return llvm::to_vector<4>(concatRanges);
1497 }
1498 
1499 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
1500   if (auto memref = t.dyn_cast<MemRefType>()) {
1501     ss << "view";
1502     for (auto size : memref.getShape())
1503       if (size < 0)
1504         ss << "sx";
1505       else
1506         ss << size << "x";
1507     appendMangledType(ss, memref.getElementType());
1508   } else if (auto vec = t.dyn_cast<VectorType>()) {
1509     ss << "vector";
1510     llvm::interleave(
1511         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
1512     appendMangledType(ss, vec.getElementType());
1513   } else if (t.isSignlessIntOrIndexOrFloat()) {
1514     ss << t;
1515   } else {
1516     llvm_unreachable("Invalid type for linalg library name mangling");
1517   }
1518 }
1519 
1520 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
1521   assert(isa<LinalgOp>(op));
1522   std::string name(op->getName().getStringRef().str());
1523   name.reserve(128);
1524   std::replace(name.begin(), name.end(), '.', '_');
1525   llvm::raw_string_ostream ss(name);
1526   ss << "_";
1527   auto types = op->getOperandTypes();
1528   llvm::interleave(
1529       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
1530       [&]() { ss << "_"; });
1531   return ss.str();
1532 }
1533 
1534 //===----------------------------------------------------------------------===//
1535 // Canonicalizers and Folders.
1536 //===----------------------------------------------------------------------===//
1537 
1538 namespace {
1539 struct EraseDeadLinalgOp : public OpInterfaceRewritePattern<LinalgOp> {
1540   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1541 
1542   LogicalResult matchAndRewrite(LinalgOp op,
1543                                 PatternRewriter &rewriter) const override {
1544     for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
1545       // Linalg "inputs" may be either tensor or memref type.
1546       // tensor<0xelt_type> is a convention that may not always mean
1547       // "0 iterations". Only erase in cases we see memref<...x0x...>.
1548       auto mt = opOperand->get().getType().dyn_cast<MemRefType>();
1549       if (!mt)
1550         continue;
1551       if (llvm::is_contained(op.getShape(opOperand), 0)) {
1552         rewriter.eraseOp(op);
1553         return success();
1554       }
1555     }
1556     return failure();
1557   }
1558 };
1559 
1560 struct FoldTensorCastProducerOp : public OpInterfaceRewritePattern<LinalgOp> {
1561   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1562 
1563   LogicalResult matchAndRewrite(LinalgOp op,
1564                                 PatternRewriter &rewriter) const override {
1565     // If no operand comes from a tensor::CastOp and can be folded then fail.
1566     bool hasTensorCastOperand =
1567         llvm::any_of(op.getInputAndOutputOperands(), [&](OpOperand *opOperand) {
1568           if (opOperand->get().isa<BlockArgument>())
1569             return false;
1570           auto castOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1571           return castOp && canFoldIntoConsumerOp(castOp);
1572         });
1573     if (!hasTensorCastOperand)
1574       return failure();
1575 
1576     SmallVector<Type, 4> newResultTypes;
1577     newResultTypes.reserve(op->getNumResults());
1578     SmallVector<Value, 4> newOperands;
1579     newOperands.reserve(op->getNumOperands());
1580     // Inputs may fold.
1581     for (OpOperand *opOperand : op.getInputOperands()) {
1582       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1583       newOperands.push_back(canFoldIntoConsumerOp(tensorCastOp)
1584                                 ? tensorCastOp.source()
1585                                 : opOperand->get());
1586     }
1587     // Init tensors may fold, in which case the resultType must also change.
1588     for (OpOperand *opOperand : op.getOutputOperands()) {
1589       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
1590       bool fold = canFoldIntoConsumerOp(tensorCastOp);
1591       newOperands.push_back(fold ? tensorCastOp.getOperand()
1592                                  : opOperand->get());
1593       newResultTypes.push_back(newOperands.back().getType());
1594     }
1595     // Clone op.
1596     Operation *newOp =
1597         op.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
1598     SmallVector<Value, 4> replacements;
1599     replacements.reserve(newOp->getNumResults());
1600     for (auto result : llvm::zip(op->getResults(), newOp->getResults())) {
1601       Value oldResult = std::get<0>(result);
1602       Value newResult = std::get<1>(result);
1603       if (newResult.getType() != oldResult.getType()) {
1604         replacements.push_back(rewriter.create<tensor::CastOp>(
1605             op->getLoc(), oldResult.getType(), newResult));
1606       } else {
1607         replacements.push_back(newResult);
1608       }
1609     }
1610     rewriter.replaceOp(op, replacements);
1611 
1612     return success();
1613   }
1614 };
1615 
1616 /// Fold LinalgOps with `tensor.cast` consumer if the `tensor.cast` has
1617 /// result that is more static than the linalg op.
1618 struct FoldTensorCastConsumerOp : public OpRewritePattern<tensor::CastOp> {
1619   using OpRewritePattern<tensor::CastOp>::OpRewritePattern;
1620 
1621   LogicalResult matchAndRewrite(tensor::CastOp castOp,
1622                                 PatternRewriter &rewriter) const override {
1623     if (!tensor::canFoldIntoProducerOp(castOp))
1624       return failure();
1625     auto linalgOp = castOp.source().getDefiningOp<LinalgOp>();
1626     if (!linalgOp)
1627       return failure();
1628 
1629     OpBuilder::InsertionGuard guard(rewriter);
1630     rewriter.setInsertionPoint(linalgOp);
1631 
1632     Location loc = linalgOp.getLoc();
1633     OpResult resultValue = castOp.source().cast<OpResult>();
1634     unsigned resultNumber = resultValue.getResultNumber();
1635     auto resultType = castOp->getResult(0).getType().cast<RankedTensorType>();
1636     // Replace the `outs` for the result with a `tensor.cast`. This cast is now
1637     // going from a more dynamic shape to a less dynamic shape. If the producer
1638     // for this cast, i.e. producer of the out operand, is also an operation
1639     // that folds with tensor.cast consumer (like this pattern), the cast will
1640     // continue to propagate as far up the stack as it can go.
1641     OpOperand *outOperand = linalgOp.getOutputOperand(resultNumber);
1642     Value newOperand =
1643         rewriter.create<tensor::CastOp>(loc, resultType, outOperand->get());
1644     SmallVector<Value> newOperands = linalgOp.getInputOperands();
1645     SmallVector<Value> outputOperands = linalgOp.getOutputOperands();
1646     outputOperands[resultNumber] = newOperand;
1647     newOperands.append(outputOperands.begin(), outputOperands.end());
1648 
1649     SmallVector<Type> resultTypes(linalgOp->result_type_begin(),
1650                                   linalgOp->result_type_end());
1651     resultTypes[resultNumber] = resultType;
1652     Operation *newOp = linalgOp.clone(rewriter, loc, resultTypes, newOperands);
1653 
1654     // Create a tensor.cast operation back to the original type.
1655     Value castBack = rewriter.create<tensor::CastOp>(
1656         loc, resultValue.getType(), newOp->getResult(resultNumber));
1657 
1658     SmallVector<Value> results(newOp->result_begin(), newOp->result_end());
1659     results[resultNumber] = castBack;
1660     rewriter.replaceOp(linalgOp, results);
1661     rewriter.replaceOp(castOp, newOp->getResult(resultNumber));
1662     return success();
1663   }
1664 };
1665 
1666 /// For each of the operand in `operands` this function maps the static sizes of
1667 /// dimensions to their affine dim expressions.
1668 static void populateMap(LinalgOp linalgOp, ArrayRef<OpOperand *> operands,
1669                         llvm::DenseMap<AffineExpr, int64_t> &affineExprToSize) {
1670   for (OpOperand *opOperand : operands) {
1671     if (linalgOp.isScalar(opOperand))
1672       continue;
1673     Value src = opOperand->get();
1674     auto sourceType = src.getType().cast<RankedTensorType>();
1675     auto sourceMap = linalgOp.getTiedIndexingMap(opOperand);
1676 
1677     // Get the `sourceShape` of the `sourceType`. If the operand is a result of
1678     // `tensor.cast` operation and source of the cast operation has a static
1679     // shape, then assign it to the `sourceShape`.
1680     auto *parentOp = src.getDefiningOp();
1681     ArrayRef<int64_t> sourceShape = sourceType.getShape();
1682     if (parentOp) {
1683       if (auto castOp = dyn_cast<tensor::CastOp>(parentOp)) {
1684         Value castSource = castOp.source();
1685         auto castSourceType = castSource.getType().cast<RankedTensorType>();
1686         if (castSourceType.hasStaticShape())
1687           sourceShape = castSourceType.getShape();
1688       }
1689     }
1690 
1691     // If the source shape's dimension has a static shape, map the affine dim
1692     // expression to the known static size.
1693     for (unsigned i = 0; i < sourceShape.size(); i++) {
1694       if (sourceType.isDynamicDim(i))
1695         continue;
1696       if (auto affineDimExpr = sourceMap.getResult(i).dyn_cast<AffineDimExpr>())
1697         affineExprToSize.try_emplace(affineDimExpr, sourceShape[i]);
1698     }
1699   }
1700 }
1701 
1702 /// Creates new operand w.r.t 'opOperand' of `linalgOp` with static sizes
1703 /// mapped in `affineExprToSize`. New operands are created in `newOperands` and
1704 /// their result types is stored in `resultTypes`. If `opOperand` requires no
1705 /// change then `changeNeeded` is false and same operand is added in the
1706 /// `newOperands` list.
1707 static void createNewOperandWithStaticSizes(
1708     Location loc, PatternRewriter &rewriter, OpOperand *opOperand,
1709     llvm::DenseMap<AffineExpr, int64_t> &affineExprToSize, LinalgOp linalgOp,
1710     SmallVector<Value> &newOperands, SmallVector<Type> &resultTypes,
1711     bool &changeNeeded) {
1712   Value src = opOperand->get();
1713   newOperands.push_back(src);
1714   if (linalgOp.isScalar(opOperand))
1715     return;
1716   auto sourceType = src.getType().cast<RankedTensorType>();
1717   Type resultType = sourceType;
1718   if (sourceType.hasStaticShape() && linalgOp.isOutputTensor(opOperand)) {
1719     resultTypes.push_back(resultType);
1720     return;
1721   }
1722   ArrayRef<int64_t> sourceShape = sourceType.getShape();
1723   AffineMap sourceMap = linalgOp.getTiedIndexingMap(opOperand);
1724   SmallVector<int64_t> newShape;
1725   // If operand is updated with new shape, `newOperandNeeded` will be
1726   // true.
1727   bool newOperandNeeded = false;
1728   for (unsigned i = 0; i < sourceShape.size(); i++) {
1729     int64_t dimShape = sourceShape[i];
1730     AffineExpr dimExpr = sourceMap.getResult(i);
1731     if (affineExprToSize.find(dimExpr) == affineExprToSize.end() ||
1732         !sourceType.isDynamicDim(i)) {
1733       newShape.push_back(dimShape);
1734       continue;
1735     }
1736     // Dimension has a dynamic shape and corresponding affine dim
1737     // expression is present in the map. So assign the size for the
1738     // given affine dim expression to the dimension.
1739     newShape.push_back(affineExprToSize[dimExpr]);
1740     newOperandNeeded = true;
1741   }
1742   resultType = RankedTensorType::get(newShape, sourceType.getElementType());
1743   if (newOperandNeeded) {
1744     changeNeeded = true;
1745     // Get the new operand value given its size and element type by
1746     // casting it.
1747     Value newOperand = rewriter.create<tensor::CastOp>(loc, resultType, src);
1748     unsigned index = opOperand->getOperandNumber();
1749     newOperands[index] = newOperand;
1750   }
1751   if (linalgOp.isOutputTensor(opOperand))
1752     resultTypes.push_back(resultType);
1753 }
1754 
1755 /// Static shapes for the operands can be inferred if any one of the operands
1756 /// have a static shape. This can be done by referring to the affine dim
1757 /// expressions for the operand.
1758 struct InferStaticShapeOfOperands : public OpInterfaceRewritePattern<LinalgOp> {
1759   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
1760 
1761   LogicalResult matchAndRewrite(LinalgOp linalgOp,
1762                                 PatternRewriter &rewriter) const override {
1763     if (!linalgOp.hasTensorSemantics())
1764       return failure();
1765 
1766     // Maps must be projected permutations.
1767     if (llvm::any_of(linalgOp.getIndexingMaps(), [](AffineMap map) {
1768           return !map.isProjectedPermutation();
1769         }))
1770       return failure();
1771 
1772     // Maps affine dim expressions to the static size of that dimension.
1773     llvm::DenseMap<AffineExpr, int64_t> affineExprToSize;
1774     Location loc = linalgOp.getLoc();
1775 
1776     // For each of the affine dim expression, check if the size is known. If
1777     // known add that in the map.
1778     populateMap(linalgOp, linalgOp.getInputAndOutputOperands(),
1779                 affineExprToSize);
1780 
1781     SmallVector<Value> newOperands;
1782     SmallVector<Type> resultTypes;
1783 
1784     // `changeNeeded` is `false` if the operands of `linalgOp` require no
1785     // change in their types.
1786     bool changeNeeded = false;
1787     newOperands.reserve(linalgOp.getNumInputsAndOutputs());
1788     resultTypes.reserve(linalgOp.getNumOutputs());
1789 
1790     // Iterate over all the operands and update the static sizes.
1791     for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
1792       createNewOperandWithStaticSizes(loc, rewriter, opOperand,
1793                                       affineExprToSize, linalgOp, newOperands,
1794                                       resultTypes, changeNeeded);
1795     }
1796 
1797     // If the generic op has all the required static information, no
1798     // canonicalization needed.
1799     if (!changeNeeded)
1800       return failure();
1801 
1802     // Clone op.
1803     Operation *newOp =
1804         linalgOp.clone(rewriter, linalgOp->getLoc(), resultTypes, newOperands);
1805     SmallVector<Value> replacements;
1806     replacements.reserve(newOp->getNumResults());
1807     for (auto it : llvm::zip(linalgOp->getResults(), newOp->getResults())) {
1808       Value newResult = std::get<1>(it);
1809       Value oldResult = std::get<0>(it);
1810       Type newType = newResult.getType();
1811       Type oldType = oldResult.getType();
1812       replacements.push_back(
1813           (newType != oldType)
1814               ? rewriter.create<tensor::CastOp>(loc, oldType, newResult)
1815               : newResult);
1816     }
1817     rewriter.replaceOp(linalgOp, replacements);
1818     return success();
1819   }
1820 };
1821 
1822 } // namespace
1823 
1824 // All named ops canonicalizers and folders are auto-generated in the
1825 // .cpp.inc.
1826 
1827 //===----------------------------------------------------------------------===//
1828 // LinalgDialect
1829 //===----------------------------------------------------------------------===//
1830 
1831 void LinalgDialect::getCanonicalizationPatterns(
1832     RewritePatternSet &results) const {
1833   results.add<EraseDeadLinalgOp, FoldTensorCastConsumerOp,
1834               FoldTensorCastProducerOp, InferStaticShapeOfOperands>(
1835       getContext());
1836 }
1837 
1838 Operation *LinalgDialect::materializeConstant(OpBuilder &builder,
1839                                               Attribute value, Type type,
1840                                               Location loc) {
1841   return builder.create<arith::ConstantOp>(loc, type, value);
1842 }
1843