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/LinalgOps.h"
14 
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Linalg/EDSC/Intrinsics.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/Dialect/StandardOps/IR/Ops.h"
20 #include "mlir/IR/AffineExprVisitor.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/OpImplementation.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "mlir/Interfaces/InferTypeOpInterface.h"
25 #include "mlir/Parser.h"
26 
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/StringSet.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 
35 using namespace mlir;
36 using namespace mlir::linalg;
37 
38 /// Forward declarations.
39 
40 /// Generic entry point to create the block for the region of a LinalgOp.
41 /// This is used by both named structured ops created by ods-gen and by manually
42 /// defined C++ ops.
43 /// This is used by both builders and parsers.
44 /// This function creates the block in the region with arguments corresponding
45 /// to the elemental types of `inputTypes` and `outputTypes`, which are asserted
46 /// to be ShapedType.
47 template <typename NamedStructuredOpType>
48 static void fillStructuredOpRegion(
49     OpBuilder &opBuilder, Region &region, TypeRange inputTypes,
50     TypeRange outputTypes, ValueRange captures = {},
51     std::function<void(unsigned, unsigned)> errorHandler = nullptr);
52 
53 /// Generic entry point to create both the region and the block of a LinalgOp.
54 template <typename NamedStructuredOpType>
55 static void
56 createAndFillStructuredOpRegion(OpBuilder &opBuilder, OperationState &result,
57                                 TypeRange inputTypes, TypeRange outputTypes,
58                                 ValueRange captures = {});
59 
60 /// Common parsing and printing used for both named structured ops created by
61 /// ods-gen and by manually defined C++ ops. Does not handle regions.
62 static ParseResult
63 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
64                              SmallVectorImpl<Type> &inputTypes,
65                              SmallVectorImpl<Type> &outputTypes);
66 template <typename NamedStructuredOpType>
67 static void printCommonStructuredOpParts(OpAsmPrinter &p,
68                                          NamedStructuredOpType op);
69 
70 /// Specific parsing and printing for named structured ops created by ods-gen.
71 template <typename NamedStructuredOpType>
72 static ParseResult
73 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
74                              TypeRange inputTypes, TypeRange outputTypes,
75                              ArrayRef<OpAsmParser::OperandType> captures = {});
76 
77 static ParseResult
78 parseNamedStructuredOpResults(OpAsmParser &parser,
79                               SmallVectorImpl<Type> &resultTypes);
80 
81 template <typename NamedStructuredOpType>
82 static ParseResult
83 parseNamedStructuredOp(OpAsmParser &parser, OperationState &result,
84                        ArrayRef<OpAsmParser::OperandType> captures = {});
85 
86 static void printNamedStructuredOpResults(OpAsmPrinter &p,
87                                           TypeRange resultTypes);
88 
89 template <typename NamedStructuredOpType>
90 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op);
91 
92 /// Helper function to convert a Value into an OpFoldResult, if the Value is
93 /// known to be a constant index value.
94 static SmallVector<OpFoldResult> getAsOpFoldResult(ArrayRef<Value> values) {
95   return llvm::to_vector<4>(
96       llvm::map_range(values, [](Value v) -> OpFoldResult {
97         APInt intValue;
98         if (v.getType().isa<IndexType>() &&
99             matchPattern(v, m_ConstantInt(&intValue))) {
100           return IntegerAttr::get(v.getType(), intValue.getSExtValue());
101         }
102         return v;
103       }));
104 }
105 
106 /// Helper function to convert a vector of `OpFoldResult`s into a vector of
107 /// `Value`s.
108 static SmallVector<Value> getAsValues(OpBuilder &b, Location loc,
109                                       ArrayRef<OpFoldResult> valueOrAttrVec) {
110   return llvm::to_vector<4>(
111       llvm::map_range(valueOrAttrVec, [&](OpFoldResult value) -> Value {
112         if (auto attr = value.dyn_cast<Attribute>())
113           return b.create<ConstantIndexOp>(loc,
114                                            attr.cast<IntegerAttr>().getInt());
115         return value.get<Value>();
116       }));
117 }
118 
119 /// Helper function to dispatch an OpFoldResult into either the `dynamicVec` if
120 /// it is a Value or into `staticVec` if it is an IntegerAttr.
121 /// In the case of a Value, a copy of the `sentinel` value is also pushed to
122 /// `staticVec`. This is useful to extract mixed static and dynamic entries that
123 /// come from an AttrSizedOperandSegments trait.
124 static void dispatchIndexOpFoldResult(OpFoldResult ofr,
125                                       SmallVectorImpl<Value> &dynamicVec,
126                                       SmallVectorImpl<int64_t> &staticVec,
127                                       int64_t sentinel) {
128   if (auto v = ofr.dyn_cast<Value>()) {
129     dynamicVec.push_back(v);
130     staticVec.push_back(sentinel);
131     return;
132   }
133   APInt apInt = ofr.dyn_cast<Attribute>().cast<IntegerAttr>().getValue();
134   staticVec.push_back(apInt.getSExtValue());
135 }
136 
137 /// This is a common class used for patterns of the form
138 /// ```
139 ///    someop(memrefcast(%src)) -> someop(%src)
140 /// ```
141 /// It folds the source of the memref.cast into the root operation directly.
142 static LogicalResult foldMemRefCast(Operation *op) {
143   bool folded = false;
144   for (OpOperand &operand : op->getOpOperands()) {
145     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
146     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
147       operand.set(castOp.getOperand());
148       folded = true;
149     }
150   }
151   return success(folded);
152 }
153 
154 /// This is a specialization of `foldMemRefCast` used for patterns of the form
155 /// ```
156 ///    tiled_loop(memrefcast(%src)) -> tiled_loop(%src)
157 /// ```
158 /// It folds the source of the memref.cast into the root operation directly.
159 static LogicalResult foldMemRefCastInTiledLoopOp(TiledLoopOp op) {
160   bool folded = false;
161   Location loc = op->getLoc();
162 
163   Block *body = op.getBody();
164   OpBuilder b = OpBuilder::atBlockBegin(body);
165 
166   // Update `input` and `output` operands and block arguments if necessary.
167   // Operands list: [lbs, ubs, steps, inputs, outputs].
168   // Block args list: [ivs, inputs, outputs].
169   for (size_t operandIndex = op.getNumControlOperands(),
170               bbArgIndex = op.getNumLoops(), e = op.getNumOperands();
171        operandIndex < e; ++operandIndex, ++bbArgIndex) {
172     OpOperand &operand = op->getOpOperand(operandIndex);
173 
174     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
175     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
176       operand.set(castOp.getOperand());
177       BlockArgument newBbArg =
178           body->insertArgument(bbArgIndex, castOp.getOperand().getType());
179       BlockArgument oldBbArg = body->getArgument(newBbArg.getArgNumber() + 1);
180 
181       // Insert memref.cast back to the original type.
182       oldBbArg.replaceAllUsesWith(
183           b.create<memref::CastOp>(loc, oldBbArg.getType(), newBbArg));
184       body->eraseArgument(oldBbArg.getArgNumber());
185 
186       folded = true;
187     }
188   }
189   return success(folded);
190 }
191 
192 //===----------------------------------------------------------------------===//
193 // Region builder helper.
194 // TODO: Move this to a utility library.
195 // The public methods on this class are referenced directly from generated code
196 // and bind by name to math functions in the DSL as:
197 //   `applyfn__{fnName}`
198 // Examples:
199 //   `applyfn__add`
200 //   `applyfn__mul`
201 // The naming convention is intentional in order to match snake-cased DSL names.
202 // See mlir-linalg-ods-yaml-gen.cpp for the code that mates to this class.
203 //
204 // Implementations of the math functions must be polymorphic over numeric types,
205 // internally performing necessary casts. If the function application makes no
206 // sense, then the only recourse is to assert and return nullptr. This can be
207 // extended later if it becomes possible to fail construction of the region. The
208 // invariant should be enforced at a higher level.
209 //
210 // TODO: These helpers are currently type polymorphic over the class of integer
211 // and floating point types, but they will not internally cast within bit
212 // widths of a class (mixed precision such as i8->i32) or across classes
213 // (i.e. mixed float and integer). Many such combinations are ambiguous or need
214 // to be handled with care and work is being considered to extend the op
215 // language to make such cases explicit. In the mean-time, violating this will
216 // fail verification, which is deemed acceptable.
217 //===----------------------------------------------------------------------===//
218 
219 namespace {
220 
221 class RegionBuilderHelper {
222 public:
223   RegionBuilderHelper(Block &block) : block(block) {}
224 
225   // Generates operations to cast the given operand to a specified type.
226   // If the cast cannot be performed, a warning will be issued and the
227   // operand returned as-is (which will presumably yield a verification
228   // issue downstream).
229   Value cast(Type toType, Value operand) {
230     OpBuilder builder = getBuilder(operand);
231     auto loc = operand.getLoc();
232 
233     if (operand.getType() == toType)
234       return operand;
235     if (auto toIntType = toType.dyn_cast<IntegerType>()) {
236       // If operand is floating point, cast directly to the int type.
237       if (operand.getType().isa<FloatType>())
238         return builder.create<FPToSIOp>(loc, toType, operand);
239       if (auto fromIntType = operand.getType().dyn_cast<IntegerType>()) {
240         // Either sign extend or truncate.
241         if (toIntType.getWidth() > fromIntType.getWidth())
242           return builder.create<SignExtendIOp>(loc, toType, operand);
243         else if (toIntType.getWidth() < fromIntType.getWidth())
244           return builder.create<TruncateIOp>(loc, toType, operand);
245       }
246     } else if (auto toFloatType = toType.dyn_cast<FloatType>()) {
247       // If operand is integer, cast directly to the float type.
248       // Note that it is unclear how to cast from BF16<->FP16.
249       if (operand.getType().isa<IntegerType>())
250         return builder.create<SIToFPOp>(loc, toFloatType, operand);
251       if (auto fromFloatType = operand.getType().dyn_cast<FloatType>()) {
252         if (toFloatType.getWidth() > fromFloatType.getWidth())
253           return builder.create<FPExtOp>(loc, toFloatType, operand);
254         else if (toFloatType.getWidth() < fromFloatType.getWidth())
255           return builder.create<FPTruncOp>(loc, toFloatType, operand);
256       }
257     }
258 
259     emitWarning(operand.getLoc()) << "could not cast operand of type "
260                                   << operand.getType() << " to " << toType;
261     return operand;
262   }
263 
264   Value applyfn__add(Value lhs, Value rhs) {
265     OpBuilder builder = getBuilder(lhs);
266     if (isFloatingPoint(lhs))
267       return builder.create<AddFOp>(lhs.getLoc(), lhs, rhs);
268     else if (isInteger(lhs))
269       return builder.create<AddIOp>(lhs.getLoc(), lhs, rhs);
270     llvm_unreachable("unsupported non numeric type");
271   }
272 
273   Value applyfn__mul(Value lhs, Value rhs) {
274     OpBuilder builder = getBuilder(lhs);
275     if (isFloatingPoint(lhs))
276       return builder.create<MulFOp>(lhs.getLoc(), lhs, rhs);
277     else if (isInteger(lhs))
278       return builder.create<MulIOp>(lhs.getLoc(), lhs, rhs);
279     llvm_unreachable("unsupported non numeric type");
280   }
281 
282   void yieldOutputs(ValueRange values) {
283     assert(!values.empty() && "linalg ops must yield outputs");
284     if (values.empty())
285       return;
286     Value first = values.front();
287     OpBuilder builder = getBuilder(first);
288     builder.create<YieldOp>(first.getLoc(), values);
289   }
290 
291 private:
292   Block &block;
293 
294   bool isFloatingPoint(Value value) { return value.getType().isa<FloatType>(); }
295   bool isInteger(Value value) { return value.getType().isa<IntegerType>(); }
296 
297   OpBuilder getBuilder(Value value) {
298     OpBuilder builder(value.getContext());
299     builder.setInsertionPointToEnd(&block);
300     return builder;
301   }
302 };
303 
304 } // namespace
305 
306 //===----------------------------------------------------------------------===//
307 // CopyOp
308 //===----------------------------------------------------------------------===//
309 void CopyOp::regionBuilder(Block &block, ValueRange captures) {
310   using namespace edsc::intrinsics;
311   assert(block.getNumArguments() == 2 && "CopyOp regionBuilder expects 2 args");
312   (linalg_yield(block.getArgument(0)));
313 }
314 
315 void CopyOp::build(OpBuilder &builder, OperationState &result, Value input,
316                    Value output, AffineMap inputPermutation,
317                    AffineMap outputPermutation,
318                    ArrayRef<NamedAttribute> namedAttrs) {
319   result.addOperands({input, output});
320   result.addAttributes(namedAttrs);
321   if (inputPermutation)
322     result.addAttribute("inputPermutation",
323                         AffineMapAttr::get(inputPermutation));
324   if (outputPermutation)
325     result.addAttribute("outputPermutation",
326                         AffineMapAttr::get(outputPermutation));
327   result.addRegion();
328   fillStructuredOpRegion<CopyOp>(builder, *result.regions.front(),
329                                  TypeRange{input.getType()},
330                                  TypeRange{output.getType()});
331 }
332 
333 ParseResult parseCopyOpRegion(OpAsmParser &parser, Region &r, Type inputType,
334                               Type outputType) {
335   OpBuilder opBuilder(parser.getBuilder().getContext());
336   fillStructuredOpRegion<CopyOp>(opBuilder, r, TypeRange{inputType},
337                                  TypeRange{outputType});
338   return success();
339 }
340 
341 /// CopyOp region is elided when printing.
342 void printCopyOpRegion(OpAsmPrinter &, Operation *, Region &, Type, Type) {}
343 
344 static LogicalResult verify(CopyOp op) {
345   auto outputViewType = op.getOutputShapedType(0);
346   auto inputViewType = op.getInputShapedType(0);
347   if (inputViewType.getElementType() != outputViewType.getElementType())
348     return op.emitOpError("expects views of the same type");
349   if (inputViewType.getRank() != outputViewType.getRank())
350     return op.emitOpError("expects views of the same rank");
351   auto rank = op.getNumParallelLoops();
352   auto inputPermutationMap = op.inputPermutation();
353   if (inputPermutationMap) {
354     if (inputPermutationMap->getNumInputs() != rank)
355       return op.emitOpError("expects optional input_permutation map of rank ")
356              << rank;
357     if (!inputPermutationMap->isPermutation())
358       return op.emitOpError(
359           "expects optional input_permutation map to be a permutation");
360   }
361   auto outputPermutationMap = op.outputPermutation();
362   if (outputPermutationMap) {
363     if (outputPermutationMap->getNumInputs() != rank)
364       return op.emitOpError("expects optional output_permutation map of rank ")
365              << rank;
366     if (!outputPermutationMap->isPermutation())
367       return op.emitOpError(
368           "expects optional output_permutation map to be a permutation");
369   }
370   if (rank == 0 && inputPermutationMap)
371     return op.emitOpError("expected no input permutation when rank == 0");
372   if (rank == 0 && outputPermutationMap)
373     return op.emitOpError("expected no output permutation when rank == 0");
374   return success();
375 }
376 
377 void CopyOp::getEffects(
378     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
379         &effects) {
380   effects.emplace_back(MemoryEffects::Read::get(), input(),
381                        SideEffects::DefaultResource::get());
382   effects.emplace_back(MemoryEffects::Write::get(), output(),
383                        SideEffects::DefaultResource::get());
384 }
385 
386 //===----------------------------------------------------------------------===//
387 // FillOp
388 //===----------------------------------------------------------------------===//
389 void FillOp::regionBuilder(Block &block, ValueRange captures) {
390   using namespace edsc::intrinsics;
391   assert(captures.size() == 1 && "FillOp regionBuilder expects 1 capture");
392   (linalg_yield(captures));
393 }
394 
395 void FillOp::build(OpBuilder &builder, OperationState &result, Value output,
396                    Value value) {
397   build(builder, result, output.getType().dyn_cast<RankedTensorType>(), output,
398         value);
399   fillStructuredOpRegion<FillOp>(builder, *result.regions.front(), TypeRange{},
400                                  TypeRange{output.getType()}, value);
401 }
402 
403 ParseResult parseFillOpRegion(OpAsmParser &parser, Region &r, Type outputType,
404                               OpAsmParser::OperandType valueRef) {
405   OpBuilder opBuilder(parser.getBuilder().getContext());
406   // Resolve `valueRef` into `value` at parse time so we can build the region
407   // with captures.
408   SmallVector<Value> value;
409   parser.resolveOperand(valueRef, getElementTypeOrSelf(outputType), value);
410   fillStructuredOpRegion<FillOp>(opBuilder, r, TypeRange{},
411                                  TypeRange{outputType}, value);
412   return success();
413 }
414 
415 /// FillOp region is elided when printing.
416 void printFillOpRegion(OpAsmPrinter &, Operation *, Region &, Type, Value) {}
417 
418 static LogicalResult verify(FillOp op) {
419   auto viewType = op.getOutputShapedType(0);
420   auto fillType = op.value().getType();
421   if (viewType.getElementType() != fillType)
422     return op.emitOpError("expects fill type to match view elemental type");
423   if (!op.getNumResults() && !viewType.isa<MemRefType>()) {
424     return op.emitOpError(
425         "expected fill op with no result value to use memref type");
426   }
427   return success();
428 }
429 
430 void FillOp::getEffects(
431     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
432         &effects) {
433   if (output().getType().isa<MemRefType>())
434     effects.emplace_back(MemoryEffects::Write::get(), output(),
435                          SideEffects::DefaultResource::get());
436 }
437 
438 //===----------------------------------------------------------------------===//
439 // GenericOps
440 //===----------------------------------------------------------------------===//
441 void GenericOp::build(
442     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
443     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
444     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
445     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
446   build(builder, result, resultTensorTypes, inputs, outputs,
447         builder.getAffineMapArrayAttr(indexingMaps),
448         builder.getStrArrayAttr(iteratorTypes),
449         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
450         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
451         ArrayAttr());
452   if (!bodyBuild)
453     return;
454 
455   SmallVector<Type, 4> blockArgTypes;
456   for (ValueRange container : {inputs, outputs})
457     for (Value v : container)
458       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
459 
460   OpBuilder::InsertionGuard guard(builder);
461   auto &region = *result.regions.front();
462   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
463   bodyBuild(builder, result.location, bodyBlock->getArguments());
464 }
465 
466 void GenericOp::build(
467     OpBuilder &builder, OperationState &result, ValueRange inputs,
468     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
469     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
470     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
471   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
472         iteratorTypes, doc, libraryCall, bodyBuild);
473 }
474 
475 void GenericOp::build(
476     OpBuilder &builder, OperationState &result, ValueRange inputs,
477     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
478     ArrayRef<StringRef> iteratorTypes,
479     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
480   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
481         /*doc=*/"",
482         /*libraryCall=*/"", bodyBuild);
483 }
484 
485 void GenericOp::build(
486     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
487     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
488     ArrayRef<StringRef> iteratorTypes,
489     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
490   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
491         iteratorTypes,
492         /*doc=*/"",
493         /*libraryCall=*/"", bodyBuild);
494 }
495 void IndexedGenericOp::build(
496     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
497     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
498     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
499     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
500         bodyBuild) {
501   build(builder, result, resultTensorTypes, inputs, outputs,
502         builder.getAffineMapArrayAttr(indexingMaps),
503         builder.getStrArrayAttr(iteratorTypes),
504         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
505         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
506         ArrayAttr());
507   if (!bodyBuild)
508     return;
509 
510   unsigned nLoops = iteratorTypes.size();
511   SmallVector<Type, 4> blockArgTypes(nLoops, builder.getIndexType());
512   for (ValueRange container : {inputs, outputs})
513     for (Value v : container)
514       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
515 
516   OpBuilder::InsertionGuard guard(builder);
517   auto &region = *result.regions.front();
518   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
519   bodyBuild(builder, result.location,
520             bodyBlock->getArguments().take_front(nLoops),
521             bodyBlock->getArguments().drop_front(nLoops));
522 }
523 
524 void IndexedGenericOp::build(
525     OpBuilder &builder, OperationState &result, ValueRange inputs,
526     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
527     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
528     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
529         bodyBuild) {
530   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
531         iteratorTypes, doc, libraryCall, bodyBuild);
532 }
533 
534 void IndexedGenericOp::build(
535     OpBuilder &builder, OperationState &result, ValueRange inputs,
536     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
537     ArrayRef<StringRef> iteratorTypes,
538     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
539         bodyBuild) {
540   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
541         /*doc=*/"", /*libraryCall=*/"", bodyBuild);
542 }
543 
544 void IndexedGenericOp::build(
545     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
546     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
547     ArrayRef<StringRef> iteratorTypes,
548     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
549         bodyBuild) {
550   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
551         iteratorTypes,
552         /*doc=*/"",
553         /*libraryCall=*/"", bodyBuild);
554 }
555 
556 template <typename GenericOpType>
557 static void printGenericOp(OpAsmPrinter &p, GenericOpType op) {
558   p << op.getOperationName() << " ";
559 
560   // Print extra attributes.
561   auto genericAttrNames = op.linalgTraitAttrNames();
562 
563   llvm::StringSet<> genericAttrNamesSet;
564   genericAttrNamesSet.insert(genericAttrNames.begin(), genericAttrNames.end());
565   SmallVector<NamedAttribute, 8> genericAttrs;
566   for (auto attr : op->getAttrs())
567     if (genericAttrNamesSet.count(attr.first.strref()) > 0)
568       genericAttrs.push_back(attr);
569   if (!genericAttrs.empty()) {
570     auto genericDictAttr = DictionaryAttr::get(op.getContext(), genericAttrs);
571     p << genericDictAttr;
572   }
573 
574   // Printing is shared with named ops, except for the region and attributes
575   printCommonStructuredOpParts(p, op);
576 
577   genericAttrNames.push_back("operand_segment_sizes");
578   genericAttrNamesSet.insert(genericAttrNames.back());
579 
580   bool hasExtraAttrs = false;
581   for (NamedAttribute n : op->getAttrs()) {
582     if ((hasExtraAttrs = !genericAttrNamesSet.contains(n.first.strref())))
583       break;
584   }
585   if (hasExtraAttrs) {
586     p << " attrs = ";
587     p.printOptionalAttrDict(op->getAttrs(), /*elidedAttrs=*/genericAttrNames);
588   }
589 
590   // Print region.
591   if (!op.region().empty())
592     p.printRegion(op.region());
593 
594   // Print results.
595   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
596 }
597 
598 static void print(OpAsmPrinter &p, GenericOp op) { printGenericOp(p, op); }
599 
600 static void print(OpAsmPrinter &p, IndexedGenericOp op) {
601   printGenericOp(p, op);
602 }
603 
604 static ParseResult parseGenericOp(OpAsmParser &parser, OperationState &result) {
605   DictionaryAttr dictAttr;
606   // Parse the core linalg traits that must check into a dictAttr.
607   // The name is unimportant as we will overwrite result.attributes.
608   // The core linalg traits must contain the information necessary to pass the
609   // verifier.
610   if (parser.parseAttribute(dictAttr, "_", result.attributes))
611     return failure();
612   result.attributes.assign(dictAttr.getValue().begin(),
613                            dictAttr.getValue().end());
614 
615   // Parsing is shared with named ops, except for the region.
616   SmallVector<Type, 1> inputTypes, outputTypes;
617   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
618     return failure();
619 
620   // Optional attributes may be added.
621   if (succeeded(parser.parseOptionalKeyword("attrs")))
622     if (failed(parser.parseEqual()) ||
623         failed(parser.parseOptionalAttrDict(result.attributes)))
624       return failure();
625 
626   SmallVector<OpAsmParser::OperandType, 8> regionOperands;
627   std::unique_ptr<Region> region = std::make_unique<Region>();
628   SmallVector<Type, 8> operandTypes, regionTypes;
629   if (parser.parseRegion(*region, regionOperands, regionTypes))
630     return failure();
631   result.addRegion(std::move(region));
632 
633   // Generic ops may specify that a subset of its outputs are tensors. Such
634   // outputs are specified in the result type.
635   // TODO: may need to move output parsing before region parsing.
636   // Need to wait for declarative assembly resolution to decide.
637   SmallVector<Type, 1> outputTensorsTypes;
638   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
639     return failure();
640   result.addTypes(outputTensorsTypes);
641 
642   return success();
643 }
644 
645 static void getGenericEffectsImpl(
646     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
647         &effects,
648     ValueRange results, ValueRange inputBuffers, ValueRange outputs) {
649   for (Value value : results) {
650     effects.emplace_back(MemoryEffects::Allocate::get(), value,
651                          SideEffects::DefaultResource::get());
652   }
653   for (Value value : inputBuffers) {
654     effects.emplace_back(MemoryEffects::Read::get(), value,
655                          SideEffects::DefaultResource::get());
656   }
657   for (Value value : outputs) {
658     effects.emplace_back(MemoryEffects::Read::get(), value,
659                          SideEffects::DefaultResource::get());
660     effects.emplace_back(MemoryEffects::Write::get(), value,
661                          SideEffects::DefaultResource::get());
662   }
663 }
664 
665 void GenericOp::getEffects(
666     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
667         &effects) {
668   getGenericEffectsImpl(effects, getOperation()->getResults(),
669                         getInputBuffers(), getOutputBuffers());
670 }
671 
672 void IndexedGenericOp::getEffects(
673     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
674         &effects) {
675   getGenericEffectsImpl(effects, getOperation()->getResults(),
676                         getInputBuffers(), getOutputBuffers());
677 }
678 
679 namespace {
680 
681 template <typename GenericOpType>
682 struct AnnotationsVerifier {
683   static LogicalResult verify(GenericOpType op) { return success(); }
684 };
685 
686 template <>
687 LogicalResult AnnotationsVerifier<GenericOp>::verify(GenericOp op) {
688   ArrayAttr sparseAttr = op.sparseAttr();
689   if (!sparseAttr)
690     return success();
691   // Verify consistency of sparse annotations.
692   if (!op.hasTensorSemantics())
693     return op.emitOpError("expected sparse annotations on tensors only");
694   if (op.getNumOutputs() != 1)
695     return op.emitOpError("expected single output tensor");
696   unsigned numTensors = op.getNumShapedOperands();
697   if (sparseAttr.size() != numTensors)
698     return op.emitOpError("expected one sparse annotation for each tensor");
699   for (unsigned t = 0; t < numTensors; t++) {
700     auto dimAttr = sparseAttr[t].dyn_cast_or_null<ArrayAttr>();
701     if (!dimAttr)
702       return op.emitOpError("expected sparse annotation array for tensor ")
703              << t;
704     unsigned rank = op.getShapedType(t).getRank();
705     if (dimAttr.size() != rank)
706       return op.emitOpError("expected sparse annotation with rank ")
707              << rank << " for tensor " << t;
708     // Per-dimension annotations for each tensor consist of only "D" or "S".
709     for (unsigned d = 0; d < rank; d++) {
710       if (isDenseDim(dimAttr[d])) {
711         continue;
712       } else if (isSparseDim(dimAttr[d])) {
713         if (t == numTensors - 1)
714           return op.emitOpError("sparse output tensors not supported (yet)");
715         continue;
716       }
717       return op.emitOpError("expected sparse annotation at position ")
718              << d << " for tensor " << t;
719     }
720   }
721   return success();
722 }
723 
724 } // namespace
725 
726 template <typename GenericOpType>
727 static LogicalResult verifyGenericOp(GenericOpType op) {
728   if (failed(AnnotationsVerifier<GenericOpType>::verify(op)))
729     return failure();
730 
731   return success();
732 }
733 
734 static LogicalResult verify(GenericOp op) { return verifyGenericOp(op); }
735 
736 static LogicalResult verify(IndexedGenericOp op) { return verifyGenericOp(op); }
737 
738 namespace {
739 
740 /// Replace indexed_generic ops by generic ops that access the iteration indices
741 /// using index operation calls.
742 struct ConvertIndexedToGenericOp : OpRewritePattern<IndexedGenericOp> {
743   using OpRewritePattern<IndexedGenericOp>::OpRewritePattern;
744   LogicalResult matchAndRewrite(IndexedGenericOp indexedOp,
745                                 PatternRewriter &rewriter) const override {
746     // Replace all uses of the index block arguments.
747     BlockAndValueMapping bvm;
748     if (Block *body = indexedOp.getBody()) {
749       rewriter.setInsertionPointToStart(body);
750       for (const auto &en : llvm::enumerate(
751                body->getArguments().take_front(indexedOp.getNumLoops()))) {
752         Value index = rewriter.create<IndexOp>(indexedOp.getLoc(), en.index());
753         bvm.map(en.value(), index);
754       }
755     }
756 
757     // Create a generic replacement operation and clone the body.
758     rewriter.setInsertionPointAfter(indexedOp);
759     SmallVector<StringRef> iterators = llvm::to_vector<4>(
760         indexedOp.iterator_types().getAsValueRange<StringAttr>());
761     GenericOp genericOp = rewriter.create<GenericOp>(
762         indexedOp.getLoc(), indexedOp->getResultTypes(), indexedOp.getInputs(),
763         indexedOp.getOutputs(), indexedOp.getIndexingMaps(), iterators);
764     Region &genericRegion = genericOp.region();
765     Region &indexedRegion = indexedOp.region();
766     rewriter.cloneRegionBefore(indexedRegion, genericRegion,
767                                genericRegion.begin(), bvm);
768 
769     rewriter.replaceOp(indexedOp, genericOp->getResults());
770     return success();
771   }
772 };
773 } // namespace
774 
775 void IndexedGenericOp::getCanonicalizationPatterns(RewritePatternSet &results,
776                                                    MLIRContext *context) {
777   results.add<ConvertIndexedToGenericOp>(context);
778 }
779 
780 //===----------------------------------------------------------------------===//
781 // InitTensorOp
782 //===----------------------------------------------------------------------===//
783 void InitTensorOp::build(OpBuilder &b, OperationState &result,
784                          ArrayRef<OpFoldResult> sizes, Type elementType,
785                          ArrayRef<NamedAttribute> attrs) {
786   unsigned rank = sizes.size();
787   SmallVector<Value, 4> dynamicSizes;
788   SmallVector<int64_t, 4> staticSizes;
789   for (unsigned i = 0; i < rank; ++i) {
790     dispatchIndexOpFoldResult(sizes[i], dynamicSizes, staticSizes,
791                               ShapedType::kDynamicSize);
792   }
793   auto resultType = RankedTensorType ::get(staticSizes, elementType);
794   build(b, result, resultType, dynamicSizes, b.getI64ArrayAttr(staticSizes));
795   result.addAttributes(attrs);
796 }
797 
798 static LogicalResult verify(InitTensorOp op) {
799   RankedTensorType resultType = op.getType();
800   SmallVector<int64_t, 4> staticSizes = llvm::to_vector<4>(llvm::map_range(
801       op.static_sizes().cast<ArrayAttr>(),
802       [](Attribute a) -> int64_t { return a.cast<IntegerAttr>().getInt(); }));
803 
804   if (failed(verifyListOfOperandsOrIntegers(op, "sizes", resultType.getRank(),
805                                             op.static_sizes(), op.sizes(),
806                                             ShapedType::isDynamic)))
807     return failure();
808 
809   if (op.static_sizes().size() != static_cast<unsigned>(resultType.getRank()))
810     return op->emitError("expected ")
811            << resultType.getRank() << " sizes values";
812 
813   Type expectedType =
814       InitTensorOp::inferResultType(staticSizes, resultType.getElementType());
815   if (resultType != expectedType) {
816     return op.emitError("specified type ")
817            << resultType << " does not match the inferred type "
818            << expectedType;
819   }
820   return success();
821 }
822 
823 Type InitTensorOp::inferResultType(ArrayRef<int64_t> staticSizes,
824                                    Type elementType) {
825   return RankedTensorType::get(staticSizes, elementType);
826 }
827 
828 namespace {
829 /// Change the type of the result of a `linalg.init_tensor` by making the result
830 /// type statically sized along dimension that in the original operation where
831 /// defined as dynamic, but the size was defined using a `constant` op. For
832 /// example
833 ///
834 ///  %c5 = constant 5: index
835 ///  %0 = linalg.init_tensor [%arg0, %c5] : tensor<?x?xf32>
836 ///
837 ///  to
838 ///
839 ///  %0 = linalg.init_tensor [%arg0, 5] : tensor<?x5xf32>
840 struct ReplaceStaticShapeDims : OpRewritePattern<InitTensorOp> {
841   using OpRewritePattern<InitTensorOp>::OpRewritePattern;
842 
843   LogicalResult matchAndRewrite(InitTensorOp op,
844                                 PatternRewriter &rewriter) const override {
845     SmallVector<Value, 4> dynamicSizes;
846     SmallVector<int64_t, 4> staticSizes;
847     for (unsigned i = 0, e = op.getType().getRank(); i != e; ++i) {
848       // If the size is already static, nothing to do.
849       if (!op.isDynamicSize(i)) {
850         staticSizes.push_back(op.getStaticSize(i));
851         continue;
852       }
853 
854       // If the size is dynamic but defined using a `constant` op, get the
855       // constant value to find the static size to use.
856       unsigned operandNum = op.getIndexOfDynamicSize(i);
857       Value sizeOperand = op.getOperand(operandNum);
858       if (auto constantIndexOp = sizeOperand.getDefiningOp<ConstantIndexOp>()) {
859         staticSizes.push_back(constantIndexOp.getValue());
860         continue;
861       }
862 
863       // Fallback case. Keep the size dynamic.
864       dynamicSizes.push_back(sizeOperand);
865       staticSizes.push_back(ShapedType::kDynamicSize);
866     }
867     RankedTensorType newType =
868         RankedTensorType::get(staticSizes, op.getType().getElementType());
869     if (newType == op.getType())
870       return failure();
871     auto newOp =
872         rewriter.create<InitTensorOp>(op.getLoc(), newType, dynamicSizes,
873                                       rewriter.getI64ArrayAttr(staticSizes));
874     rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
875     return success();
876   }
877 };
878 } // namespace
879 
880 namespace {
881 /// Since `init_tensor` operation creates a tensor needed only for its shape, a
882 /// subtensor of this is also needed only for its shape. The result can be
883 /// replaced by a new init_tensor operation of the same size as the subtensor
884 /// op.
885 struct FoldInitTensorWithSubTensorOp : public OpRewritePattern<SubTensorOp> {
886   using OpRewritePattern<SubTensorOp>::OpRewritePattern;
887 
888   LogicalResult matchAndRewrite(SubTensorOp subtensorOp,
889                                 PatternRewriter &rewriter) const override {
890     if (!subtensorOp.source().getDefiningOp<linalg::InitTensorOp>())
891       return failure();
892     rewriter.replaceOpWithNewOp<linalg::InitTensorOp>(
893         subtensorOp, subtensorOp.sizes(),
894         llvm::to_vector<4>(llvm::map_range(
895             subtensorOp.static_sizes(),
896             [](Attribute attr) { return attr.cast<IntegerAttr>().getInt(); })),
897         subtensorOp.getSourceType().getElementType());
898     return success();
899   }
900 };
901 
902 struct FoldInitTensorWithTensorReshapeOp
903     : public OpRewritePattern<TensorReshapeOp> {
904   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
905 
906   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
907                                 PatternRewriter &rewriter) const override {
908     if (!reshapeOp.src().getDefiningOp<InitTensorOp>())
909       return failure();
910     Location loc = reshapeOp.getLoc();
911     SmallVector<SmallVector<Value>, 4> resultShapes;
912     if (failed(reshapeOp.reifyReturnTypeShapesPerResultDim(rewriter,
913                                                            resultShapes)) ||
914         !llvm::hasSingleElement(resultShapes))
915       return failure();
916     Value initTensor = rewriter.create<InitTensorOp>(
917         loc, getAsOpFoldResult(resultShapes[0]),
918         reshapeOp.getResultType().getElementType());
919     if (initTensor.getType() != reshapeOp.getResultType()) {
920       rewriter.replaceOpWithNewOp<tensor::CastOp>(
921           reshapeOp, reshapeOp.getResultType(), initTensor);
922     } else {
923       rewriter.replaceOp(reshapeOp, initTensor);
924     }
925     return success();
926   }
927 };
928 } // namespace
929 
930 void InitTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
931                                                MLIRContext *context) {
932   results.add<FoldInitTensorWithSubTensorOp, FoldInitTensorWithTensorReshapeOp,
933               ReplaceStaticShapeDims>(context);
934 }
935 
936 LogicalResult InitTensorOp::reifyReturnTypeShapesPerResultDim(
937     OpBuilder &builder,
938     SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
939   auto shapes = llvm::to_vector<4>(llvm::map_range(
940       llvm::seq<int64_t>(0, getType().getRank()), [&](int64_t dim) -> Value {
941         if (isDynamicSize(dim))
942           return getDynamicSize(dim);
943         return builder.create<ConstantIndexOp>(getLoc(), getStaticSize(dim));
944       }));
945   reifiedReturnShapes.emplace_back(std::move(shapes));
946   return success();
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // PadTensorOp
951 //===----------------------------------------------------------------------===//
952 
953 /// Extract int64_t values from the assumed ArrayAttr of IntegerAttr.
954 static SmallVector<int64_t, 4> extractFromI64ArrayAttr(Attribute attr) {
955   return llvm::to_vector<4>(
956       llvm::map_range(attr.cast<ArrayAttr>(), [](Attribute a) -> int64_t {
957         return a.cast<IntegerAttr>().getInt();
958       }));
959 }
960 
961 static LogicalResult verify(PadTensorOp op) {
962   auto sourceType = op.source().getType().cast<RankedTensorType>();
963   auto resultType = op.result().getType().cast<RankedTensorType>();
964   auto expectedType = PadTensorOp::inferResultType(
965       sourceType, extractFromI64ArrayAttr(op.static_low()),
966       extractFromI64ArrayAttr(op.static_high()));
967   for (int i = 0, e = sourceType.getRank(); i < e; ++i) {
968     if (resultType.getDimSize(i) == expectedType.getDimSize(i))
969       continue;
970     if (expectedType.isDynamicDim(i))
971       continue;
972     return op.emitError("specified type ")
973            << resultType << " does not match the inferred type "
974            << expectedType;
975   }
976 
977   auto &region = op.region();
978   unsigned rank = resultType.getRank();
979   Block &block = region.front();
980   if (block.getNumArguments() != rank)
981     return op.emitError("expected the block to have ") << rank << " arguments";
982 
983   // Note: the number and type of yield values are checked in the YieldOp.
984   for (auto en : llvm::enumerate(block.getArgumentTypes())) {
985     if (!en.value().isIndex())
986       return op.emitOpError("expected block argument ")
987              << (en.index() + 1) << " to be an index";
988   }
989 
990   return success();
991 }
992 
993 RankedTensorType PadTensorOp::inferResultType(RankedTensorType sourceType,
994                                               ArrayRef<int64_t> staticLow,
995                                               ArrayRef<int64_t> staticHigh) {
996   unsigned rank = sourceType.getRank();
997   assert(staticLow.size() == rank && "unexpected staticLow size mismatch");
998   assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch");
999 
1000   SmallVector<int64_t, 4> resultShape;
1001   for (auto i : llvm::seq<unsigned>(0, rank)) {
1002     if (sourceType.isDynamicDim(i) ||
1003         staticLow[i] == ShapedType::kDynamicSize ||
1004         staticHigh[i] == ShapedType::kDynamicSize) {
1005       resultShape.push_back(ShapedType::kDynamicSize);
1006     } else {
1007       int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i];
1008       resultShape.push_back(size);
1009     }
1010   }
1011 
1012   return RankedTensorType::get(resultShape, sourceType.getElementType());
1013 }
1014 
1015 void PadTensorOp::build(OpBuilder &b, OperationState &result, Value source,
1016                         ArrayRef<int64_t> staticLow,
1017                         ArrayRef<int64_t> staticHigh, ValueRange low,
1018                         ValueRange high, ArrayRef<NamedAttribute> attrs) {
1019   auto sourceType = source.getType().cast<RankedTensorType>();
1020   auto resultType = inferResultType(sourceType, staticLow, staticHigh);
1021   build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow),
1022         b.getI64ArrayAttr(staticHigh));
1023   result.addAttributes(attrs);
1024 }
1025 
1026 void PadTensorOp::build(OpBuilder &b, OperationState &result, Value source,
1027                         ValueRange low, ValueRange high,
1028                         ArrayRef<NamedAttribute> attrs) {
1029   auto sourceType = source.getType().cast<RankedTensorType>();
1030   unsigned rank = sourceType.getRank();
1031   SmallVector<int64_t, 4> staticVector(ShapedType::kDynamicSize, rank);
1032   build(b, result, source, staticVector, staticVector, low, high, attrs);
1033 }
1034 
1035 void PadTensorOp::build(OpBuilder &b, OperationState &result, Type resultType,
1036                         Value source, ArrayRef<OpFoldResult> low,
1037                         ArrayRef<OpFoldResult> high,
1038                         ArrayRef<NamedAttribute> attrs) {
1039   assert(resultType.isa<RankedTensorType>());
1040   auto sourceType = source.getType().cast<RankedTensorType>();
1041   unsigned rank = sourceType.getRank();
1042   SmallVector<Value, 4> dynamicLow, dynamicHigh;
1043   SmallVector<int64_t, 4> staticLow, staticHigh;
1044   for (unsigned i = 0; i < rank; ++i) {
1045     // staticLow and staticHigh have full information of the padding config.
1046     // This will grow staticLow and staticHigh with 1 value. If the config is
1047     // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1
1048     // value as well.
1049     dispatchIndexOpFoldResult(low[i], dynamicLow, staticLow,
1050                               ShapedType::kDynamicSize);
1051     dispatchIndexOpFoldResult(high[i], dynamicHigh, staticHigh,
1052                               ShapedType::kDynamicSize);
1053   }
1054   if (!resultType) {
1055     resultType =
1056         PadTensorOp::inferResultType(sourceType, staticLow, staticHigh);
1057   }
1058   build(b, result, resultType, source, dynamicLow, dynamicHigh,
1059         b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh));
1060 }
1061 
1062 PadTensorOp PadTensorOp::createPadScalarOp(Type type, Value source, Value pad,
1063                                            ArrayRef<OpFoldResult> low,
1064                                            ArrayRef<OpFoldResult> high,
1065                                            Location loc, OpBuilder &builder) {
1066   auto padTensorOp =
1067       builder.create<linalg::PadTensorOp>(loc, type, source, low, high);
1068   int rank = padTensorOp.getResultType().getRank();
1069   SmallVector<Type, 4> blockArgTypes;
1070   blockArgTypes.assign(rank, builder.getIndexType());
1071   auto &region = padTensorOp.region();
1072   // `builder.createBlock` changes the insertion point within the block. Create
1073   // a guard to reset the insertion point of the builder after it is destroyed.
1074   OpBuilder::InsertionGuard guard(builder);
1075   builder.createBlock(&region, region.end(), blockArgTypes);
1076   builder.create<linalg::YieldOp>(loc, pad);
1077   return padTensorOp;
1078 }
1079 
1080 PadTensorOp PadTensorOp::createPadHighOp(Type type, Value source, Value pad,
1081                                          Location loc, OpBuilder &builder) {
1082   SmallVector<OpFoldResult, 4> low, high;
1083   auto rankedTensorType = type.cast<RankedTensorType>();
1084   assert(rankedTensorType.hasStaticShape());
1085   int rank = rankedTensorType.getRank();
1086   for (int i = 0; i < rank; ++i) {
1087     auto dimOp = builder.createOrFold<memref::DimOp>(loc, source, i);
1088     auto resultDimSize = builder.createOrFold<ConstantIndexOp>(
1089         loc, rankedTensorType.getDimSize(i));
1090     auto highValue = builder.createOrFold<SubIOp>(loc, resultDimSize, dimOp);
1091     high.push_back(highValue);
1092     low.push_back(builder.createOrFold<ConstantIndexOp>(loc, 0));
1093   }
1094   return PadTensorOp::createPadScalarOp(type, source, pad, low, high, loc,
1095                                         builder);
1096 }
1097 
1098 LogicalResult PadTensorOp::reifyReturnTypeShapesPerResultDim(
1099     OpBuilder &b, SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
1100   Location loc = getLoc();
1101   auto lowPad = getMixedLowPad();
1102   auto highPad = getMixedHighPad();
1103   SmallVector<Value> shapes;
1104   for (auto dim : llvm::seq<int64_t>(0, getSourceType().getRank())) {
1105     // Shape along each dimension is source dim + low pad + high pad.
1106     SmallVector<Value> mapOperands;
1107     mapOperands.push_back(b.createOrFold<memref::DimOp>(loc, source(), dim));
1108     AffineExpr expr = b.getAffineDimExpr(0);
1109     unsigned numSymbols = 0;
1110     auto addOpFoldResult = [&](OpFoldResult valueOrAttr) {
1111       if (Value v = valueOrAttr.dyn_cast<Value>()) {
1112         expr = expr + b.getAffineSymbolExpr(numSymbols++);
1113         mapOperands.push_back(v);
1114         return;
1115       }
1116       int64_t staticValue =
1117           valueOrAttr.get<Attribute>().cast<IntegerAttr>().getInt();
1118       expr = expr + staticValue;
1119     };
1120     addOpFoldResult(lowPad[dim]);
1121     addOpFoldResult(highPad[dim]);
1122     shapes.push_back(applyMapToValues(
1123         b, loc, AffineMap::get(1, numSymbols, expr), mapOperands)[0]);
1124   }
1125   reifiedReturnShapes.emplace_back(std::move(shapes));
1126   return success();
1127 }
1128 
1129 //===----------------------------------------------------------------------===//
1130 // ReshapeOp
1131 //===----------------------------------------------------------------------===//
1132 
1133 Optional<SmallVector<ReassociationIndices>>
1134 mlir::linalg::getReassociationIndicesForReshape(ShapedType sourceType,
1135                                                 ShapedType targetType) {
1136   // Make the sourceType greater rank than the targetType. If they are same
1137   // rank, then its an unsupported reshape op.
1138   if (sourceType.getRank() == targetType.getRank())
1139     return llvm::None;
1140   if (sourceType.getRank() < targetType.getRank())
1141     std::swap(sourceType, targetType);
1142 
1143   ArrayRef<int64_t> sourceShape = sourceType.getShape();
1144   ArrayRef<int64_t> targetShape = targetType.getShape();
1145   unsigned sourceDim = 0;
1146   SmallVector<ReassociationIndices> reassociationMap;
1147   reassociationMap.reserve(targetType.getRank());
1148 
1149   ReassociationIndices currIndices;
1150   int64_t prodOfCollapsedDims = 1;
1151   while (sourceDim < sourceShape.size()) {
1152     unsigned targetDim = reassociationMap.size();
1153 
1154     // If all the dimensions of the targetShape are exhausted, then the
1155     // remaining dims in the source shape must be all 1s. So for such cases, set
1156     // 1 as the target shape. The actual reassociation indices will be handled
1157     // later.
1158     int64_t currTargetShape =
1159         (targetDim < targetType.getRank() ? targetShape[targetDim] : 1);
1160     while (sourceShape[sourceDim] != ShapedType::kDynamicSize &&
1161            prodOfCollapsedDims * sourceShape[sourceDim] < currTargetShape &&
1162            sourceDim < sourceShape.size()) {
1163       prodOfCollapsedDims *= sourceShape[sourceDim];
1164       currIndices.push_back(sourceDim++);
1165     }
1166 
1167     // If the current expanded dimension is dynamic, then the collapsed
1168     // dimensions should also be dynamic and product of all previous unprocessed
1169     // dimensions of the expanded shape should be 1.
1170     if (sourceShape[sourceDim] == ShapedType::kDynamicSize &&
1171         (currTargetShape != ShapedType::kDynamicSize ||
1172          prodOfCollapsedDims != 1))
1173       return llvm::None;
1174 
1175     // If the collapsed dim is dynamic, the current expanded dim should also
1176     // be dynamic.
1177     if (currTargetShape == ShapedType::kDynamicSize &&
1178         sourceShape[sourceDim] != ShapedType::kDynamicSize)
1179       return llvm::None;
1180 
1181     // For static shapes, if the product of dimensions of the expanded shape
1182     // should match the collapsed dimension shape.
1183     if (prodOfCollapsedDims * sourceShape[sourceDim] != currTargetShape)
1184       return llvm::None;
1185 
1186     currIndices.push_back(sourceDim++);
1187     // If there are no dimensions in the target to match, then append the
1188     // `currIndices` to the last element of the reassociationMap.
1189     if (targetDim == targetShape.size()) {
1190       reassociationMap.back().append(currIndices.begin(), currIndices.end());
1191       // Break out of the loops. We should be done here.
1192       break;
1193     }
1194     reassociationMap.emplace_back(ReassociationIndices{});
1195     std::swap(reassociationMap.back(), currIndices);
1196     prodOfCollapsedDims = 1;
1197   }
1198   // All the dimensions in the two shapes must have been processed.
1199   if (reassociationMap.size() != targetShape.size() ||
1200       sourceDim != sourceShape.size())
1201     return llvm::None;
1202   return reassociationMap;
1203 }
1204 
1205 template <typename ReshapeLikeOp>
1206 static void print(OpAsmPrinter &p, ReshapeLikeOp op) {
1207   p << op.getOperationName() << ' ' << op.src() << " [";
1208 
1209   llvm::interleaveComma(op.reassociation(), p, [&](const Attribute &attr) {
1210     p << '[';
1211     auto arrayAttr = attr.template cast<ArrayAttr>();
1212     llvm::interleaveComma(arrayAttr, p, [&](const Attribute &attr) {
1213       p << attr.cast<IntegerAttr>().getInt();
1214     });
1215     p << ']';
1216   });
1217 
1218   p << "] ";
1219   p.printOptionalAttrDict(op->getAttrs(),
1220                           /*elidedAttrs=*/{op.getReassociationAttrName()});
1221   p << ": " << op.src().getType() << " into " << op.getType();
1222 }
1223 
1224 static void print(OpAsmPrinter &p, linalg::ReshapeOp op) {
1225   print<linalg::ReshapeOp>(p, op);
1226 }
1227 
1228 static void print(OpAsmPrinter &p, linalg::TensorReshapeOp op) {
1229   print<linalg::TensorReshapeOp>(p, op);
1230 }
1231 
1232 static ParseResult parseReshapeLikeOp(OpAsmParser &parser,
1233                                       OperationState &result) {
1234   // Parse the operand.
1235   OpAsmParser::OperandType src;
1236   if (parser.parseOperand(src))
1237     return failure();
1238 
1239   // Parse reassociation indices.
1240   Builder &b = parser.getBuilder();
1241   SmallVector<Attribute, 4> reassociation;
1242   if (parser.parseLSquare())
1243     return failure();
1244 
1245   while (true) {
1246     if (succeeded(parser.parseOptionalRSquare()))
1247       break;
1248     if (parser.parseLSquare())
1249       return failure();
1250     SmallVector<int64_t> indices;
1251     while (true) {
1252       int64_t index;
1253       if (parser.parseInteger(index))
1254         return failure();
1255       indices.push_back(index);
1256 
1257       if (succeeded(parser.parseOptionalComma()))
1258         continue;
1259       if (failed(parser.parseRSquare()))
1260         return failure();
1261       break;
1262     }
1263     reassociation.push_back(b.getI64ArrayAttr(indices));
1264     if (succeeded(parser.parseOptionalComma()))
1265       continue;
1266     if (failed(parser.parseRSquare()))
1267       return failure();
1268     break;
1269   }
1270 
1271   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1272                       b.getArrayAttr(reassociation));
1273 
1274   // Parse optional attributes.
1275   parser.parseOptionalAttrDict(result.attributes);
1276 
1277   // Parse types.
1278   Type srcType;
1279   Type resultType;
1280   if (parser.parseColon() || parser.parseType(srcType) ||
1281       parser.resolveOperand(src, srcType, result.operands) ||
1282       parser.parseKeyword("into") || parser.parseType(resultType))
1283     return failure();
1284   result.addTypes(resultType);
1285   return success();
1286 }
1287 
1288 /// Collapse reassociation maps that are used in pair of reshape ops where one
1289 /// is a producer and other is the consumer. Only valid to use this method when
1290 /// both the producer and consumer are collapsing dimensions or both are
1291 /// expanding dimensions.
1292 ///
1293 /// For example,
1294 ///   mapsProducer = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1)>,
1295 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d2)>,
1296 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
1297 ///   mapsConsumer = [affine_map<(d0, d1, d2) -> (d0, d1)>,
1298 ///                   affine_map<(d0, d1, d2) -> (d2)>]
1299 ///
1300 /// is folded into
1301 ///
1302 ///   result = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1, d2)>,
1303 ///             affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
1304 static Optional<SmallVector<ReassociationIndices>>
1305 collapseReassociationIndices(ArrayRef<AffineMap> mapsProducer,
1306                              ArrayRef<AffineMap> mapsConsumer,
1307                              MLIRContext *context) {
1308   // Make the producer the larger sized vector. If they are of same size, the
1309   // resulting reshape is not a supported reshape op.
1310   if (mapsProducer.size() == mapsConsumer.size())
1311     return llvm::None;
1312   if (mapsProducer.size() < mapsConsumer.size())
1313     std::swap(mapsProducer, mapsConsumer);
1314 
1315   // Handle the corner case of the result being a rank 0 shaped type. Return an
1316   // empty reassociation.
1317   if (mapsConsumer.empty())
1318     return SmallVector<ReassociationIndices>{};
1319   if (mapsProducer.size() != mapsConsumer[0].getNumDims())
1320     return llvm::None;
1321 
1322   unsigned currDim = 0;
1323   SmallVector<ReassociationIndices> reassociationMaps;
1324   for (AffineMap rhs : mapsConsumer) {
1325     ReassociationIndices reassociations;
1326     for (AffineExpr rhsExpr : rhs.getResults()) {
1327       AffineDimExpr dimExpr = rhsExpr.cast<AffineDimExpr>();
1328       for (int i = 0, e = mapsProducer[dimExpr.getPosition()].getNumResults();
1329            i < e; ++i)
1330         reassociations.push_back(currDim++);
1331     }
1332     reassociationMaps.push_back(std::move(reassociations));
1333   }
1334   return reassociationMaps;
1335 }
1336 
1337 namespace {
1338 /// Pattern to collapse producer/consumer reshape ops that are both collapsing
1339 /// dimensions or are both expanding dimensions.
1340 template <typename ReshapeOpTy>
1341 struct CollapseReshapeOps : public OpRewritePattern<ReshapeOpTy> {
1342   using OpRewritePattern<ReshapeOpTy>::OpRewritePattern;
1343   LogicalResult matchAndRewrite(ReshapeOpTy reshapeOp,
1344                                 PatternRewriter &rewriter) const override {
1345     auto srcReshapeOp = reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
1346     if (!srcReshapeOp)
1347       return failure();
1348 
1349     ShapedType srcReshapeSrcType = srcReshapeOp.getSrcType();
1350     ShapedType intermediateType = reshapeOp.getSrcType();
1351     ShapedType resultType = reshapeOp.getResultType();
1352 
1353     auto areReshapeOpsFoldable = [](ShapedType largerType,
1354                                     ShapedType intermediateType,
1355                                     ShapedType smallerType) -> bool {
1356       return largerType.getRank() > intermediateType.getRank() &&
1357              intermediateType.getRank() > smallerType.getRank();
1358     };
1359     Optional<SmallVector<ReassociationIndices>> reassociationIndices =
1360         llvm::None;
1361     // Check if producer and consumer are both expanding dims or both collapsing
1362     // dims. In this case, try to compose the affine maps. This works for
1363     // dynamic shapes too.
1364     if (areReshapeOpsFoldable(resultType, intermediateType,
1365                               srcReshapeSrcType) ||
1366         areReshapeOpsFoldable(srcReshapeSrcType, intermediateType,
1367                               resultType)) {
1368       reassociationIndices = collapseReassociationIndices(
1369           srcReshapeOp.getReassociationMaps(), reshapeOp.getReassociationMaps(),
1370           rewriter.getContext());
1371     }
1372     if (!reassociationIndices) {
1373       // If the source reshape can be collapsed/expanded into the target reshape
1374       // they can still be folded. This can only be reasoned about statically
1375       // for cases where
1376       // - either all shapes are static, or
1377       // - The number of dynamic dimensions matches in the source of source and
1378       //   result with all other dimensions being 1.
1379       reassociationIndices =
1380           getReassociationIndicesForReshape(srcReshapeSrcType, resultType);
1381     }
1382     if (!reassociationIndices)
1383       return failure();
1384     rewriter.replaceOpWithNewOp<ReshapeOpTy>(
1385         reshapeOp, resultType, srcReshapeOp.src(), *reassociationIndices);
1386     return success();
1387   }
1388 };
1389 } // namespace
1390 
1391 template <typename ReshapeOpTy>
1392 static OpFoldResult foldReshapeOp(ReshapeOpTy reshapeOp,
1393                                   ArrayRef<Attribute> operands) {
1394   // Fold producer-consumer reshape ops that where the operand type of the
1395   // producer is same as the return type of the consumer.
1396   ReshapeOpTy reshapeSrcOp =
1397       reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
1398   if (reshapeSrcOp && reshapeSrcOp.getSrcType() == reshapeOp.getResultType())
1399     return reshapeSrcOp.src();
1400   // Reshape of a constant can be replaced with a new constant.
1401   if (auto elements = operands.front().dyn_cast_or_null<DenseElementsAttr>()) {
1402     return elements.reshape(
1403         reshapeOp.getResult().getType().template cast<ShapedType>());
1404   }
1405   return nullptr;
1406 }
1407 
1408 /// Return true if the reassociation specification is valid, false otherwise.
1409 /// When false, the `invalidIndex` integer pointer is optionally filled with the
1410 /// index of the offending reassociation map.
1411 static bool isReassociationValid(ArrayRef<AffineMap> reassociation,
1412                                  int *invalidIndex = nullptr) {
1413   if (reassociation.empty())
1414     return true;
1415   unsigned nDims = reassociation[0].getNumDims();
1416   unsigned nextExpectedDim = 0;
1417   for (auto it : llvm::enumerate(reassociation)) {
1418     auto m = it.value();
1419     if (m.getNumDims() != nDims || m.getNumSymbols() != 0) {
1420       if (invalidIndex)
1421         *invalidIndex = it.index();
1422       return false;
1423     }
1424     for (auto e : m.getResults()) {
1425       auto d = e.dyn_cast<AffineDimExpr>();
1426       if (!d || d.getPosition() != nextExpectedDim++) {
1427         if (invalidIndex)
1428           *invalidIndex = it.index();
1429         return false;
1430       }
1431     }
1432   }
1433   if (nextExpectedDim != nDims) {
1434     if (invalidIndex)
1435       *invalidIndex = reassociation.size() - 1;
1436     return false;
1437   }
1438   return true;
1439 }
1440 
1441 /// Detect whether memref dims [dim, dim + extent) can be reshaped without
1442 /// copies.
1443 static bool isReshapableDimBand(unsigned dim, unsigned extent,
1444                                 ArrayRef<int64_t> sizes,
1445                                 ArrayRef<AffineExpr> strides) {
1446   assert(sizes.size() == strides.size() && "mismatched ranks");
1447   // off by 1 indexing to avoid out of bounds
1448   //                       V
1449   for (auto idx = dim, e = dim + extent; idx + 1 < e; ++idx) {
1450     // Only bands of static shapes are reshapable. This is due to the fact that
1451     // there is no relation between dynamic sizes and dynamic strides: we do not
1452     // have enough information to know whether a "-1" size corresponds to the
1453     // proper symbol in the AffineExpr of a stride.
1454     if (ShapedType::isDynamic(sizes[dim + 1]))
1455       return false;
1456     // TODO: Refine this by passing the proper nDims and nSymbols so we can
1457     // simplify on the fly and catch more reshapable cases.
1458     if (strides[idx] != strides[idx + 1] * sizes[idx + 1])
1459       return false;
1460   }
1461   return true;
1462 }
1463 
1464 /// Compute the MemRefType obtained by applying the `reassociation` (which is
1465 /// expected to be valid) to `type`.
1466 /// If `type` is Contiguous MemRefType, this always produce a contiguous
1467 /// MemRefType.
1468 static MemRefType
1469 computeReshapeCollapsedType(MemRefType type,
1470                             ArrayRef<AffineMap> reassociation) {
1471   auto sizes = type.getShape();
1472   AffineExpr offset;
1473   SmallVector<AffineExpr, 4> strides;
1474   auto status = getStridesAndOffset(type, strides, offset);
1475   (void)status;
1476   assert(succeeded(status) && "expected strided memref");
1477 
1478   SmallVector<int64_t, 4> newSizes;
1479   newSizes.reserve(reassociation.size());
1480   SmallVector<AffineExpr, 4> newStrides;
1481   newStrides.reserve(reassociation.size());
1482 
1483   // Use the fact that reassociation is valid to simplify the logic: only use
1484   // each map's rank.
1485   assert(isReassociationValid(reassociation) && "invalid reassociation");
1486   unsigned currentDim = 0;
1487   for (AffineMap m : reassociation) {
1488     unsigned dim = m.getNumResults();
1489     int64_t size = 1;
1490     AffineExpr stride = strides[currentDim + dim - 1];
1491     if (!isReshapableDimBand(currentDim, dim, sizes, strides)) {
1492       size = ShapedType::kDynamicSize;
1493       stride = AffineExpr();
1494     } else {
1495       for (unsigned d = 0; d < dim; ++d)
1496         size *= sizes[currentDim + d];
1497     }
1498     newSizes.push_back(size);
1499     newStrides.push_back(stride);
1500     currentDim += dim;
1501   }
1502 
1503   // Early-exit: if `type` is contiguous, the result must be contiguous.
1504   if (canonicalizeStridedLayout(type).getAffineMaps().empty())
1505     return MemRefType::Builder(type).setShape(newSizes).setAffineMaps({});
1506 
1507   // Convert back to int64_t because we don't have enough information to create
1508   // new strided layouts from AffineExpr only. This corresponds to a case where
1509   // copies may be necessary.
1510   int64_t intOffset = ShapedType::kDynamicStrideOrOffset;
1511   if (auto o = offset.dyn_cast<AffineConstantExpr>())
1512     intOffset = o.getValue();
1513   SmallVector<int64_t, 4> intStrides;
1514   intStrides.reserve(strides.size());
1515   for (auto stride : newStrides) {
1516     if (auto cst = stride.dyn_cast_or_null<AffineConstantExpr>())
1517       intStrides.push_back(cst.getValue());
1518     else
1519       intStrides.push_back(ShapedType::kDynamicStrideOrOffset);
1520   }
1521   auto layout =
1522       makeStridedLinearLayoutMap(intStrides, intOffset, type.getContext());
1523   return canonicalizeStridedLayout(
1524       MemRefType::Builder(type).setShape(newSizes).setAffineMaps({layout}));
1525 }
1526 
1527 
1528 template <typename AffineExprTy>
1529 unsigned getMaxPosOfType(ArrayRef<ReassociationExprs> exprArrays) {
1530   unsigned pos = 0;
1531   for (const auto &exprs : exprArrays) {
1532     for (auto expr : exprs) {
1533       expr.walk([&pos](AffineExpr e) {
1534         if (auto d = e.dyn_cast<AffineExprTy>())
1535           pos = std::max(pos, d.getPosition());
1536       });
1537     }
1538   }
1539   return pos;
1540 }
1541 
1542 static SmallVector<AffineMap, 4>
1543 getSymbolLessAffineMaps(ArrayRef<ReassociationExprs> reassociation) {
1544   unsigned maxDim = getMaxPosOfType<AffineDimExpr>(reassociation);
1545   assert(getMaxPosOfType<AffineSymbolExpr>(reassociation) == 0 &&
1546          "Expected symbol-less expressions");
1547   SmallVector<AffineMap, 4> maps;
1548   maps.reserve(reassociation.size());
1549   for (const auto &exprs : reassociation) {
1550     assert(!exprs.empty());
1551     maps.push_back(AffineMap::get(maxDim + 1, 0, exprs, exprs[0].getContext()));
1552   }
1553   return maps;
1554 }
1555 
1556 static SmallVector<ReassociationIndices, 2> convertReassociationMapsToIndices(
1557     OpBuilder &b, ArrayRef<ReassociationExprs> reassociationExprs) {
1558   SmallVector<ReassociationIndices, 2> reassociationIndices;
1559   for (const auto &exprs : reassociationExprs) {
1560     ReassociationIndices indices;
1561     indices.reserve(exprs.size());
1562     for (const auto &expr : exprs)
1563       indices.push_back(expr.cast<AffineDimExpr>().getPosition());
1564     reassociationIndices.push_back(indices);
1565   }
1566   return reassociationIndices;
1567 }
1568 
1569 static SmallVector<SmallVector<AffineExpr, 2>, 2>
1570 convertReassociationIndicesToExprs(
1571     OpBuilder &b, ArrayRef<ReassociationIndices> reassociationIndices) {
1572   SmallVector<SmallVector<AffineExpr, 2>, 2> reassociationMaps;
1573   for (const auto &indices : reassociationIndices) {
1574     SmallVector<AffineExpr, 2> reassociationMap;
1575     reassociationMap.reserve(indices.size());
1576     for (int64_t index : indices)
1577       reassociationMap.push_back(b.getAffineDimExpr(index));
1578     reassociationMaps.push_back(std::move(reassociationMap));
1579   }
1580   return reassociationMaps;
1581 }
1582 
1583 SmallVector<AffineMap, 4> ReshapeOp::getReassociationMaps() {
1584   return getSymbolLessAffineMaps(getReassociationExprs());
1585 }
1586 SmallVector<ReassociationExprs, 4> ReshapeOp::getReassociationExprs() {
1587   OpBuilder b(this->getContext());
1588   return convertReassociationIndicesToExprs(b, getReassociationIndices());
1589 }
1590 SmallVector<AffineMap, 4> TensorReshapeOp::getReassociationMaps() {
1591   return getSymbolLessAffineMaps(getReassociationExprs());
1592 }
1593 SmallVector<ReassociationExprs, 4> TensorReshapeOp::getReassociationExprs() {
1594   OpBuilder b(this->getContext());
1595   return convertReassociationIndicesToExprs(b, getReassociationIndices());
1596 }
1597 /// For reshape op compute the shape at dimension `dimIndex` of the output in
1598 /// terms of shape of the `src`, when the reshape op is a collapsing
1599 /// operation. It is the product of the shape of the collapsed dimensions of the
1600 /// `src`.
1601 static OpFoldResult
1602 getCollapsedOutputDimFromInputShape(OpBuilder &builder, Location loc,
1603                                     int64_t dimIndex, Value src,
1604                                     ArrayRef<AffineMap> reassociationMap) {
1605   AffineMap map = reassociationMap[dimIndex];
1606   unsigned startPos =
1607       map.getResults().front().cast<AffineDimExpr>().getPosition();
1608   unsigned endPos = map.getResults().back().cast<AffineDimExpr>().getPosition();
1609   AffineExpr expr;
1610   SmallVector<Value, 2> dynamicDims;
1611   for (auto dim : llvm::seq(startPos, endPos + 1)) {
1612     dynamicDims.push_back(builder.createOrFold<memref::DimOp>(loc, src, dim));
1613     AffineExpr currExpr = builder.getAffineSymbolExpr(dim - startPos);
1614     expr = (expr ? expr * currExpr : currExpr);
1615   }
1616   return applyMapToValues(builder, loc,
1617                           AffineMap::get(0, endPos - startPos + 1, expr),
1618                           dynamicDims)[0];
1619 }
1620 
1621 /// Given the `src` of a collapsing reshape op and its reassociation maps,
1622 /// compute the shape of the result of the reshape.
1623 static SmallVector<OpFoldResult, 4> getCollapsedOutputShapeFromInputShape(
1624     OpBuilder &builder, Location loc, Value src,
1625     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation) {
1626   return llvm::to_vector<4>(llvm::map_range(
1627       llvm::seq<int64_t>(0, dstStaticShape.size()), [&](int64_t dim) {
1628         return getCollapsedOutputDimFromInputShape(builder, loc, dim, src,
1629                                                    reassociation);
1630       }));
1631 }
1632 
1633 /// Compute a map that for a given dimension of the expanded type gives the
1634 /// dimension in the collapsed type it maps to. Essentially its the inverse of
1635 /// the `reassocation` maps.
1636 static llvm::DenseMap<int64_t, int64_t>
1637 getExpandedDimToCollapsedDimMap(ArrayRef<AffineMap> reassociation) {
1638   llvm::DenseMap<int64_t, int64_t> expandedDimToCollapsedDim;
1639   for (auto map : enumerate(reassociation)) {
1640     unsigned startPos =
1641         map.value().getResults().front().cast<AffineDimExpr>().getPosition();
1642     unsigned endPos =
1643         map.value().getResults().back().cast<AffineDimExpr>().getPosition();
1644     for (auto dim : llvm::seq(startPos, endPos + 1)) {
1645       expandedDimToCollapsedDim[dim] = map.index();
1646     }
1647   }
1648   return expandedDimToCollapsedDim;
1649 }
1650 
1651 /// For an expanding reshape op, compute the value for a dimension of the output
1652 /// from the shape of the input.
1653 static OpFoldResult getExpandedOutputDimFromInputShape(
1654     OpBuilder &builder, Location loc, int64_t dimIndex, Value src,
1655     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation,
1656     llvm::DenseMap<int64_t, int64_t> &expandedDimToCollapsedDim) {
1657   if (!ShapedType::isDynamic(dstStaticShape[dimIndex])) {
1658     return builder.getI64IntegerAttr(dstStaticShape[dimIndex]);
1659   }
1660   unsigned sourceDimPos = expandedDimToCollapsedDim[dimIndex];
1661   unsigned startPos = reassociation[sourceDimPos]
1662                           .getResults()
1663                           .front()
1664                           .cast<AffineDimExpr>()
1665                           .getPosition();
1666   unsigned endPos = reassociation[sourceDimPos]
1667                         .getResults()
1668                         .back()
1669                         .cast<AffineDimExpr>()
1670                         .getPosition();
1671   int64_t linearizedStaticDim = 1;
1672   for (auto d :
1673        llvm::enumerate(dstStaticShape.slice(startPos, endPos - startPos + 1))) {
1674     if (d.index() + startPos == static_cast<unsigned>(dimIndex))
1675       continue;
1676     assert(!ShapedType::isDynamic(d.value()) &&
1677            "single dimension cannot be expanded into multiple dynamic "
1678            "dimensions");
1679     linearizedStaticDim *= d.value();
1680   }
1681   Value sourceDim = builder.create<memref::DimOp>(loc, src, sourceDimPos);
1682   return applyMapToValues(
1683       builder, loc,
1684       AffineMap::get(
1685           0, 1, builder.getAffineSymbolExpr(0).floorDiv(linearizedStaticDim)),
1686       sourceDim)[0];
1687 }
1688 
1689 /// Given the `src` of an expanding reshape op, the reassociation maps and the
1690 /// result type, compute the shape of the result of the reshape.
1691 static SmallVector<OpFoldResult, 4> getExpandedOutputShapeFromInputShape(
1692     OpBuilder &builder, Location loc, Value src,
1693     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation) {
1694   llvm::DenseMap<int64_t, int64_t> expandedDimToCollapsedDim =
1695       getExpandedDimToCollapsedDimMap(reassociation);
1696   return llvm::to_vector<4>(llvm::map_range(
1697       llvm::seq<int64_t>(0, dstStaticShape.size()), [&](int64_t dim) {
1698         return getExpandedOutputDimFromInputShape(builder, loc, dim, src,
1699                                                   dstStaticShape, reassociation,
1700                                                   expandedDimToCollapsedDim);
1701       }));
1702 }
1703 
1704 static SmallVector<OpFoldResult, 4>
1705 getReshapeOutputShapeFromInputShape(OpBuilder &builder, Location loc, Value src,
1706                                     ArrayRef<int64_t> dstStaticShape,
1707                                     ArrayRef<AffineMap> reassocation) {
1708   return dstStaticShape.size() >
1709                  static_cast<size_t>(src.getType().cast<ShapedType>().getRank())
1710              ? getExpandedOutputShapeFromInputShape(
1711                    builder, loc, src, dstStaticShape, reassocation)
1712              : getCollapsedOutputShapeFromInputShape(
1713                    builder, loc, src, dstStaticShape, reassocation);
1714 }
1715 
1716 static ArrayAttr
1717 getReassociationIndicesAttribute(OpBuilder &b,
1718                                  ArrayRef<ReassociationIndices> reassociation) {
1719   SmallVector<Attribute, 4> reassociationAttr =
1720       llvm::to_vector<4>(llvm::map_range(
1721           reassociation, [&](ReassociationIndices indices) -> Attribute {
1722             return b.getI64ArrayAttr(indices).cast<Attribute>();
1723           }));
1724   return b.getArrayAttr(reassociationAttr);
1725 }
1726 
1727 void mlir::linalg::ReshapeOp::build(
1728     OpBuilder &b, OperationState &result, Value src,
1729     ArrayRef<ReassociationIndices> reassociation,
1730     ArrayRef<NamedAttribute> attrs) {
1731   auto memRefType = src.getType().cast<MemRefType>();
1732   auto resultType = computeReshapeCollapsedType(
1733       memRefType, getSymbolLessAffineMaps(
1734                       convertReassociationIndicesToExprs(b, reassociation)));
1735   build(b, result, resultType, src, attrs);
1736   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1737                       getReassociationIndicesAttribute(b, reassociation));
1738 }
1739 
1740 void mlir::linalg::ReshapeOp::build(
1741     OpBuilder &b, OperationState &result, Type resultType, Value src,
1742     ArrayRef<ReassociationIndices> reassociation,
1743     ArrayRef<NamedAttribute> attrs) {
1744   build(b, result, resultType, src, attrs);
1745   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1746                       getReassociationIndicesAttribute(b, reassociation));
1747 }
1748 
1749 Value mlir::linalg::ReshapeOp::getViewSource() { return src(); }
1750 
1751 /// Verify that shapes of the reshaped types using following rules
1752 /// 1) if a dimension in the collapsed type is static, then the corresponding
1753 ///    dimensions in the expanded shape should be
1754 ///    a) static
1755 ///    b) the product should be same as the collaped shape.
1756 /// 2) if a dimension in the collaped type is dynamic, one and only one of the
1757 ///    corresponding dimensions in the expanded type should be dynamic. This
1758 ///    rule is only needed with reshape operations that are expanding.
1759 template <typename OpTy>
1760 static LogicalResult verifyReshapeLikeShapes(OpTy op, ShapedType collapsedType,
1761                                              ShapedType expandedType,
1762                                              bool isExpandingReshape) {
1763   ArrayRef<int64_t> collapsedShape = collapsedType.getShape();
1764   ArrayRef<int64_t> expandedShape = expandedType.getShape();
1765   unsigned expandedDimStart = 0;
1766   for (auto map : llvm::enumerate(op.getReassociationMaps())) {
1767     Optional<int64_t> dynamicShape;
1768     int64_t linearizedStaticShape = 1;
1769     for (auto dim : llvm::enumerate(expandedShape.slice(
1770              expandedDimStart, map.value().getNumResults()))) {
1771       if (ShapedType::isDynamic(dim.value())) {
1772         if (isExpandingReshape && dynamicShape) {
1773           return op->emitOpError("invalid to have a single dimension (")
1774                  << map.index() << ") expanded into multiple dynamic dims ("
1775                  << expandedDimStart + dynamicShape.getValue() << ","
1776                  << expandedDimStart + dim.index() << ")";
1777         }
1778         dynamicShape = dim.index();
1779       } else {
1780         linearizedStaticShape *= dim.value();
1781       }
1782     }
1783     if (dynamicShape) {
1784       if (!ShapedType::isDynamic(collapsedShape[map.index()])) {
1785         return op->emitOpError("expected dimension ")
1786                << map.index()
1787                << " of collapsed type to be dynamic since one or more of the "
1788                   "corresponding dimensions in the expanded type is dynamic";
1789       }
1790     } else {
1791       if (collapsedShape[map.index()] != linearizedStaticShape) {
1792         return op->emitOpError("expected dimension ")
1793                << map.index() << " of collapsed type to be static value of "
1794                << linearizedStaticShape << " ";
1795       }
1796     }
1797     expandedDimStart += map.value().getNumResults();
1798   }
1799   return success();
1800 }
1801 
1802 // Common verifier for reshape-like types. Fills `expandedType` and
1803 // `collapsedType` with the proper `src` or `result` type.
1804 template <typename Op, typename T>
1805 static LogicalResult verifyReshapeLikeTypes(Op op, T &expandedType,
1806                                             T &collapsedType) {
1807   expandedType = op.getSrcType();
1808   collapsedType = op.getResultType();
1809   unsigned expandedRank = expandedType.getRank();
1810   unsigned collapsedRank = collapsedType.getRank();
1811   bool isCollapse = expandedRank > collapsedRank;
1812   if (!isCollapse) {
1813     std::swap(expandedRank, collapsedRank);
1814     std::swap(expandedType, collapsedType);
1815   }
1816   if (expandedRank == 0)
1817     return op.emitOpError("expected non-zero memref ranks");
1818   if (expandedRank == collapsedRank)
1819     return op.emitOpError("expected to collapse or expand dims");
1820 
1821   if (collapsedRank == 0) {
1822     // If collapsed rank is 0, then expanded type must be static shaped and of
1823     // sizes 1.
1824     if (llvm::any_of(expandedType.getShape(),
1825                      [](int64_t dim) -> bool { return dim != 1; }))
1826       return op.emitOpError("invalid to reshape tensor/memref with non-unit "
1827                             "extent dimensions to zero-rank tensor/memref");
1828     return success();
1829   }
1830   if (collapsedRank != op.reassociation().size())
1831     return op.emitOpError("expected rank of the collapsed type(")
1832            << collapsedRank << ") to be the number of reassociation maps("
1833            << op.reassociation().size() << ")";
1834   auto maps = op.getReassociationMaps();
1835   for (auto it : llvm::enumerate(maps))
1836     if (it.value().getNumDims() != expandedRank)
1837       return op.emitOpError("expected reassociation map #")
1838              << it.index() << " of same rank as expanded memref("
1839              << expandedRank << "), but got " << it.value().getNumDims();
1840   int invalidIdx = 0;
1841   if (!isReassociationValid(maps, &invalidIdx))
1842     return op.emitOpError("expected reassociation map #")
1843            << invalidIdx << " to be valid and contiguous";
1844   return verifyReshapeLikeShapes(op, collapsedType, expandedType, !isCollapse);
1845 }
1846 
1847 static LogicalResult verify(ReshapeOp op) {
1848   MemRefType expandedType, collapsedType;
1849   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
1850     return failure();
1851   auto maps = op.getReassociationMaps();
1852   MemRefType expectedType = computeReshapeCollapsedType(expandedType, maps);
1853   if (collapsedType != expectedType)
1854     return op.emitOpError("expected collapsed type to be ")
1855            << expectedType << ", but got " << collapsedType;
1856   return success();
1857 }
1858 
1859 void ReshapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
1860                                             MLIRContext *context) {
1861   results.add<CollapseReshapeOps<ReshapeOp>>(context);
1862 }
1863 
1864 //===----------------------------------------------------------------------===//
1865 // TensorReshapeOp
1866 //===----------------------------------------------------------------------===//
1867 
1868 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`.
1869 static RankedTensorType
1870 computeTensorReshapeCollapsedType(RankedTensorType type,
1871                                   ArrayRef<AffineMap> reassociation) {
1872   auto shape = type.getShape();
1873   SmallVector<int64_t, 4> newShape;
1874   newShape.reserve(reassociation.size());
1875 
1876   // Use the fact that reassociation is valid to simplify the logic: only use
1877   // each map's rank.
1878   assert(isReassociationValid(reassociation) && "invalid reassociation");
1879   unsigned currentDim = 0;
1880   for (AffineMap m : reassociation) {
1881     unsigned dim = m.getNumResults();
1882     auto band = shape.slice(currentDim, dim);
1883     int64_t size = 1;
1884     if (llvm::is_contained(band, ShapedType::kDynamicSize))
1885       size = ShapedType::kDynamicSize;
1886     else
1887       for (unsigned d = 0; d < dim; ++d)
1888         size *= shape[currentDim + d];
1889     newShape.push_back(size);
1890     currentDim += dim;
1891   }
1892 
1893   return RankedTensorType::get(newShape, type.getElementType());
1894 }
1895 
1896 void mlir::linalg::TensorReshapeOp::build(
1897     OpBuilder &b, OperationState &result, Value src,
1898     ArrayRef<ReassociationIndices> reassociation,
1899     ArrayRef<NamedAttribute> attrs) {
1900   auto resultType = computeTensorReshapeCollapsedType(
1901       src.getType().cast<RankedTensorType>(),
1902       getSymbolLessAffineMaps(
1903           convertReassociationIndicesToExprs(b, reassociation)));
1904   build(b, result, resultType, src, attrs);
1905   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1906                       getReassociationIndicesAttribute(b, reassociation));
1907 }
1908 
1909 void mlir::linalg::TensorReshapeOp::build(
1910     OpBuilder &b, OperationState &result, Type resultType, Value src,
1911     ArrayRef<ReassociationIndices> reassociation,
1912     ArrayRef<NamedAttribute> attrs) {
1913   build(b, result, resultType, src, attrs);
1914   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1915                       getReassociationIndicesAttribute(b, reassociation));
1916 }
1917 
1918 static LogicalResult verify(TensorReshapeOp op) {
1919   RankedTensorType expandedType, collapsedType;
1920   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
1921     return failure();
1922 
1923   auto maps = op.getReassociationMaps();
1924   RankedTensorType expectedType =
1925       computeTensorReshapeCollapsedType(expandedType, maps);
1926   if (collapsedType != expectedType)
1927     return op.emitOpError("expected collapsed type to be ")
1928            << expectedType << ", but got " << collapsedType;
1929   return success();
1930 }
1931 
1932 namespace {
1933 /// Reshape of a splat constant can be replaced with a constant of the result
1934 /// type.
1935 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> {
1936   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1937   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1938                                 PatternRewriter &rewriter) const override {
1939     DenseElementsAttr attr;
1940     if (!matchPattern(reshapeOp.src(), m_Constant(&attr)))
1941       return failure();
1942     if (!attr || !attr.isSplat())
1943       return failure();
1944     DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer(
1945         reshapeOp.getResultType(), attr.getRawData(), true);
1946     rewriter.replaceOpWithNewOp<ConstantOp>(reshapeOp, newAttr);
1947     return success();
1948   }
1949 };
1950 
1951 /// Fold linalg.fill -> linalg.tensor_reshape chain.
1952 ///
1953 /// For such op chains, we can create new linalg.fill ops with the result
1954 /// type of the linalg.tensor_reshape op.
1955 struct FoldFillWithTensorReshape : OpRewritePattern<TensorReshapeOp> {
1956   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1957   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1958                                 PatternRewriter &rewriter) const override {
1959     auto oldFill = reshapeOp.src().getDefiningOp<FillOp>();
1960     if (!oldFill)
1961       return failure();
1962 
1963     Location loc = oldFill.getLoc();
1964     auto newInit = rewriter.create<TensorReshapeOp>(
1965         loc, reshapeOp.getResultType(), oldFill.output(),
1966         reshapeOp.reassociation());
1967     rewriter.replaceOpWithNewOp<FillOp>(reshapeOp, newInit, oldFill.value());
1968 
1969     return success();
1970   }
1971 };
1972 } // namespace
1973 
1974 void TensorReshapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
1975                                                   MLIRContext *context) {
1976   results.add<CollapseReshapeOps<TensorReshapeOp>, FoldFillWithTensorReshape,
1977               FoldInitTensorWithTensorReshapeOp, FoldReshapeWithConstant>(
1978       context);
1979 }
1980 
1981 LogicalResult TensorReshapeOp::reifyReturnTypeShapesPerResultDim(
1982     OpBuilder &b, SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
1983   auto resultShape =
1984       getAsValues(b, getLoc(),
1985                   getReshapeOutputShapeFromInputShape(
1986                       b, getLoc(), src(), getResultType().getShape(),
1987                       getReassociationMaps()));
1988   reifiedReturnShapes.emplace_back(std::move(resultShape));
1989   return success();
1990 }
1991 
1992 //===----------------------------------------------------------------------===//
1993 // YieldOp
1994 //===----------------------------------------------------------------------===//
1995 
1996 static void print(OpAsmPrinter &p, linalg::YieldOp op) {
1997   p << op.getOperationName();
1998   if (op.getNumOperands() > 0)
1999     p << ' ' << op.getOperands();
2000   p.printOptionalAttrDict(op->getAttrs());
2001   if (op.getNumOperands() > 0)
2002     p << " : " << op.getOperandTypes();
2003 }
2004 
2005 static ParseResult parseYieldOp(OpAsmParser &parser, OperationState &result) {
2006   SmallVector<OpAsmParser::OperandType, 2> opInfo;
2007   SmallVector<Type, 2> types;
2008   llvm::SMLoc loc = parser.getCurrentLocation();
2009   return failure(parser.parseOperandList(opInfo) ||
2010                  parser.parseOptionalAttrDict(result.attributes) ||
2011                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
2012                  parser.resolveOperands(opInfo, types, loc, result.operands));
2013 }
2014 
2015 // Check the operand number and types must match the element types of the
2016 // LinalgOp interface's shaped operands.
2017 static LogicalResult verifyYield(linalg::YieldOp op,
2018                                  LinalgOp linalgOpInterface) {
2019   auto nOutputs = linalgOpInterface.getNumOutputs();
2020   if (op.getNumOperands() != nOutputs)
2021     return op.emitOpError("expected number of yield values (")
2022            << nOutputs << ") to match the number of operands of the enclosing "
2023            << "LinalgOp (" << op.getNumOperands() << ")";
2024 
2025   for (unsigned i = 0; i != nOutputs; ++i) {
2026     auto elementType =
2027         linalgOpInterface.getOutputShapedType(i).getElementType();
2028     if (op.getOperand(i).getType() != elementType)
2029       return op.emitOpError("type of yield operand ")
2030              << (i + 1) << " (" << op.getOperand(i).getType()
2031              << ") doesn't match "
2032              << "the element type of the enclosing linalg.generic op ("
2033              << elementType << ")";
2034   }
2035   return success();
2036 }
2037 
2038 static LogicalResult verify(linalg::YieldOp op) {
2039   auto *parentOp = op->getParentOp();
2040   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
2041     return op.emitOpError("expected single non-empty parent region");
2042 
2043   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
2044     return verifyYield(op, cast<LinalgOp>(parentOp));
2045 
2046   if (auto padTensorOp = dyn_cast<linalg::PadTensorOp>(parentOp)) {
2047     if (op.getNumOperands() != 1)
2048       return op.emitOpError("expected single yield operand (got ")
2049              << op->getNumOperands() << ")";
2050     if (op.getOperand(0).getType() !=
2051         padTensorOp.getType().cast<ShapedType>().getElementType())
2052       return op.emitOpError("expected yield type to match shape element type");
2053     return success();
2054   }
2055 
2056   if (auto tiledLoopOp = dyn_cast<linalg::TiledLoopOp>(parentOp)) {
2057     // Check if output args with tensor types match results types.
2058     SmallVector<Value, 2> tensorOuts;
2059     llvm::copy_if(
2060         tiledLoopOp.outputs(), std::back_inserter(tensorOuts),
2061         [&](Value out) { return out.getType().isa<RankedTensorType>(); });
2062     if (tensorOuts.size() != op.values().size())
2063       return op.emitOpError("expected number of tensor output args = ")
2064              << tensorOuts.size() << " to match the number of yield operands = "
2065              << op.values().size();
2066 
2067     TypeRange tensorTypes(llvm::makeArrayRef(tensorOuts));
2068     for (auto &item :
2069          llvm::enumerate(llvm::zip(tensorTypes, op.getOperandTypes()))) {
2070       Type outType, resultType;
2071       unsigned index = item.index();
2072       std::tie(outType, resultType) = item.value();
2073       if (outType != resultType)
2074         return op.emitOpError("expected yield operand ")
2075                << index << " with type = " << resultType
2076                << " to match output arg type = " << outType;
2077     }
2078     return success();
2079   }
2080   return op.emitOpError("expected parent op with LinalgOp interface");
2081 }
2082 
2083 //===----------------------------------------------------------------------===//
2084 // TiledLoopOp
2085 //===----------------------------------------------------------------------===//
2086 
2087 void TiledLoopOp::build(OpBuilder &builder, OperationState &result,
2088                         ValueRange lowerBounds, ValueRange upperBounds,
2089                         ValueRange steps, ValueRange inputs, ValueRange outputs,
2090                         ArrayAttr iteratorTypes,
2091                         function_ref<void(OpBuilder &, Location, ValueRange,
2092                                           ValueRange, ValueRange)>
2093                             bodyBuilderFn) {
2094   result.addOperands(lowerBounds);
2095   result.addOperands(upperBounds);
2096   result.addOperands(steps);
2097   result.addOperands(inputs);
2098   result.addOperands(outputs);
2099   result.addAttribute(
2100       TiledLoopOp::getOperandSegmentSizeAttr(),
2101       builder.getI32VectorAttr({static_cast<int32_t>(lowerBounds.size()),
2102                                 static_cast<int32_t>(upperBounds.size()),
2103                                 static_cast<int32_t>(steps.size()),
2104                                 static_cast<int32_t>(inputs.size()),
2105                                 static_cast<int32_t>(outputs.size())}));
2106   result.addAttribute(getIteratorTypesAttrName(), iteratorTypes);
2107 
2108   // Add output types for `RankedTensorType` output arguments.
2109   for (Value output : outputs) {
2110     Type outputType = output.getType();
2111     if (outputType.isa<RankedTensorType>())
2112       result.addTypes(outputType);
2113   }
2114 
2115   OpBuilder::InsertionGuard guard(builder);
2116   unsigned numIVs = steps.size();
2117   SmallVector<Type, 8> argTypes(numIVs, builder.getIndexType());
2118   for (Type type : TypeRange(inputs))
2119     argTypes.push_back(type);
2120   for (Type type : TypeRange(outputs))
2121     argTypes.push_back(type);
2122   Region *bodyRegion = result.addRegion();
2123   Block *bodyBlock = builder.createBlock(bodyRegion, {}, argTypes);
2124 
2125   if (bodyBuilderFn) {
2126     builder.setInsertionPointToStart(bodyBlock);
2127     bodyBuilderFn(builder, result.location,
2128                   bodyBlock->getArguments().take_front(numIVs),
2129                   bodyBlock->getArguments().slice(numIVs, inputs.size()),
2130                   bodyBlock->getArguments().take_back(outputs.size()));
2131     TiledLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
2132   }
2133 }
2134 
2135 static void print(OpAsmPrinter &p, TiledLoopOp op) {
2136   p << op.getOperationName() << " (" << op.getInductionVars() << ") = ("
2137     << op.lowerBound() << ") to (" << op.upperBound() << ") step (" << op.step()
2138     << ")";
2139 
2140   if (!op.inputs().empty()) {
2141     p << " ins (";
2142     llvm::interleaveComma(llvm::zip(op.getRegionInputArgs(), op.inputs()), p,
2143                           [&](auto it) {
2144                             p << std::get<0>(it) << " = " << std::get<1>(it)
2145                               << ": " << std::get<1>(it).getType();
2146                           });
2147     p << ")";
2148   }
2149   if (!op.outputs().empty()) {
2150     p << " outs (";
2151     llvm::interleaveComma(llvm::zip(op.getRegionOutputArgs(), op.outputs()), p,
2152                           [&](auto it) {
2153                             p << std::get<0>(it) << " = " << std::get<1>(it)
2154                               << ": " << std::get<1>(it).getType();
2155                           });
2156     p << ")";
2157   }
2158 
2159   if (llvm::any_of(op.iterator_types(), [](Attribute attr) {
2160         return attr.cast<StringAttr>().getValue() !=
2161                getParallelIteratorTypeName();
2162       })) {
2163     p << " iterators" << op.iterator_types() << "";
2164   }
2165 
2166   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
2167   p.printOptionalAttrDict(
2168       op->getAttrs(), /*elidedAttrs=*/{TiledLoopOp::getOperandSegmentSizeAttr(),
2169                                        getIteratorTypesAttrName()});
2170 }
2171 
2172 static ParseResult parseTiledLoopOp(OpAsmParser &parser,
2173                                     OperationState &result) {
2174   auto &builder = parser.getBuilder();
2175   // Parse an opening `(` followed by induction variables followed by `)`
2176   SmallVector<OpAsmParser::OperandType, 4> ivs;
2177   if (parser.parseRegionArgumentList(ivs, /*requiredOperandCount=*/-1,
2178                                      OpAsmParser::Delimiter::Paren))
2179     return failure();
2180 
2181   // Parse loop bounds.
2182   SmallVector<OpAsmParser::OperandType, 4> lower;
2183   if (parser.parseEqual() ||
2184       parser.parseOperandList(lower, ivs.size(),
2185                               OpAsmParser::Delimiter::Paren) ||
2186       parser.resolveOperands(lower, builder.getIndexType(), result.operands))
2187     return failure();
2188 
2189   SmallVector<OpAsmParser::OperandType, 4> upper;
2190   if (parser.parseKeyword("to") ||
2191       parser.parseOperandList(upper, ivs.size(),
2192                               OpAsmParser::Delimiter::Paren) ||
2193       parser.resolveOperands(upper, builder.getIndexType(), result.operands))
2194     return failure();
2195 
2196   // Parse step values.
2197   SmallVector<OpAsmParser::OperandType, 4> steps;
2198   if (parser.parseKeyword("step") ||
2199       parser.parseOperandList(steps, ivs.size(),
2200                               OpAsmParser::Delimiter::Paren) ||
2201       parser.resolveOperands(steps, builder.getIndexType(), result.operands))
2202     return failure();
2203 
2204   // Parse input tensors.
2205   SmallVector<OpAsmParser::OperandType, 4> inputs, input_region_args;
2206   SmallVector<Type, 4> inputTypes;
2207   if (succeeded(parser.parseOptionalKeyword("ins"))) {
2208     llvm::SMLoc inputsOperandsLoc = parser.getCurrentLocation();
2209 
2210     if (parser.parseAssignmentListWithTypes(input_region_args, inputs,
2211                                             inputTypes))
2212       return failure();
2213 
2214     if (parser.resolveOperands(inputs, inputTypes, inputsOperandsLoc,
2215                                result.operands))
2216       return failure();
2217   }
2218 
2219   // Parse output tensors.
2220   SmallVector<OpAsmParser::OperandType, 4> outputs, output_region_args;
2221   SmallVector<Type, 4> outputTypes;
2222   if (succeeded(parser.parseOptionalKeyword("outs"))) {
2223     llvm::SMLoc outputsOperandsLoc = parser.getCurrentLocation();
2224 
2225     if (parser.parseAssignmentListWithTypes(output_region_args, outputs,
2226                                             outputTypes))
2227       return failure();
2228 
2229     if (parser.resolveOperands(outputs, outputTypes, outputsOperandsLoc,
2230                                result.operands))
2231       return failure();
2232     for (Type outputType : outputTypes)
2233       if (outputType.isa<RankedTensorType>())
2234         result.addTypes(outputType);
2235   }
2236 
2237   // Parse attributes.
2238   SmallVector<Attribute, 4> iterTypes;
2239   if (succeeded(parser.parseOptionalKeyword("iterators"))) {
2240     StringAttr iterType;
2241 
2242     if (parser.parseLSquare() || parser.parseAttribute(iterType))
2243       return failure();
2244     iterTypes.push_back(iterType);
2245     for (int i = 1, e = ivs.size(); i < e; ++i) {
2246       if (parser.parseComma() || parser.parseAttribute(iterType))
2247         return failure();
2248       iterTypes.push_back(iterType);
2249     }
2250     if (parser.parseRSquare())
2251       return failure();
2252   } else {
2253     auto parallelIter = builder.getStringAttr(getParallelIteratorTypeName());
2254     iterTypes = SmallVector<Attribute, 4>(ivs.size(), parallelIter);
2255   }
2256   result.addAttribute(getIteratorTypesAttrName(),
2257                       builder.getArrayAttr(iterTypes));
2258   result.addAttribute(
2259       TiledLoopOp::getOperandSegmentSizeAttr(),
2260       builder.getI32VectorAttr({static_cast<int32_t>(lower.size()),
2261                                 static_cast<int32_t>(upper.size()),
2262                                 static_cast<int32_t>(steps.size()),
2263                                 static_cast<int32_t>(inputs.size()),
2264                                 static_cast<int32_t>(outputs.size())}));
2265 
2266   // Parse the body.
2267   Region *body = result.addRegion();
2268 
2269   SmallVector<Type, 4> region_types(ivs.size(), builder.getIndexType());
2270   region_types.append(inputTypes);
2271   region_types.append(outputTypes);
2272 
2273   SmallVector<OpAsmParser::OperandType, 4> region_args(ivs);
2274   region_args.append(input_region_args);
2275   region_args.append(output_region_args);
2276 
2277   if (parser.parseRegion(*body, region_args, region_types))
2278     return failure();
2279 
2280   // Parse optional attributes.
2281   parser.parseOptionalAttrDict(result.attributes);
2282 
2283   return success();
2284 }
2285 
2286 Region &TiledLoopOp::getLoopBody() { return region(); }
2287 
2288 LogicalResult TiledLoopOp::moveOutOfLoop(ArrayRef<Operation *> ops) {
2289   for (auto *op : ops)
2290     op->moveBefore(*this);
2291   return success();
2292 }
2293 
2294 bool TiledLoopOp::isDefinedOutsideOfLoop(Value value) {
2295   return !region().isAncestor(value.getParentRegion());
2296 }
2297 
2298 static LogicalResult verify(TiledLoopOp op) {
2299   // Check if iterator types are provided for every loop dimension.
2300   if (op.iterator_types().size() != op.getNumLoops())
2301     return op.emitOpError("expected iterator types array attribute size = ")
2302            << op.iterator_types().size()
2303            << " to match the number of loops = " << op.getNumLoops();
2304 
2305   // Check if types of input arguments match region args types.
2306   for (auto &item :
2307        llvm::enumerate(llvm::zip(op.inputs(), op.getRegionInputArgs()))) {
2308     Value input, inputRegionArg;
2309     unsigned index = item.index();
2310     std::tie(input, inputRegionArg) = item.value();
2311     if (input.getType() != inputRegionArg.getType())
2312       return op.emitOpError("expected input arg ")
2313              << index << " with type = " << input.getType()
2314              << " to match region arg " << index + op.getNumLoops()
2315              << " type = " << inputRegionArg.getType();
2316   }
2317 
2318   // Check if types of input arguments match region args types.
2319   for (auto &item :
2320        llvm::enumerate(llvm::zip(op.outputs(), op.getRegionOutputArgs()))) {
2321     Value output, outputRegionArg;
2322     unsigned index = item.index();
2323     std::tie(output, outputRegionArg) = item.value();
2324     if (output.getType() != outputRegionArg.getType())
2325       return op.emitOpError("expected output arg ")
2326              << index << " with type = " << output.getType()
2327              << " to match region arg "
2328              << index + op.getNumLoops() + op.inputs().size()
2329              << " type = " << outputRegionArg.getType();
2330   }
2331   return success();
2332 }
2333 
2334 namespace {
2335 
2336 static constexpr int64_t kNoMatch = -1;
2337 
2338 // Folds away TiledLoopOp inputs if they have no uses within the body.
2339 //
2340 // Example:
2341 //
2342 // %0 = linalg.tiled_loop ...  ins (%in_ = %in: tensor<...>,
2343 //                                  %in_buf_ = %in_buf: memref<...>) {...}
2344 // Becomes
2345 //
2346 // linalg.tiled_loop ...  ins (%in_buf_ = %in_buf: memref<...>) {...}
2347 struct TiledLoopInputsFolder : public OpRewritePattern<linalg::TiledLoopOp> {
2348   using OpRewritePattern<linalg::TiledLoopOp>::OpRewritePattern;
2349 
2350   LogicalResult matchAndRewrite(linalg::TiledLoopOp tiledLoop,
2351                                 PatternRewriter &rewriter) const final {
2352     SmallVector<Value, 2> newInputs, regionInputTensorArgs;
2353     // Store ids of the corresponding old and new input operands.
2354     SmallVector<int64_t, 2> oldInputIdToNew(tiledLoop.inputs().size(),
2355                                             kNoMatch);
2356     for (auto en : llvm::enumerate(
2357              llvm::zip(tiledLoop.inputs(), tiledLoop.getRegionInputArgs()))) {
2358       Value in, bbArg;
2359       size_t index = en.index();
2360       std::tie(in, bbArg) = en.value();
2361       if (!bbArg.use_empty()) {
2362         oldInputIdToNew[index] = newInputs.size();
2363         newInputs.push_back(in);
2364       }
2365     }
2366     if (newInputs.size() == tiledLoop.inputs().size())
2367       return failure();
2368     Location loc = tiledLoop.getLoc();
2369     auto newTiledLoop = rewriter.create<TiledLoopOp>(
2370         loc, tiledLoop.lowerBound(), tiledLoop.upperBound(), tiledLoop.step(),
2371         newInputs, tiledLoop.outputs(), tiledLoop.iterator_types());
2372 
2373     // Clone the region.
2374     BlockAndValueMapping bvm;
2375     bvm.map(tiledLoop.getInductionVars(), newTiledLoop.getInductionVars());
2376     bvm.map(tiledLoop.getRegionOutputArgs(),
2377             newTiledLoop.getRegionOutputArgs());
2378     for (const auto &en : llvm::enumerate(oldInputIdToNew))
2379       if (en.value() != kNoMatch)
2380         bvm.map(tiledLoop.getRegionInputArgs()[en.index()],
2381                 newTiledLoop.getRegionInputArgs()[en.value()]);
2382     OpBuilder innerBuilder =
2383         OpBuilder::atBlockEnd(newTiledLoop.getBody(), rewriter.getListener());
2384     for (auto &op : *tiledLoop.getBody())
2385       innerBuilder.clone(op, bvm);
2386     rewriter.replaceOp(tiledLoop, newTiledLoop.getResults());
2387 
2388     return success();
2389   }
2390 };
2391 
2392 // Folds away TiledLoopOp output tensors when the following conditions are met:
2393 // * result of `linalg.tiled_loop` has no uses
2394 // * output tensor is the argument of `linalg.yield`
2395 //
2396 // Example:
2397 //
2398 // %0 = linalg.tiled_loop ...  outs (%o_ = %out: tensor<...>,
2399 //                                   %obuf_ = %out_buf: memref<...>) {
2400 //   ...
2401 //   linalg.yield %o_ : tensor ...
2402 // }
2403 //
2404 // Becomes
2405 //
2406 // linalg.tiled_loop ...  outs (%obuf_ = %out_buf: memref<...>) {
2407 //   ...
2408 //   linalg.yield
2409 // }
2410 struct TiledLoopResultsFolder : public OpRewritePattern<linalg::TiledLoopOp> {
2411   using OpRewritePattern<linalg::TiledLoopOp>::OpRewritePattern;
2412 
2413   LogicalResult matchAndRewrite(linalg::TiledLoopOp tiledLoop,
2414                                 PatternRewriter &rewriter) const final {
2415     if (tiledLoop.getNumResults() == 0)
2416       return failure();
2417 
2418     Block *block = tiledLoop.getBody();
2419     auto yieldOp = cast<linalg::YieldOp>(block->getTerminator());
2420 
2421     // Match the pattern and collect output buffers that will replace the output
2422     // tensors and also the ops that will be ignored when cloning the body.
2423     SmallVector<Value, 2> newOutputOperands, newYieldArgs;
2424     int resultId = 0;
2425     // Store ids of the corresponding old and new output operands.
2426     SmallVector<int64_t, 2> oldOutputIdToNew(tiledLoop.outputs().size(),
2427                                              kNoMatch);
2428     // Store ids of the corresponding old and new results.
2429     SmallVector<int64_t, 2> oldResultIdToNew(tiledLoop.getNumResults(),
2430                                              kNoMatch);
2431     SmallVector<Value, 2> resultReplacement(tiledLoop.getNumResults());
2432     for (auto en : llvm::enumerate(
2433              llvm::zip(tiledLoop.outputs(), tiledLoop.getRegionOutputArgs()))) {
2434       size_t index = en.index();
2435       Value out = std::get<0>(en.value());
2436       Value outRegionArg = std::get<1>(en.value());
2437 
2438       if (!out.getType().isa<RankedTensorType>()) {
2439         oldOutputIdToNew[index] = newOutputOperands.size();
2440         newOutputOperands.push_back(out);
2441         continue;
2442       }
2443       Value result = tiledLoop.getResult(resultId);
2444       Value yieldArg = yieldOp.getOperand(resultId);
2445       if (yieldArg != outRegionArg || !result.use_empty()) {
2446         oldOutputIdToNew[index] = newOutputOperands.size();
2447         oldResultIdToNew[resultId] = newYieldArgs.size();
2448         resultReplacement[resultId] = out;
2449         newOutputOperands.push_back(out);
2450         newYieldArgs.push_back(yieldArg);
2451       }
2452       ++resultId;
2453     }
2454     if (newOutputOperands.size() == tiledLoop.outputs().size())
2455       return failure();
2456 
2457     Location loc = tiledLoop.getLoc();
2458     auto newTiledLoop = rewriter.create<TiledLoopOp>(
2459         loc, tiledLoop.lowerBound(), tiledLoop.upperBound(), tiledLoop.step(),
2460         tiledLoop.inputs(), newOutputOperands, tiledLoop.iterator_types());
2461 
2462     // Clone the region.
2463     BlockAndValueMapping bvm;
2464     bvm.map(tiledLoop.getInductionVars(), newTiledLoop.getInductionVars());
2465     bvm.map(tiledLoop.getRegionInputArgs(), newTiledLoop.getRegionInputArgs());
2466     for (const auto &en : llvm::enumerate(oldOutputIdToNew)) {
2467       if (en.value() != kNoMatch)
2468         bvm.map(tiledLoop.getRegionOutputArgs()[en.index()],
2469                 newTiledLoop.getRegionOutputArgs()[en.value()]);
2470       else
2471         bvm.map(tiledLoop.getRegionOutputArgs()[en.index()],
2472                 tiledLoop.outputs()[en.index()]);
2473     }
2474     OpBuilder innerBuilder =
2475         OpBuilder::atBlockEnd(newTiledLoop.getBody(), rewriter.getListener());
2476     for (auto &op : tiledLoop.getBody()->without_terminator())
2477       innerBuilder.clone(op, bvm);
2478     innerBuilder.create<linalg::YieldOp>(
2479         loc, llvm::to_vector<2>(llvm::map_range(
2480                  newYieldArgs, [&](Value arg) { return bvm.lookup(arg); })));
2481 
2482     for (const auto &en : llvm::enumerate(oldResultIdToNew))
2483       if (en.value() != kNoMatch)
2484         resultReplacement[en.index()] = newTiledLoop.getResult(en.value());
2485     rewriter.replaceOp(tiledLoop, resultReplacement);
2486 
2487     return success();
2488   }
2489 };
2490 } // namespace
2491 
2492 void TiledLoopOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
2493                                               MLIRContext *context) {
2494   results.insert<TiledLoopInputsFolder, TiledLoopResultsFolder>(context);
2495 }
2496 
2497 LogicalResult TiledLoopOp::fold(ArrayRef<Attribute>,
2498                                 SmallVectorImpl<OpFoldResult> &) {
2499   return foldMemRefCastInTiledLoopOp(*this);
2500 }
2501 
2502 //===----------------------------------------------------------------------===//
2503 // IndexOp
2504 //===----------------------------------------------------------------------===//
2505 
2506 static LogicalResult verify(IndexOp op) {
2507   auto linalgOp = dyn_cast<LinalgOp>(op->getParentOp());
2508   if (!linalgOp)
2509     return op.emitOpError("expected parent op with LinalgOp interface");
2510   if (linalgOp.getNumLoops() <= op.dim())
2511     return op.emitOpError("expected dim (")
2512            << op.dim() << ") to be lower than the number of loops ("
2513            << linalgOp.getNumLoops() << ") of the enclosing LinalgOp";
2514   return success();
2515 }
2516 
2517 /////// Operations corresponding to library calls defined with Tablegen ////////
2518 
2519 template <typename LinalgPoolingOp>
2520 static LogicalResult verifyStrideOrDilation(LinalgPoolingOp op,
2521                                             ArrayRef<Attribute> attrs,
2522                                             bool isStride) {
2523   auto strideOrDilation = isStride ? "stride" : "dilation";
2524   if (attrs.size() != op.getNumWindowLoops())
2525     return op.emitOpError("expects num ")
2526            << strideOrDilation
2527            << "s equal to number of window dimensions: " << attrs.size()
2528            << " vs " << op.getNumWindowLoops();
2529   return success();
2530 }
2531 
2532 void ConvOp::getEffects(
2533     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
2534         &effects) {
2535   effects.emplace_back(MemoryEffects::Read::get(), input(),
2536                        SideEffects::DefaultResource::get());
2537   effects.emplace_back(MemoryEffects::Read::get(), filter(),
2538                        SideEffects::DefaultResource::get());
2539   effects.emplace_back(MemoryEffects::Write::get(), output(),
2540                        SideEffects::DefaultResource::get());
2541 }
2542 
2543 static LogicalResult verify(ConvOp op) {
2544   auto oType = op.output().getType().cast<MemRefType>();
2545   auto fType = op.filter().getType().cast<MemRefType>();
2546   auto iType = op.input().getType().cast<MemRefType>();
2547   if (oType.getElementType() != iType.getElementType() ||
2548       oType.getElementType() != fType.getElementType())
2549     return op.emitOpError("expects memref elemental types to match");
2550   if (oType.getRank() != iType.getRank() || oType.getRank() != fType.getRank())
2551     return op.emitOpError("expects memref ranks to match");
2552   if (auto strides = op.strides()) {
2553     if (failed(verifyStrideOrDilation(op, strides->getValue(),
2554                                       /*isStride=*/true)))
2555       return failure();
2556   }
2557   if (auto dilations = op.dilations()) {
2558     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
2559                                       /*isStride=*/false)))
2560       return failure();
2561   }
2562   return success();
2563 }
2564 
2565 template <typename PoolingOp>
2566 static LogicalResult verifySingleInputPoolingOp(PoolingOp op) {
2567   auto inputType = op.input().getType().template cast<MemRefType>();
2568   auto outputType = op.output().getType().template cast<MemRefType>();
2569   if (outputType.getElementType() != inputType.getElementType())
2570     return op.emitOpError("expects memref elemental types to match");
2571 
2572   auto windowDimsType = op.windowDims().getType().template cast<MemRefType>();
2573   if (outputType.getRank() != inputType.getRank() ||
2574       outputType.getRank() != windowDimsType.getRank())
2575     return op.emitOpError("expects memref ranks to match");
2576 
2577   if (auto strides = op.strides()) {
2578     if (failed(verifyStrideOrDilation(op, strides->getValue(),
2579                                       /*isStride=*/true)))
2580       return failure();
2581   }
2582   if (auto dilations = op.dilations()) {
2583     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
2584                                       /*isStride=*/false)))
2585       return failure();
2586   }
2587   return success();
2588 }
2589 
2590 #define DEFINE_POOLING_OP_GET_EFFECTS(OP_NAME)                                 \
2591   void OP_NAME::getEffects(                                                    \
2592       SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>      \
2593           &effects) {                                                          \
2594     effects.emplace_back(MemoryEffects::Read::get(), input(),                  \
2595                          SideEffects::DefaultResource::get());                 \
2596     effects.emplace_back(MemoryEffects::Write::get(), output(),                \
2597                          SideEffects::DefaultResource::get());                 \
2598   }
2599 
2600 static LogicalResult verify(PoolingMaxOp op) {
2601   return verifySingleInputPoolingOp(op);
2602 }
2603 static LogicalResult verify(PoolingMinOp op) {
2604   return verifySingleInputPoolingOp(op);
2605 }
2606 static LogicalResult verify(PoolingSumOp op) {
2607   return verifySingleInputPoolingOp(op);
2608 }
2609 
2610 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMaxOp)
2611 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMinOp)
2612 DEFINE_POOLING_OP_GET_EFFECTS(PoolingSumOp)
2613 
2614 namespace {
2615 struct EraseDeadLinalgOp;
2616 struct FoldTensorCastOp;
2617 } // namespace
2618 
2619 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.tcgen.cpp.inc"
2620 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc"
2621 
2622 #define GET_OP_CLASSES
2623 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
2624 
2625 #define GET_OP_CLASSES
2626 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
2627 
2628 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
2629 /// Assumes `op` is a LinalgOp.
2630 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
2631                                  SmallVectorImpl<AffineExpr> &res) {
2632   if (!cast<LinalgOp>(op).iterator_types())
2633     return;
2634 
2635   unsigned dim = 0;
2636   MLIRContext *ctx = op->getContext();
2637   for (auto tn :
2638        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
2639     if (tn == iteratorTypeName)
2640       res.push_back(getAffineDimExpr(dim, ctx));
2641     ++dim;
2642   }
2643 }
2644 
2645 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
2646                                              unsigned rank,
2647                                              MLIRContext *context) {
2648   if (maybeMap)
2649     return maybeMap.getValue();
2650   if (rank == 0)
2651     return AffineMap::get(context);
2652   return AffineMap::getMultiDimIdentityMap(rank, context);
2653 }
2654 
2655 SmallVector<AffineExpr, 4>
2656 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
2657                                  MLIRContext *context) {
2658   SmallVector<AffineExpr, 4> res;
2659   res.reserve(num);
2660   for (unsigned i = 0; i < num; ++i)
2661     res.push_back(getAffineDimExpr(startIdx++, context));
2662   return res;
2663 }
2664 
2665 template <typename PoolingOp>
2666 SmallVector<AffineExpr, 4>
2667 mlir::linalg::weightedPoolingInputIndex(PoolingOp op,
2668                                         ArrayRef<AffineExpr> outputDims,
2669                                         ArrayRef<AffineExpr> windowDims) {
2670   assert(outputDims.size() == windowDims.size());
2671   SmallVector<AffineExpr, 4> res;
2672   res.reserve(outputDims.size());
2673   for (unsigned i = 0, e = outputDims.size(); i < e; ++i) {
2674     // TODO: add a level of indirection to linalg.generic.
2675     auto expr = op.getStride(i) * outputDims[i] +
2676                 op.getDilation(i) * windowDims[i] - op.getLowPad(i);
2677     res.push_back(expr);
2678   }
2679   return res;
2680 }
2681 
2682 #define INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(OP_TYPE)                      \
2683   template SmallVector<AffineExpr, 4>                                          \
2684   mlir::linalg::weightedPoolingInputIndex<OP_TYPE>(                            \
2685       OP_TYPE op, ArrayRef<AffineExpr> outputDims,                             \
2686       ArrayRef<AffineExpr> windowDims);
2687 
2688 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(ConvOp)
2689 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMaxOp)
2690 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMinOp)
2691 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingSumOp)
2692 
2693 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
2694                                                 ArrayRef<AffineExpr> b) {
2695   auto rangeA = llvm::make_range(a.begin(), a.end());
2696   auto rangeB = llvm::make_range(b.begin(), b.end());
2697   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
2698   return llvm::to_vector<4>(concatRanges);
2699 }
2700 
2701 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
2702   if (auto memref = t.dyn_cast<MemRefType>()) {
2703     ss << "view";
2704     for (auto size : memref.getShape())
2705       if (size < 0)
2706         ss << "sx";
2707       else
2708         ss << size << "x";
2709     appendMangledType(ss, memref.getElementType());
2710   } else if (auto vec = t.dyn_cast<VectorType>()) {
2711     ss << "vector";
2712     llvm::interleave(
2713         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
2714     appendMangledType(ss, vec.getElementType());
2715   } else if (t.isSignlessIntOrIndexOrFloat()) {
2716     ss << t;
2717   } else {
2718     llvm_unreachable("Invalid type for linalg library name mangling");
2719   }
2720 }
2721 
2722 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
2723   assert(isa<LinalgOp>(op));
2724   std::string name(op->getName().getStringRef().str());
2725   name.reserve(128);
2726   std::replace(name.begin(), name.end(), '.', '_');
2727   llvm::raw_string_ostream ss(name);
2728   ss << "_";
2729   auto types = op->getOperandTypes();
2730   llvm::interleave(
2731       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
2732       [&]() { ss << "_"; });
2733   return ss.str();
2734 }
2735 
2736 // TODO: Consider making all this boilerplate easy to autogenerate
2737 // with Tablegen. This seems a desirable property in the context of
2738 // OpInterfaces where a Linalg "named" op **isa** LinalgOp.
2739 OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) {
2740   if (succeeded(foldMemRefCast(*this)))
2741     return getResult();
2742   return foldReshapeOp(*this, operands);
2743 }
2744 OpFoldResult TensorReshapeOp::fold(ArrayRef<Attribute> operands) {
2745   return foldReshapeOp(*this, operands);
2746 }
2747 
2748 //===----------------------------------------------------------------------===//
2749 // Support for named Linalg ops defined in ods-gen.
2750 //===----------------------------------------------------------------------===//
2751 
2752 /// Generic entry point to create the block for the region of a LinalgOp.
2753 /// This is used by both named structured ops created by ods-gen and by manually
2754 /// defined C++ ops.
2755 /// This is used by both builders and parsers.
2756 /// This function creates the block in the region with arguments corresponding
2757 /// to the elemental types of `inputTypes` and `outputTypes`, which are asserted
2758 /// to be ShapedType.
2759 template <typename NamedStructuredOpType>
2760 static void
2761 fillStructuredOpRegion(OpBuilder &opBuilder, Region &region,
2762                        TypeRange inputTypes, TypeRange outputTypes,
2763                        ValueRange captures,
2764                        std::function<void(unsigned, unsigned)> errorHandler) {
2765   assert(llvm::all_of(inputTypes, [](Type t) { return t.isa<ShapedType>(); }));
2766   assert(llvm::all_of(outputTypes, [](Type t) { return t.isa<ShapedType>(); }));
2767 
2768   // TODO: atm all operands go through getElementTypeOrSelf,
2769   // reconsider when we have evidence we need to.
2770   SmallVector<Type, 8> argTypes;
2771   for (auto containers : {inputTypes, outputTypes})
2772     for (auto t : containers)
2773       argTypes.push_back(getElementTypeOrSelf(t));
2774 
2775   // RAII.
2776   OpBuilder::InsertionGuard guard(opBuilder);
2777   Block *body = opBuilder.createBlock(&region, /*insertPt=*/{}, argTypes);
2778   unsigned actual = body->getNumArguments();
2779   unsigned expected = NamedStructuredOpType::getNumRegionArgs();
2780   if (expected != actual) {
2781     if (errorHandler)
2782       errorHandler(expected, actual);
2783     return;
2784   }
2785 
2786   opBuilder.setInsertionPointToStart(body);
2787   mlir::edsc::ScopedContext scope(opBuilder, opBuilder.getUnknownLoc());
2788   NamedStructuredOpType::regionBuilder(*body, captures);
2789 
2790   // indexing_maps is an auto-generated method.
2791 
2792   // iterator_types is an auto-generated method.
2793 }
2794 
2795 /// Generic entry point to create both the region and the block of a LinalgOp.
2796 template <typename NamedStructuredOpType>
2797 void createAndFillStructuredOpRegion(OpBuilder &opBuilder,
2798                                      OperationState &result,
2799                                      TypeRange inputTypes,
2800                                      TypeRange outputTypes,
2801                                      ValueRange captures) {
2802   Region &region = *result.addRegion();
2803   fillStructuredOpRegion<NamedStructuredOpType>(
2804       opBuilder, region, inputTypes, outputTypes, captures,
2805       [&](unsigned expected, unsigned actual) {
2806         assert(expected != actual && "incorrect number of arguments");
2807       });
2808 }
2809 
2810 /// Common parsing used for both named structured ops created by ods-gen and by
2811 /// manually defined C++ ops. Does not handle regions.
2812 static ParseResult
2813 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
2814                              SmallVectorImpl<Type> &inputTypes,
2815                              SmallVectorImpl<Type> &outputTypes) {
2816   llvm::SMLoc inputsOperandsLoc, outputsOperandsLoc;
2817   SmallVector<OpAsmParser::OperandType, 4> inputsOperands, outputsOperands;
2818 
2819   parser.parseOptionalAttrDict(result.attributes);
2820 
2821   if (succeeded(parser.parseOptionalKeyword("ins"))) {
2822     if (parser.parseLParen())
2823       return failure();
2824 
2825     inputsOperandsLoc = parser.getCurrentLocation();
2826     if (parser.parseOperandList(inputsOperands) ||
2827         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
2828       return failure();
2829   }
2830 
2831   if (succeeded(parser.parseOptionalKeyword("outs"))) {
2832     outputsOperandsLoc = parser.getCurrentLocation();
2833     if (parser.parseLParen() || parser.parseOperandList(outputsOperands) ||
2834         parser.parseColonTypeList(outputTypes) || parser.parseRParen())
2835       return failure();
2836   }
2837 
2838   if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
2839                              result.operands) ||
2840       parser.resolveOperands(outputsOperands, outputTypes, outputsOperandsLoc,
2841                              result.operands))
2842     return failure();
2843 
2844   result.addAttribute("operand_segment_sizes",
2845                       parser.getBuilder().getI32VectorAttr(
2846                           {static_cast<int32_t>(inputsOperands.size()),
2847                            static_cast<int32_t>(outputsOperands.size())}));
2848   return success();
2849 }
2850 
2851 template <typename NamedStructuredOpType>
2852 static void printCommonStructuredOpParts(OpAsmPrinter &p,
2853                                          NamedStructuredOpType op) {
2854   if (!op.inputs().empty())
2855     p << " ins(" << op.inputs() << " : " << op.inputs().getTypes() << ")";
2856   if (!op.outputs().empty())
2857     p << " outs(" << op.outputs() << " : " << op.outputs().getTypes() << ")";
2858 }
2859 
2860 //===----------------------------------------------------------------------===//
2861 // Specific parsing and printing for named structured ops created by ods-gen.
2862 //===----------------------------------------------------------------------===//
2863 
2864 template <typename NamedStructuredOpType>
2865 static ParseResult
2866 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
2867                              TypeRange inputTypes, TypeRange outputTypes,
2868                              ArrayRef<OpAsmParser::OperandType> captures) {
2869   ParseResult res = success();
2870   OpBuilder opBuilder(parser.getBuilder().getContext());
2871   // Resolve `captures` into `capturedValues` at parse time so we can build the
2872   // region with captures.
2873   SmallVector<Value> capturedValues;
2874   fillStructuredOpRegion<NamedStructuredOpType>(
2875       opBuilder, region, inputTypes, outputTypes, capturedValues,
2876       [&](unsigned expected, unsigned actual) {
2877         res = parser.emitError(
2878             parser.getCurrentLocation(),
2879             llvm::formatv("[parseNamedStructuredOpRegion] ods-gen generated "
2880                           "region expects {0} args, got {1}",
2881                           expected, actual));
2882         region.front().dump();
2883       });
2884   return res;
2885 }
2886 
2887 static ParseResult
2888 parseNamedStructuredOpResults(OpAsmParser &parser,
2889                               SmallVectorImpl<Type> &resultTypes) {
2890   if (succeeded(parser.parseOptionalArrow()))
2891     if (parser.parseTypeList(resultTypes))
2892       return failure();
2893   return success();
2894 }
2895 
2896 template <typename NamedStructuredOpType>
2897 static ParseResult
2898 parseNamedStructuredOp(OpAsmParser &parser, OperationState &result,
2899                        ArrayRef<OpAsmParser::OperandType> captures) {
2900   // TODO: Enable when ods-gen supports captures.
2901   assert(captures.empty() && "unexpected captures for named structured ops");
2902   SmallVector<Type, 1> inputTypes, outputTypes;
2903   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
2904     return failure();
2905 
2906   // TODO: consider merging results parsing into region parsing.
2907   // Need to wait for declarative assembly resolution to decide.
2908   SmallVector<Type, 1> outputTensorsTypes;
2909   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
2910     return failure();
2911   result.addTypes(outputTensorsTypes);
2912 
2913   std::unique_ptr<Region> region = std::make_unique<Region>();
2914   if (parseNamedStructuredOpRegion<NamedStructuredOpType>(
2915           parser, *region, inputTypes, outputTypes, captures))
2916     return failure();
2917   result.addRegion(std::move(region));
2918 
2919   return success();
2920 }
2921 
2922 static void printNamedStructuredOpResults(OpAsmPrinter &p,
2923                                           TypeRange resultTypes) {
2924   if (resultTypes.empty())
2925     return;
2926   p.printOptionalArrowTypeList(resultTypes);
2927 }
2928 
2929 template <typename NamedStructuredOpType>
2930 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op) {
2931   p << op.getOperationName();
2932   p.printOptionalAttrDict(
2933       op->getAttrs(),
2934       /*elidedAttrs=*/{"operand_segment_sizes",
2935                        // See generated code in mlir-linalg-yaml-gen.cpp
2936                        "linalg.memoized_indexing_maps"});
2937 
2938   // Printing is shared with generic ops, except for the region and
2939   // attributes.
2940   printCommonStructuredOpParts(p, op);
2941 
2942   // Results printing.
2943   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
2944 
2945   // Region is elided.
2946 }
2947 
2948 template <typename NamedStructuredOpType>
2949 static LogicalResult verifyNamedStructuredOp(NamedStructuredOpType op) {
2950   return verifyGenericOp<NamedStructuredOpType>(op);
2951 }
2952 
2953 //===----------------------------------------------------------------------===//
2954 // Canonicalizers and Folders.
2955 //===----------------------------------------------------------------------===//
2956 
2957 namespace {
2958 struct EraseDeadLinalgOp : public OpInterfaceRewritePattern<LinalgOp> {
2959   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2960 
2961   LogicalResult matchAndRewrite(LinalgOp op,
2962                                 PatternRewriter &rewriter) const override {
2963     for (Value v : op.getShapedOperands()) {
2964       // Linalg "inputs" may be either tensor or memref type.
2965       // tensor<0xelt_type> is a convention that may not always mean
2966       // "0 iterations". Only erase in cases we see memref<...x0x...>.
2967       auto mt = v.getType().dyn_cast<MemRefType>();
2968       if (!mt)
2969         continue;
2970       if (llvm::is_contained(mt.getShape(), 0)) {
2971         rewriter.eraseOp(op);
2972         return success();
2973       }
2974     }
2975     return failure();
2976   }
2977 };
2978 
2979 struct FoldTensorCastOp : public OpInterfaceRewritePattern<LinalgOp> {
2980   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2981 
2982   LogicalResult matchAndRewrite(LinalgOp op,
2983                                 PatternRewriter &rewriter) const override {
2984     // If no operand comes from a tensor::CastOp and can be folded then fail.
2985     bool hasTensorCastOperand =
2986         llvm::any_of(op.getShapedOperands(), [&](Value v) {
2987           if (v.isa<BlockArgument>())
2988             return false;
2989           auto castOp = v.getDefiningOp<tensor::CastOp>();
2990           return castOp && canFoldIntoConsumerOp(castOp);
2991         });
2992     if (!hasTensorCastOperand)
2993       return failure();
2994 
2995     SmallVector<Type, 4> newResultTypes;
2996     newResultTypes.reserve(op->getNumResults());
2997     SmallVector<Value, 4> newOperands;
2998     newOperands.reserve(op->getNumOperands());
2999     // Inputs may fold.
3000     for (Value v : op.getInputs()) {
3001       auto tensorCastOp = v.getDefiningOp<tensor::CastOp>();
3002       newOperands.push_back(
3003           canFoldIntoConsumerOp(tensorCastOp) ? tensorCastOp.source() : v);
3004     }
3005     // Init tensors may fold, in which case the resultType must also change.
3006     for (Value v : op.getOutputs()) {
3007       auto tensorCastOp = v.getDefiningOp<tensor::CastOp>();
3008       bool fold = canFoldIntoConsumerOp(tensorCastOp);
3009       newOperands.push_back(fold ? tensorCastOp.getOperand() : v);
3010       newResultTypes.push_back(newOperands.back().getType());
3011     }
3012     auto extraOperands = op.getAssumedNonShapedOperands();
3013     newOperands.append(extraOperands.begin(), extraOperands.end());
3014     // Clone op.
3015     Operation *newOp =
3016         op.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
3017     SmallVector<Value, 4> replacements;
3018     replacements.reserve(newOp->getNumResults());
3019     for (auto result : llvm::zip(op->getResults(), newOp->getResults())) {
3020       Value oldResult = std::get<0>(result);
3021       Value newResult = std::get<1>(result);
3022       if (newResult.getType() != oldResult.getType()) {
3023         replacements.push_back(rewriter.create<tensor::CastOp>(
3024             op->getLoc(), oldResult.getType(), newResult));
3025       } else {
3026         replacements.push_back(newResult);
3027       }
3028     }
3029     rewriter.replaceOp(op, replacements);
3030 
3031     return success();
3032   }
3033 };
3034 } // namespace
3035 
3036 namespace {
3037 // Deduplicate redundant args of a linalg op.
3038 // An arg is redundant if it has the same Value and indexing map as another.
3039 struct DeduplicateInputs : public OpInterfaceRewritePattern<LinalgOp> {
3040   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
3041 
3042   LogicalResult matchAndRewrite(LinalgOp op,
3043                                 PatternRewriter &rewriter) const override {
3044     // This pattern reduces the number of arguments of an op, which breaks
3045     // the invariants of semantically charged named ops.
3046     if (!isa<GenericOp, IndexedGenericOp>(op))
3047       return failure();
3048 
3049     // Associate each input to an equivalent "canonical" input that has the same
3050     // Value and indexing map.
3051     //
3052     // In the non-duplicate case, input `i` will have canonical input `i`. But
3053     // in the case of duplicated inputs, the canonical input could be some other
3054     // input `< i`. That is, a later input will have some earlier input as its
3055     // canonical input.
3056     llvm::SmallDenseMap<std::pair<Value, AffineMap>, int> canonicalInput;
3057     // For later remapping tasks like deduplicating payload block arguments,
3058     // having a simple "inputIndex -> canonicalInputIndex" integer mapping is
3059     // convenient.
3060     SmallVector<int, 6> canonicalInputIndices;
3061     for (int i = 0, e = op.getNumInputs(); i != e; i++) {
3062       Value input = op.getInput(i);
3063       AffineMap indexingMap = op.getInputIndexingMap(i);
3064       // STL-like maps have a convenient behavior for our use case here. In the
3065       // case of duplicate keys, the insertion is rejected, and the returned
3066       // iterator gives access to the value already in the map.
3067       auto pair = canonicalInput.insert({{input, indexingMap}, i});
3068       canonicalInputIndices.push_back(pair.first->second);
3069     }
3070 
3071     // If there are no duplicate args, then bail out.
3072     if (canonicalInput.size() == op.getNumInputs())
3073       return failure();
3074 
3075     // The operands for the newly canonicalized op.
3076     SmallVector<Value, 6> newOperands;
3077     for (auto v : llvm::enumerate(op.getInputs()))
3078       if (canonicalInputIndices[v.index()] == static_cast<int>(v.index()))
3079         newOperands.push_back(v.value());
3080     llvm::append_range(newOperands, op.getOutputs());
3081     llvm::append_range(newOperands, op.getAssumedNonShapedOperands());
3082 
3083     // Clone the old op with new operands.
3084     Operation *newOp =
3085         op.clone(rewriter, op->getLoc(), op->getResultTypes(), newOperands);
3086     auto newLinalgOp = cast<LinalgOp>(newOp);
3087 
3088     // Repair the indexing maps by filtering out the ones that have been
3089     // eliminated.
3090     SmallVector<AffineMap, 6> newIndexingMaps;
3091     for (int i = 0, e = newLinalgOp.getNumInputs(); i != e; i++)
3092       if (canonicalInputIndices[i] == i)
3093         newIndexingMaps.push_back(newLinalgOp.getIndexingMap(i));
3094     for (int i = 0, e = newLinalgOp.getNumOutputs(); i != e; i++)
3095       newIndexingMaps.push_back(newLinalgOp.getOutputIndexingMap(i));
3096     newOp->setAttr("indexing_maps",
3097                    rewriter.getAffineMapArrayAttr(newIndexingMaps));
3098 
3099     // Set the number of inputs to the new value. The `clone` call above kept
3100     // the value from the original op.
3101     newLinalgOp.setNumInputs(canonicalInput.size());
3102 
3103     // linalg.indexed_generic payloads have additional arguments prepended to
3104     // the block arg list.
3105     int bbArgBaseOffset = newLinalgOp.getNumPayloadInductionVariables();
3106 
3107     // Repair the payload entry block by RAUW'ing redundant arguments and
3108     // erasing them.
3109     Block &payload = newOp->getRegion(0).front();
3110     for (int i = 0, e = op.getNumInputs(); i < e; i++) {
3111       // Iterate in reverse, so that we erase later args first, preventing the
3112       // argument list from shifting unexpectedly and invalidating all our
3113       // indices.
3114       int reversed = e - i - 1;
3115       int canonicalIndex = canonicalInputIndices[reversed];
3116       if (canonicalInputIndices[reversed] == reversed)
3117         continue;
3118       payload.getArgument(bbArgBaseOffset + reversed)
3119           .replaceAllUsesWith(
3120               payload.getArgument(bbArgBaseOffset + canonicalIndex));
3121       payload.eraseArgument(bbArgBaseOffset + reversed);
3122     }
3123 
3124     rewriter.replaceOp(op, newOp->getResults());
3125     return success();
3126   }
3127 };
3128 
3129 /// Remove generic/indexed_generic operations (on tensors) that are just copying
3130 /// the values from inputs to the results. Requirements are
3131 /// 1) All iterator types are parallel
3132 /// 2) The body contains just a yield operation with the yielded values being
3133 ///    the arguments corresponding to the operands.
3134 struct RemoveIdentityLinalgOps : public OpInterfaceRewritePattern<LinalgOp> {
3135   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
3136 
3137   LogicalResult matchAndRewrite(LinalgOp op,
3138                                 PatternRewriter &rewriter) const override {
3139     if (auto copyOp = dyn_cast<CopyOp>(*op)) {
3140       assert(copyOp.hasBufferSemantics());
3141       if (copyOp.input() == copyOp.output() &&
3142           copyOp.inputPermutation() == copyOp.outputPermutation()) {
3143         rewriter.eraseOp(op);
3144         return success();
3145       }
3146     }
3147 
3148     if (!isa<GenericOp, IndexedGenericOp>(op))
3149       return failure();
3150     if (!op.hasTensorSemantics())
3151       return failure();
3152     // Check all indexing maps are identity.
3153     if (llvm::any_of(op.getIndexingMaps(),
3154                      [](AffineMap map) { return !map.isIdentity(); }))
3155       return failure();
3156 
3157     // Check that the body of the linalg operation is just a linalg.yield
3158     // operation.
3159     Block &body = op->getRegion(0).front();
3160     if (!llvm::hasSingleElement(body))
3161       return failure();
3162     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
3163     if (!yieldOp)
3164       return failure();
3165 
3166     // Get the argument number of the returned values. That is the operand
3167     // number to use for replacing uses of this operation.
3168     unsigned numIndexArgs = op.getNumPayloadInductionVariables();
3169     SmallVector<Value, 4> returnedArgs;
3170     for (Value yieldVal : yieldOp.values()) {
3171       auto yieldArg = yieldVal.dyn_cast<BlockArgument>();
3172       if (!yieldArg || yieldArg.getOwner() != &body)
3173         return failure();
3174       unsigned argumentNumber = yieldArg.getArgNumber();
3175       if (argumentNumber < numIndexArgs)
3176         return failure();
3177       returnedArgs.push_back(op->getOperand(argumentNumber - numIndexArgs));
3178     }
3179     if (returnedArgs.size() != op.getOperation()->getNumResults())
3180       return failure();
3181     rewriter.replaceOp(op, returnedArgs);
3182     return success();
3183   }
3184 };
3185 } // namespace
3186 
3187 #define CANONICALIZERS_AND_FOLDERS(XXX)                                        \
3188   void XXX::getCanonicalizationPatterns(RewritePatternSet &results,            \
3189                                         MLIRContext *context) {                \
3190     results.add<DeduplicateInputs, EraseDeadLinalgOp, FoldTensorCastOp,        \
3191                 RemoveIdentityLinalgOps>(context);                             \
3192   }                                                                            \
3193                                                                                \
3194   LogicalResult XXX::fold(ArrayRef<Attribute>,                                 \
3195                           SmallVectorImpl<OpFoldResult> &) {                   \
3196     return foldMemRefCast(*this);                                              \
3197   }
3198 
3199 CANONICALIZERS_AND_FOLDERS(ConvOp)
3200 CANONICALIZERS_AND_FOLDERS(PoolingMaxOp)
3201 CANONICALIZERS_AND_FOLDERS(PoolingMinOp)
3202 CANONICALIZERS_AND_FOLDERS(PoolingSumOp)
3203 CANONICALIZERS_AND_FOLDERS(CopyOp)
3204 CANONICALIZERS_AND_FOLDERS(FillOp)
3205 CANONICALIZERS_AND_FOLDERS(GenericOp)
3206 
3207 // All named ops canonicalizers and folders are auto-generated in the
3208 // .cpp.inc.
3209