1 //===- AffineOps.cpp - MLIR Affine 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 #include "mlir/Dialect/Affine/IR/AffineOps.h"
10 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
11 #include "mlir/Dialect/MemRef/IR/MemRef.h"
12 #include "mlir/Dialect/Tensor/IR/Tensor.h"
13 #include "mlir/IR/AffineExprVisitor.h"
14 #include "mlir/IR/BlockAndValueMapping.h"
15 #include "mlir/IR/IntegerSet.h"
16 #include "mlir/IR/Matchers.h"
17 #include "mlir/IR/PatternMatch.h"
18 #include "mlir/Transforms/InliningUtils.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/TypeSwitch.h"
21 #include "llvm/Support/Debug.h"
22 
23 using namespace mlir;
24 
25 #define DEBUG_TYPE "affine-analysis"
26 
27 #include "mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc"
28 
29 /// A utility function to check if a value is defined at the top level of
30 /// `region` or is an argument of `region`. A value of index type defined at the
31 /// top level of a `AffineScope` region is always a valid symbol for all
32 /// uses in that region.
33 bool mlir::isTopLevelValue(Value value, Region *region) {
34   if (auto arg = value.dyn_cast<BlockArgument>())
35     return arg.getParentRegion() == region;
36   return value.getDefiningOp()->getParentRegion() == region;
37 }
38 
39 /// Checks if `value` known to be a legal affine dimension or symbol in `src`
40 /// region remains legal if the operation that uses it is inlined into `dest`
41 /// with the given value mapping. `legalityCheck` is either `isValidDim` or
42 /// `isValidSymbol`, depending on the value being required to remain a valid
43 /// dimension or symbol.
44 static bool
45 remainsLegalAfterInline(Value value, Region *src, Region *dest,
46                         const BlockAndValueMapping &mapping,
47                         function_ref<bool(Value, Region *)> legalityCheck) {
48   // If the value is a valid dimension for any other reason than being
49   // a top-level value, it will remain valid: constants get inlined
50   // with the function, transitive affine applies also get inlined and
51   // will be checked themselves, etc.
52   if (!isTopLevelValue(value, src))
53     return true;
54 
55   // If it's a top-level value because it's a block operand, i.e. a
56   // function argument, check whether the value replacing it after
57   // inlining is a valid dimension in the new region.
58   if (value.isa<BlockArgument>())
59     return legalityCheck(mapping.lookup(value), dest);
60 
61   // If it's a top-level value because it's defined in the region,
62   // it can only be inlined if the defining op is a constant or a
63   // `dim`, which can appear anywhere and be valid, since the defining
64   // op won't be top-level anymore after inlining.
65   Attribute operandCst;
66   return matchPattern(value.getDefiningOp(), m_Constant(&operandCst)) ||
67          value.getDefiningOp<memref::DimOp>() ||
68          value.getDefiningOp<tensor::DimOp>();
69 }
70 
71 /// Checks if all values known to be legal affine dimensions or symbols in `src`
72 /// remain so if their respective users are inlined into `dest`.
73 static bool
74 remainsLegalAfterInline(ValueRange values, Region *src, Region *dest,
75                         const BlockAndValueMapping &mapping,
76                         function_ref<bool(Value, Region *)> legalityCheck) {
77   return llvm::all_of(values, [&](Value v) {
78     return remainsLegalAfterInline(v, src, dest, mapping, legalityCheck);
79   });
80 }
81 
82 /// Checks if an affine read or write operation remains legal after inlining
83 /// from `src` to `dest`.
84 template <typename OpTy>
85 static bool remainsLegalAfterInline(OpTy op, Region *src, Region *dest,
86                                     const BlockAndValueMapping &mapping) {
87   static_assert(llvm::is_one_of<OpTy, AffineReadOpInterface,
88                                 AffineWriteOpInterface>::value,
89                 "only ops with affine read/write interface are supported");
90 
91   AffineMap map = op.getAffineMap();
92   ValueRange dimOperands = op.getMapOperands().take_front(map.getNumDims());
93   ValueRange symbolOperands =
94       op.getMapOperands().take_back(map.getNumSymbols());
95   if (!remainsLegalAfterInline(
96           dimOperands, src, dest, mapping,
97           static_cast<bool (*)(Value, Region *)>(isValidDim)))
98     return false;
99   if (!remainsLegalAfterInline(
100           symbolOperands, src, dest, mapping,
101           static_cast<bool (*)(Value, Region *)>(isValidSymbol)))
102     return false;
103   return true;
104 }
105 
106 /// Checks if an affine apply operation remains legal after inlining from `src`
107 /// to `dest`.
108 //  Use "unused attribute" marker to silence clang-tidy warning stemming from
109 //  the inability to see through "llvm::TypeSwitch".
110 template <>
111 bool LLVM_ATTRIBUTE_UNUSED
112 remainsLegalAfterInline(AffineApplyOp op, Region *src, Region *dest,
113                         const BlockAndValueMapping &mapping) {
114   // If it's a valid dimension, we need to check that it remains so.
115   if (isValidDim(op.getResult(), src))
116     return remainsLegalAfterInline(
117         op.getMapOperands(), src, dest, mapping,
118         static_cast<bool (*)(Value, Region *)>(isValidDim));
119 
120   // Otherwise it must be a valid symbol, check that it remains so.
121   return remainsLegalAfterInline(
122       op.getMapOperands(), src, dest, mapping,
123       static_cast<bool (*)(Value, Region *)>(isValidSymbol));
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // AffineDialect Interfaces
128 //===----------------------------------------------------------------------===//
129 
130 namespace {
131 /// This class defines the interface for handling inlining with affine
132 /// operations.
133 struct AffineInlinerInterface : public DialectInlinerInterface {
134   using DialectInlinerInterface::DialectInlinerInterface;
135 
136   //===--------------------------------------------------------------------===//
137   // Analysis Hooks
138   //===--------------------------------------------------------------------===//
139 
140   /// Returns true if the given region 'src' can be inlined into the region
141   /// 'dest' that is attached to an operation registered to the current dialect.
142   /// 'wouldBeCloned' is set if the region is cloned into its new location
143   /// rather than moved, indicating there may be other users.
144   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
145                        BlockAndValueMapping &valueMapping) const final {
146     // We can inline into affine loops and conditionals if this doesn't break
147     // affine value categorization rules.
148     Operation *destOp = dest->getParentOp();
149     if (!isa<AffineParallelOp, AffineForOp, AffineIfOp>(destOp))
150       return false;
151 
152     // Multi-block regions cannot be inlined into affine constructs, all of
153     // which require single-block regions.
154     if (!llvm::hasSingleElement(*src))
155       return false;
156 
157     // Side-effecting operations that the affine dialect cannot understand
158     // should not be inlined.
159     Block &srcBlock = src->front();
160     for (Operation &op : srcBlock) {
161       // Ops with no side effects are fine,
162       if (auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
163         if (iface.hasNoEffect())
164           continue;
165       }
166 
167       // Assuming the inlined region is valid, we only need to check if the
168       // inlining would change it.
169       bool remainsValid =
170           llvm::TypeSwitch<Operation *, bool>(&op)
171               .Case<AffineApplyOp, AffineReadOpInterface,
172                     AffineWriteOpInterface>([&](auto op) {
173                 return remainsLegalAfterInline(op, src, dest, valueMapping);
174               })
175               .Default([](Operation *) {
176                 // Conservatively disallow inlining ops we cannot reason about.
177                 return false;
178               });
179 
180       if (!remainsValid)
181         return false;
182     }
183 
184     return true;
185   }
186 
187   /// Returns true if the given operation 'op', that is registered to this
188   /// dialect, can be inlined into the given region, false otherwise.
189   bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
190                        BlockAndValueMapping &valueMapping) const final {
191     // Always allow inlining affine operations into a region that is marked as
192     // affine scope, or into affine loops and conditionals. There are some edge
193     // cases when inlining *into* affine structures, but that is handled in the
194     // other 'isLegalToInline' hook above.
195     Operation *parentOp = region->getParentOp();
196     return parentOp->hasTrait<OpTrait::AffineScope>() ||
197            isa<AffineForOp, AffineParallelOp, AffineIfOp>(parentOp);
198   }
199 
200   /// Affine regions should be analyzed recursively.
201   bool shouldAnalyzeRecursively(Operation *op) const final { return true; }
202 };
203 } // namespace
204 
205 //===----------------------------------------------------------------------===//
206 // AffineDialect
207 //===----------------------------------------------------------------------===//
208 
209 void AffineDialect::initialize() {
210   addOperations<AffineDmaStartOp, AffineDmaWaitOp,
211 #define GET_OP_LIST
212 #include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
213                 >();
214   addInterfaces<AffineInlinerInterface>();
215 }
216 
217 /// Materialize a single constant operation from a given attribute value with
218 /// the desired resultant type.
219 Operation *AffineDialect::materializeConstant(OpBuilder &builder,
220                                               Attribute value, Type type,
221                                               Location loc) {
222   return builder.create<arith::ConstantOp>(loc, type, value);
223 }
224 
225 /// A utility function to check if a value is defined at the top level of an
226 /// op with trait `AffineScope`. If the value is defined in an unlinked region,
227 /// conservatively assume it is not top-level. A value of index type defined at
228 /// the top level is always a valid symbol.
229 bool mlir::isTopLevelValue(Value value) {
230   if (auto arg = value.dyn_cast<BlockArgument>()) {
231     // The block owning the argument may be unlinked, e.g. when the surrounding
232     // region has not yet been attached to an Op, at which point the parent Op
233     // is null.
234     Operation *parentOp = arg.getOwner()->getParentOp();
235     return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
236   }
237   // The defining Op may live in an unlinked block so its parent Op may be null.
238   Operation *parentOp = value.getDefiningOp()->getParentOp();
239   return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
240 }
241 
242 /// Returns the closest region enclosing `op` that is held by an operation with
243 /// trait `AffineScope`; `nullptr` if there is no such region.
244 Region *mlir::getAffineScope(Operation *op) {
245   auto *curOp = op;
246   while (auto *parentOp = curOp->getParentOp()) {
247     if (parentOp->hasTrait<OpTrait::AffineScope>())
248       return curOp->getParentRegion();
249     curOp = parentOp;
250   }
251   return nullptr;
252 }
253 
254 // A Value can be used as a dimension id iff it meets one of the following
255 // conditions:
256 // *) It is valid as a symbol.
257 // *) It is an induction variable.
258 // *) It is the result of affine apply operation with dimension id arguments.
259 bool mlir::isValidDim(Value value) {
260   // The value must be an index type.
261   if (!value.getType().isIndex())
262     return false;
263 
264   if (auto *defOp = value.getDefiningOp())
265     return isValidDim(value, getAffineScope(defOp));
266 
267   // This value has to be a block argument for an op that has the
268   // `AffineScope` trait or for an affine.for or affine.parallel.
269   auto *parentOp = value.cast<BlockArgument>().getOwner()->getParentOp();
270   return parentOp && (parentOp->hasTrait<OpTrait::AffineScope>() ||
271                       isa<AffineForOp, AffineParallelOp>(parentOp));
272 }
273 
274 // Value can be used as a dimension id iff it meets one of the following
275 // conditions:
276 // *) It is valid as a symbol.
277 // *) It is an induction variable.
278 // *) It is the result of an affine apply operation with dimension id operands.
279 bool mlir::isValidDim(Value value, Region *region) {
280   // The value must be an index type.
281   if (!value.getType().isIndex())
282     return false;
283 
284   // All valid symbols are okay.
285   if (isValidSymbol(value, region))
286     return true;
287 
288   auto *op = value.getDefiningOp();
289   if (!op) {
290     // This value has to be a block argument for an affine.for or an
291     // affine.parallel.
292     auto *parentOp = value.cast<BlockArgument>().getOwner()->getParentOp();
293     return isa<AffineForOp, AffineParallelOp>(parentOp);
294   }
295 
296   // Affine apply operation is ok if all of its operands are ok.
297   if (auto applyOp = dyn_cast<AffineApplyOp>(op))
298     return applyOp.isValidDim(region);
299   // The dim op is okay if its operand memref/tensor is defined at the top
300   // level.
301   if (auto dimOp = dyn_cast<memref::DimOp>(op))
302     return isTopLevelValue(dimOp.source());
303   if (auto dimOp = dyn_cast<tensor::DimOp>(op))
304     return isTopLevelValue(dimOp.source());
305   return false;
306 }
307 
308 /// Returns true if the 'index' dimension of the `memref` defined by
309 /// `memrefDefOp` is a statically  shaped one or defined using a valid symbol
310 /// for `region`.
311 template <typename AnyMemRefDefOp>
312 static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index,
313                                     Region *region) {
314   auto memRefType = memrefDefOp.getType();
315   // Statically shaped.
316   if (!memRefType.isDynamicDim(index))
317     return true;
318   // Get the position of the dimension among dynamic dimensions;
319   unsigned dynamicDimPos = memRefType.getDynamicDimIndex(index);
320   return isValidSymbol(*(memrefDefOp.getDynamicSizes().begin() + dynamicDimPos),
321                        region);
322 }
323 
324 /// Returns true if the result of the dim op is a valid symbol for `region`.
325 template <typename OpTy>
326 static bool isDimOpValidSymbol(OpTy dimOp, Region *region) {
327   // The dim op is okay if its source is defined at the top level.
328   if (isTopLevelValue(dimOp.source()))
329     return true;
330 
331   // Conservatively handle remaining BlockArguments as non-valid symbols.
332   // E.g. scf.for iterArgs.
333   if (dimOp.source().template isa<BlockArgument>())
334     return false;
335 
336   // The dim op is also okay if its operand memref is a view/subview whose
337   // corresponding size is a valid symbol.
338   Optional<int64_t> index = dimOp.getConstantIndex();
339   assert(index.hasValue() &&
340          "expect only `dim` operations with a constant index");
341   int64_t i = index.getValue();
342   return TypeSwitch<Operation *, bool>(dimOp.source().getDefiningOp())
343       .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
344           [&](auto op) { return isMemRefSizeValidSymbol(op, i, region); })
345       .Default([](Operation *) { return false; });
346 }
347 
348 // A value can be used as a symbol (at all its use sites) iff it meets one of
349 // the following conditions:
350 // *) It is a constant.
351 // *) Its defining op or block arg appearance is immediately enclosed by an op
352 //    with `AffineScope` trait.
353 // *) It is the result of an affine.apply operation with symbol operands.
354 // *) It is a result of the dim op on a memref whose corresponding size is a
355 //    valid symbol.
356 bool mlir::isValidSymbol(Value value) {
357   if (!value)
358     return false;
359 
360   // The value must be an index type.
361   if (!value.getType().isIndex())
362     return false;
363 
364   // Check that the value is a top level value.
365   if (isTopLevelValue(value))
366     return true;
367 
368   if (auto *defOp = value.getDefiningOp())
369     return isValidSymbol(value, getAffineScope(defOp));
370 
371   return false;
372 }
373 
374 /// A value can be used as a symbol for `region` iff it meets one of the
375 /// following conditions:
376 /// *) It is a constant.
377 /// *) It is the result of an affine apply operation with symbol arguments.
378 /// *) It is a result of the dim op on a memref whose corresponding size is
379 ///    a valid symbol.
380 /// *) It is defined at the top level of 'region' or is its argument.
381 /// *) It dominates `region`'s parent op.
382 /// If `region` is null, conservatively assume the symbol definition scope does
383 /// not exist and only accept the values that would be symbols regardless of
384 /// the surrounding region structure, i.e. the first three cases above.
385 bool mlir::isValidSymbol(Value value, Region *region) {
386   // The value must be an index type.
387   if (!value.getType().isIndex())
388     return false;
389 
390   // A top-level value is a valid symbol.
391   if (region && ::isTopLevelValue(value, region))
392     return true;
393 
394   auto *defOp = value.getDefiningOp();
395   if (!defOp) {
396     // A block argument that is not a top-level value is a valid symbol if it
397     // dominates region's parent op.
398     Operation *regionOp = region ? region->getParentOp() : nullptr;
399     if (regionOp && !regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
400       if (auto *parentOpRegion = region->getParentOp()->getParentRegion())
401         return isValidSymbol(value, parentOpRegion);
402     return false;
403   }
404 
405   // Constant operation is ok.
406   Attribute operandCst;
407   if (matchPattern(defOp, m_Constant(&operandCst)))
408     return true;
409 
410   // Affine apply operation is ok if all of its operands are ok.
411   if (auto applyOp = dyn_cast<AffineApplyOp>(defOp))
412     return applyOp.isValidSymbol(region);
413 
414   // Dim op results could be valid symbols at any level.
415   if (auto dimOp = dyn_cast<memref::DimOp>(defOp))
416     return isDimOpValidSymbol(dimOp, region);
417   if (auto dimOp = dyn_cast<tensor::DimOp>(defOp))
418     return isDimOpValidSymbol(dimOp, region);
419 
420   // Check for values dominating `region`'s parent op.
421   Operation *regionOp = region ? region->getParentOp() : nullptr;
422   if (regionOp && !regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
423     if (auto *parentRegion = region->getParentOp()->getParentRegion())
424       return isValidSymbol(value, parentRegion);
425 
426   return false;
427 }
428 
429 // Returns true if 'value' is a valid index to an affine operation (e.g.
430 // affine.load, affine.store, affine.dma_start, affine.dma_wait) where
431 // `region` provides the polyhedral symbol scope. Returns false otherwise.
432 static bool isValidAffineIndexOperand(Value value, Region *region) {
433   return isValidDim(value, region) || isValidSymbol(value, region);
434 }
435 
436 /// Prints dimension and symbol list.
437 static void printDimAndSymbolList(Operation::operand_iterator begin,
438                                   Operation::operand_iterator end,
439                                   unsigned numDims, OpAsmPrinter &printer) {
440   OperandRange operands(begin, end);
441   printer << '(' << operands.take_front(numDims) << ')';
442   if (operands.size() > numDims)
443     printer << '[' << operands.drop_front(numDims) << ']';
444 }
445 
446 /// Parses dimension and symbol list and returns true if parsing failed.
447 ParseResult mlir::parseDimAndSymbolList(OpAsmParser &parser,
448                                         SmallVectorImpl<Value> &operands,
449                                         unsigned &numDims) {
450   SmallVector<OpAsmParser::UnresolvedOperand, 8> opInfos;
451   if (parser.parseOperandList(opInfos, OpAsmParser::Delimiter::Paren))
452     return failure();
453   // Store number of dimensions for validation by caller.
454   numDims = opInfos.size();
455 
456   // Parse the optional symbol operands.
457   auto indexTy = parser.getBuilder().getIndexType();
458   return failure(parser.parseOperandList(
459                      opInfos, OpAsmParser::Delimiter::OptionalSquare) ||
460                  parser.resolveOperands(opInfos, indexTy, operands));
461 }
462 
463 /// Utility function to verify that a set of operands are valid dimension and
464 /// symbol identifiers. The operands should be laid out such that the dimension
465 /// operands are before the symbol operands. This function returns failure if
466 /// there was an invalid operand. An operation is provided to emit any necessary
467 /// errors.
468 template <typename OpTy>
469 static LogicalResult
470 verifyDimAndSymbolIdentifiers(OpTy &op, Operation::operand_range operands,
471                               unsigned numDims) {
472   unsigned opIt = 0;
473   for (auto operand : operands) {
474     if (opIt++ < numDims) {
475       if (!isValidDim(operand, getAffineScope(op)))
476         return op.emitOpError("operand cannot be used as a dimension id");
477     } else if (!isValidSymbol(operand, getAffineScope(op))) {
478       return op.emitOpError("operand cannot be used as a symbol");
479     }
480   }
481   return success();
482 }
483 
484 //===----------------------------------------------------------------------===//
485 // AffineApplyOp
486 //===----------------------------------------------------------------------===//
487 
488 AffineValueMap AffineApplyOp::getAffineValueMap() {
489   return AffineValueMap(getAffineMap(), getOperands(), getResult());
490 }
491 
492 ParseResult AffineApplyOp::parse(OpAsmParser &parser, OperationState &result) {
493   auto &builder = parser.getBuilder();
494   auto indexTy = builder.getIndexType();
495 
496   AffineMapAttr mapAttr;
497   unsigned numDims;
498   if (parser.parseAttribute(mapAttr, "map", result.attributes) ||
499       parseDimAndSymbolList(parser, result.operands, numDims) ||
500       parser.parseOptionalAttrDict(result.attributes))
501     return failure();
502   auto map = mapAttr.getValue();
503 
504   if (map.getNumDims() != numDims ||
505       numDims + map.getNumSymbols() != result.operands.size()) {
506     return parser.emitError(parser.getNameLoc(),
507                             "dimension or symbol index mismatch");
508   }
509 
510   result.types.append(map.getNumResults(), indexTy);
511   return success();
512 }
513 
514 void AffineApplyOp::print(OpAsmPrinter &p) {
515   p << " " << mapAttr();
516   printDimAndSymbolList(operand_begin(), operand_end(),
517                         getAffineMap().getNumDims(), p);
518   p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{"map"});
519 }
520 
521 LogicalResult AffineApplyOp::verify() {
522   // Check input and output dimensions match.
523   AffineMap affineMap = map();
524 
525   // Verify that operand count matches affine map dimension and symbol count.
526   if (getNumOperands() != affineMap.getNumDims() + affineMap.getNumSymbols())
527     return emitOpError(
528         "operand count and affine map dimension and symbol count must match");
529 
530   // Verify that the map only produces one result.
531   if (affineMap.getNumResults() != 1)
532     return emitOpError("mapping must produce one value");
533 
534   return success();
535 }
536 
537 // The result of the affine apply operation can be used as a dimension id if all
538 // its operands are valid dimension ids.
539 bool AffineApplyOp::isValidDim() {
540   return llvm::all_of(getOperands(),
541                       [](Value op) { return mlir::isValidDim(op); });
542 }
543 
544 // The result of the affine apply operation can be used as a dimension id if all
545 // its operands are valid dimension ids with the parent operation of `region`
546 // defining the polyhedral scope for symbols.
547 bool AffineApplyOp::isValidDim(Region *region) {
548   return llvm::all_of(getOperands(),
549                       [&](Value op) { return ::isValidDim(op, region); });
550 }
551 
552 // The result of the affine apply operation can be used as a symbol if all its
553 // operands are symbols.
554 bool AffineApplyOp::isValidSymbol() {
555   return llvm::all_of(getOperands(),
556                       [](Value op) { return mlir::isValidSymbol(op); });
557 }
558 
559 // The result of the affine apply operation can be used as a symbol in `region`
560 // if all its operands are symbols in `region`.
561 bool AffineApplyOp::isValidSymbol(Region *region) {
562   return llvm::all_of(getOperands(), [&](Value operand) {
563     return mlir::isValidSymbol(operand, region);
564   });
565 }
566 
567 OpFoldResult AffineApplyOp::fold(ArrayRef<Attribute> operands) {
568   auto map = getAffineMap();
569 
570   // Fold dims and symbols to existing values.
571   auto expr = map.getResult(0);
572   if (auto dim = expr.dyn_cast<AffineDimExpr>())
573     return getOperand(dim.getPosition());
574   if (auto sym = expr.dyn_cast<AffineSymbolExpr>())
575     return getOperand(map.getNumDims() + sym.getPosition());
576 
577   // Otherwise, default to folding the map.
578   SmallVector<Attribute, 1> result;
579   if (failed(map.constantFold(operands, result)))
580     return {};
581   return result[0];
582 }
583 
584 /// Replace all occurrences of AffineExpr at position `pos` in `map` by the
585 /// defining AffineApplyOp expression and operands.
586 /// When `dimOrSymbolPosition < dims.size()`, AffineDimExpr@[pos] is replaced.
587 /// When `dimOrSymbolPosition >= dims.size()`,
588 /// AffineSymbolExpr@[pos - dims.size()] is replaced.
589 /// Mutate `map`,`dims` and `syms` in place as follows:
590 ///   1. `dims` and `syms` are only appended to.
591 ///   2. `map` dim and symbols are gradually shifted to higer positions.
592 ///   3. Old `dim` and `sym` entries are replaced by nullptr
593 /// This avoids the need for any bookkeeping.
594 static LogicalResult replaceDimOrSym(AffineMap *map,
595                                      unsigned dimOrSymbolPosition,
596                                      SmallVectorImpl<Value> &dims,
597                                      SmallVectorImpl<Value> &syms) {
598   bool isDimReplacement = (dimOrSymbolPosition < dims.size());
599   unsigned pos = isDimReplacement ? dimOrSymbolPosition
600                                   : dimOrSymbolPosition - dims.size();
601   Value &v = isDimReplacement ? dims[pos] : syms[pos];
602   if (!v)
603     return failure();
604 
605   auto affineApply = v.getDefiningOp<AffineApplyOp>();
606   if (!affineApply)
607     return failure();
608 
609   // At this point we will perform a replacement of `v`, set the entry in `dim`
610   // or `sym` to nullptr immediately.
611   v = nullptr;
612 
613   // Compute the map, dims and symbols coming from the AffineApplyOp.
614   AffineMap composeMap = affineApply.getAffineMap();
615   assert(composeMap.getNumResults() == 1 && "affine.apply with >1 results");
616   AffineExpr composeExpr =
617       composeMap.shiftDims(dims.size()).shiftSymbols(syms.size()).getResult(0);
618   ValueRange composeDims =
619       affineApply.getMapOperands().take_front(composeMap.getNumDims());
620   ValueRange composeSyms =
621       affineApply.getMapOperands().take_back(composeMap.getNumSymbols());
622 
623   // Append the dims and symbols where relevant and perform the replacement.
624   MLIRContext *ctx = map->getContext();
625   AffineExpr toReplace = isDimReplacement ? getAffineDimExpr(pos, ctx)
626                                           : getAffineSymbolExpr(pos, ctx);
627   dims.append(composeDims.begin(), composeDims.end());
628   syms.append(composeSyms.begin(), composeSyms.end());
629   *map = map->replace(toReplace, composeExpr, dims.size(), syms.size());
630 
631   return success();
632 }
633 
634 /// Iterate over `operands` and fold away all those produced by an AffineApplyOp
635 /// iteratively. Perform canonicalization of map and operands as well as
636 /// AffineMap simplification. `map` and `operands` are mutated in place.
637 static void composeAffineMapAndOperands(AffineMap *map,
638                                         SmallVectorImpl<Value> *operands) {
639   if (map->getNumResults() == 0) {
640     canonicalizeMapAndOperands(map, operands);
641     *map = simplifyAffineMap(*map);
642     return;
643   }
644 
645   MLIRContext *ctx = map->getContext();
646   SmallVector<Value, 4> dims(operands->begin(),
647                              operands->begin() + map->getNumDims());
648   SmallVector<Value, 4> syms(operands->begin() + map->getNumDims(),
649                              operands->end());
650 
651   // Iterate over dims and symbols coming from AffineApplyOp and replace until
652   // exhaustion. This iteratively mutates `map`, `dims` and `syms`. Both `dims`
653   // and `syms` can only increase by construction.
654   // The implementation uses a `while` loop to support the case of symbols
655   // that may be constructed from dims ;this may be overkill.
656   while (true) {
657     bool changed = false;
658     for (unsigned pos = 0; pos != dims.size() + syms.size(); ++pos)
659       if ((changed |= succeeded(replaceDimOrSym(map, pos, dims, syms))))
660         break;
661     if (!changed)
662       break;
663   }
664 
665   // Clear operands so we can fill them anew.
666   operands->clear();
667 
668   // At this point we may have introduced null operands, prune them out before
669   // canonicalizing map and operands.
670   unsigned nDims = 0, nSyms = 0;
671   SmallVector<AffineExpr, 4> dimReplacements, symReplacements;
672   dimReplacements.reserve(dims.size());
673   symReplacements.reserve(syms.size());
674   for (auto *container : {&dims, &syms}) {
675     bool isDim = (container == &dims);
676     auto &repls = isDim ? dimReplacements : symReplacements;
677     for (const auto &en : llvm::enumerate(*container)) {
678       Value v = en.value();
679       if (!v) {
680         assert(isDim ? !map->isFunctionOfDim(en.index())
681                      : !map->isFunctionOfSymbol(en.index()) &&
682                            "map is function of unexpected expr@pos");
683         repls.push_back(getAffineConstantExpr(0, ctx));
684         continue;
685       }
686       repls.push_back(isDim ? getAffineDimExpr(nDims++, ctx)
687                             : getAffineSymbolExpr(nSyms++, ctx));
688       operands->push_back(v);
689     }
690   }
691   *map = map->replaceDimsAndSymbols(dimReplacements, symReplacements, nDims,
692                                     nSyms);
693 
694   // Canonicalize and simplify before returning.
695   canonicalizeMapAndOperands(map, operands);
696   *map = simplifyAffineMap(*map);
697 }
698 
699 void mlir::fullyComposeAffineMapAndOperands(AffineMap *map,
700                                             SmallVectorImpl<Value> *operands) {
701   while (llvm::any_of(*operands, [](Value v) {
702     return isa_and_nonnull<AffineApplyOp>(v.getDefiningOp());
703   })) {
704     composeAffineMapAndOperands(map, operands);
705   }
706 }
707 
708 AffineApplyOp mlir::makeComposedAffineApply(OpBuilder &b, Location loc,
709                                             AffineMap map,
710                                             ValueRange operands) {
711   AffineMap normalizedMap = map;
712   SmallVector<Value, 8> normalizedOperands(operands.begin(), operands.end());
713   composeAffineMapAndOperands(&normalizedMap, &normalizedOperands);
714   assert(normalizedMap);
715   return b.create<AffineApplyOp>(loc, normalizedMap, normalizedOperands);
716 }
717 
718 AffineApplyOp mlir::makeComposedAffineApply(OpBuilder &b, Location loc,
719                                             AffineExpr e, ValueRange values) {
720   return makeComposedAffineApply(
721       b, loc, AffineMap::inferFromExprList(ArrayRef<AffineExpr>{e}).front(),
722       values);
723 }
724 
725 /// Fully compose map with operands and canonicalize the result.
726 /// Return the `createOrFold`'ed AffineApply op.
727 static Value createFoldedComposedAffineApply(OpBuilder &b, Location loc,
728                                              AffineMap map,
729                                              ValueRange operandsRef) {
730   SmallVector<Value, 4> operands(operandsRef.begin(), operandsRef.end());
731   fullyComposeAffineMapAndOperands(&map, &operands);
732   canonicalizeMapAndOperands(&map, &operands);
733   return b.createOrFold<AffineApplyOp>(loc, map, operands);
734 }
735 
736 SmallVector<Value, 4> mlir::applyMapToValues(OpBuilder &b, Location loc,
737                                              AffineMap map, ValueRange values) {
738   SmallVector<Value, 4> res;
739   res.reserve(map.getNumResults());
740   unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols();
741   // For each `expr` in `map`, applies the `expr` to the values extracted from
742   // ranges. If the resulting application can be folded into a Value, the
743   // folding occurs eagerly.
744   for (auto expr : map.getResults()) {
745     AffineMap map = AffineMap::get(numDims, numSym, expr);
746     res.push_back(createFoldedComposedAffineApply(b, loc, map, values));
747   }
748   return res;
749 }
750 
751 // A symbol may appear as a dim in affine.apply operations. This function
752 // canonicalizes dims that are valid symbols into actual symbols.
753 template <class MapOrSet>
754 static void canonicalizePromotedSymbols(MapOrSet *mapOrSet,
755                                         SmallVectorImpl<Value> *operands) {
756   if (!mapOrSet || operands->empty())
757     return;
758 
759   assert(mapOrSet->getNumInputs() == operands->size() &&
760          "map/set inputs must match number of operands");
761 
762   auto *context = mapOrSet->getContext();
763   SmallVector<Value, 8> resultOperands;
764   resultOperands.reserve(operands->size());
765   SmallVector<Value, 8> remappedSymbols;
766   remappedSymbols.reserve(operands->size());
767   unsigned nextDim = 0;
768   unsigned nextSym = 0;
769   unsigned oldNumSyms = mapOrSet->getNumSymbols();
770   SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
771   for (unsigned i = 0, e = mapOrSet->getNumInputs(); i != e; ++i) {
772     if (i < mapOrSet->getNumDims()) {
773       if (isValidSymbol((*operands)[i])) {
774         // This is a valid symbol that appears as a dim, canonicalize it.
775         dimRemapping[i] = getAffineSymbolExpr(oldNumSyms + nextSym++, context);
776         remappedSymbols.push_back((*operands)[i]);
777       } else {
778         dimRemapping[i] = getAffineDimExpr(nextDim++, context);
779         resultOperands.push_back((*operands)[i]);
780       }
781     } else {
782       resultOperands.push_back((*operands)[i]);
783     }
784   }
785 
786   resultOperands.append(remappedSymbols.begin(), remappedSymbols.end());
787   *operands = resultOperands;
788   *mapOrSet = mapOrSet->replaceDimsAndSymbols(dimRemapping, {}, nextDim,
789                                               oldNumSyms + nextSym);
790 
791   assert(mapOrSet->getNumInputs() == operands->size() &&
792          "map/set inputs must match number of operands");
793 }
794 
795 // Works for either an affine map or an integer set.
796 template <class MapOrSet>
797 static void canonicalizeMapOrSetAndOperands(MapOrSet *mapOrSet,
798                                             SmallVectorImpl<Value> *operands) {
799   static_assert(llvm::is_one_of<MapOrSet, AffineMap, IntegerSet>::value,
800                 "Argument must be either of AffineMap or IntegerSet type");
801 
802   if (!mapOrSet || operands->empty())
803     return;
804 
805   assert(mapOrSet->getNumInputs() == operands->size() &&
806          "map/set inputs must match number of operands");
807 
808   canonicalizePromotedSymbols<MapOrSet>(mapOrSet, operands);
809 
810   // Check to see what dims are used.
811   llvm::SmallBitVector usedDims(mapOrSet->getNumDims());
812   llvm::SmallBitVector usedSyms(mapOrSet->getNumSymbols());
813   mapOrSet->walkExprs([&](AffineExpr expr) {
814     if (auto dimExpr = expr.dyn_cast<AffineDimExpr>())
815       usedDims[dimExpr.getPosition()] = true;
816     else if (auto symExpr = expr.dyn_cast<AffineSymbolExpr>())
817       usedSyms[symExpr.getPosition()] = true;
818   });
819 
820   auto *context = mapOrSet->getContext();
821 
822   SmallVector<Value, 8> resultOperands;
823   resultOperands.reserve(operands->size());
824 
825   llvm::SmallDenseMap<Value, AffineExpr, 8> seenDims;
826   SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
827   unsigned nextDim = 0;
828   for (unsigned i = 0, e = mapOrSet->getNumDims(); i != e; ++i) {
829     if (usedDims[i]) {
830       // Remap dim positions for duplicate operands.
831       auto it = seenDims.find((*operands)[i]);
832       if (it == seenDims.end()) {
833         dimRemapping[i] = getAffineDimExpr(nextDim++, context);
834         resultOperands.push_back((*operands)[i]);
835         seenDims.insert(std::make_pair((*operands)[i], dimRemapping[i]));
836       } else {
837         dimRemapping[i] = it->second;
838       }
839     }
840   }
841   llvm::SmallDenseMap<Value, AffineExpr, 8> seenSymbols;
842   SmallVector<AffineExpr, 8> symRemapping(mapOrSet->getNumSymbols());
843   unsigned nextSym = 0;
844   for (unsigned i = 0, e = mapOrSet->getNumSymbols(); i != e; ++i) {
845     if (!usedSyms[i])
846       continue;
847     // Handle constant operands (only needed for symbolic operands since
848     // constant operands in dimensional positions would have already been
849     // promoted to symbolic positions above).
850     IntegerAttr operandCst;
851     if (matchPattern((*operands)[i + mapOrSet->getNumDims()],
852                      m_Constant(&operandCst))) {
853       symRemapping[i] =
854           getAffineConstantExpr(operandCst.getValue().getSExtValue(), context);
855       continue;
856     }
857     // Remap symbol positions for duplicate operands.
858     auto it = seenSymbols.find((*operands)[i + mapOrSet->getNumDims()]);
859     if (it == seenSymbols.end()) {
860       symRemapping[i] = getAffineSymbolExpr(nextSym++, context);
861       resultOperands.push_back((*operands)[i + mapOrSet->getNumDims()]);
862       seenSymbols.insert(std::make_pair((*operands)[i + mapOrSet->getNumDims()],
863                                         symRemapping[i]));
864     } else {
865       symRemapping[i] = it->second;
866     }
867   }
868   *mapOrSet = mapOrSet->replaceDimsAndSymbols(dimRemapping, symRemapping,
869                                               nextDim, nextSym);
870   *operands = resultOperands;
871 }
872 
873 void mlir::canonicalizeMapAndOperands(AffineMap *map,
874                                       SmallVectorImpl<Value> *operands) {
875   canonicalizeMapOrSetAndOperands<AffineMap>(map, operands);
876 }
877 
878 void mlir::canonicalizeSetAndOperands(IntegerSet *set,
879                                       SmallVectorImpl<Value> *operands) {
880   canonicalizeMapOrSetAndOperands<IntegerSet>(set, operands);
881 }
882 
883 namespace {
884 /// Simplify AffineApply, AffineLoad, and AffineStore operations by composing
885 /// maps that supply results into them.
886 ///
887 template <typename AffineOpTy>
888 struct SimplifyAffineOp : public OpRewritePattern<AffineOpTy> {
889   using OpRewritePattern<AffineOpTy>::OpRewritePattern;
890 
891   /// Replace the affine op with another instance of it with the supplied
892   /// map and mapOperands.
893   void replaceAffineOp(PatternRewriter &rewriter, AffineOpTy affineOp,
894                        AffineMap map, ArrayRef<Value> mapOperands) const;
895 
896   LogicalResult matchAndRewrite(AffineOpTy affineOp,
897                                 PatternRewriter &rewriter) const override {
898     static_assert(
899         llvm::is_one_of<AffineOpTy, AffineLoadOp, AffinePrefetchOp,
900                         AffineStoreOp, AffineApplyOp, AffineMinOp, AffineMaxOp,
901                         AffineVectorStoreOp, AffineVectorLoadOp>::value,
902         "affine load/store/vectorstore/vectorload/apply/prefetch/min/max op "
903         "expected");
904     auto map = affineOp.getAffineMap();
905     AffineMap oldMap = map;
906     auto oldOperands = affineOp.getMapOperands();
907     SmallVector<Value, 8> resultOperands(oldOperands);
908     composeAffineMapAndOperands(&map, &resultOperands);
909     canonicalizeMapAndOperands(&map, &resultOperands);
910     if (map == oldMap && std::equal(oldOperands.begin(), oldOperands.end(),
911                                     resultOperands.begin()))
912       return failure();
913 
914     replaceAffineOp(rewriter, affineOp, map, resultOperands);
915     return success();
916   }
917 };
918 
919 // Specialize the template to account for the different build signatures for
920 // affine load, store, and apply ops.
921 template <>
922 void SimplifyAffineOp<AffineLoadOp>::replaceAffineOp(
923     PatternRewriter &rewriter, AffineLoadOp load, AffineMap map,
924     ArrayRef<Value> mapOperands) const {
925   rewriter.replaceOpWithNewOp<AffineLoadOp>(load, load.getMemRef(), map,
926                                             mapOperands);
927 }
928 template <>
929 void SimplifyAffineOp<AffinePrefetchOp>::replaceAffineOp(
930     PatternRewriter &rewriter, AffinePrefetchOp prefetch, AffineMap map,
931     ArrayRef<Value> mapOperands) const {
932   rewriter.replaceOpWithNewOp<AffinePrefetchOp>(
933       prefetch, prefetch.memref(), map, mapOperands, prefetch.localityHint(),
934       prefetch.isWrite(), prefetch.isDataCache());
935 }
936 template <>
937 void SimplifyAffineOp<AffineStoreOp>::replaceAffineOp(
938     PatternRewriter &rewriter, AffineStoreOp store, AffineMap map,
939     ArrayRef<Value> mapOperands) const {
940   rewriter.replaceOpWithNewOp<AffineStoreOp>(
941       store, store.getValueToStore(), store.getMemRef(), map, mapOperands);
942 }
943 template <>
944 void SimplifyAffineOp<AffineVectorLoadOp>::replaceAffineOp(
945     PatternRewriter &rewriter, AffineVectorLoadOp vectorload, AffineMap map,
946     ArrayRef<Value> mapOperands) const {
947   rewriter.replaceOpWithNewOp<AffineVectorLoadOp>(
948       vectorload, vectorload.getVectorType(), vectorload.getMemRef(), map,
949       mapOperands);
950 }
951 template <>
952 void SimplifyAffineOp<AffineVectorStoreOp>::replaceAffineOp(
953     PatternRewriter &rewriter, AffineVectorStoreOp vectorstore, AffineMap map,
954     ArrayRef<Value> mapOperands) const {
955   rewriter.replaceOpWithNewOp<AffineVectorStoreOp>(
956       vectorstore, vectorstore.getValueToStore(), vectorstore.getMemRef(), map,
957       mapOperands);
958 }
959 
960 // Generic version for ops that don't have extra operands.
961 template <typename AffineOpTy>
962 void SimplifyAffineOp<AffineOpTy>::replaceAffineOp(
963     PatternRewriter &rewriter, AffineOpTy op, AffineMap map,
964     ArrayRef<Value> mapOperands) const {
965   rewriter.replaceOpWithNewOp<AffineOpTy>(op, map, mapOperands);
966 }
967 } // namespace
968 
969 void AffineApplyOp::getCanonicalizationPatterns(RewritePatternSet &results,
970                                                 MLIRContext *context) {
971   results.add<SimplifyAffineOp<AffineApplyOp>>(context);
972 }
973 
974 //===----------------------------------------------------------------------===//
975 // Common canonicalization pattern support logic
976 //===----------------------------------------------------------------------===//
977 
978 /// This is a common class used for patterns of the form
979 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
980 /// into the root operation directly.
981 static LogicalResult foldMemRefCast(Operation *op, Value ignore = nullptr) {
982   bool folded = false;
983   for (OpOperand &operand : op->getOpOperands()) {
984     auto cast = operand.get().getDefiningOp<memref::CastOp>();
985     if (cast && operand.get() != ignore &&
986         !cast.getOperand().getType().isa<UnrankedMemRefType>()) {
987       operand.set(cast.getOperand());
988       folded = true;
989     }
990   }
991   return success(folded);
992 }
993 
994 //===----------------------------------------------------------------------===//
995 // AffineDmaStartOp
996 //===----------------------------------------------------------------------===//
997 
998 // TODO: Check that map operands are loop IVs or symbols.
999 void AffineDmaStartOp::build(OpBuilder &builder, OperationState &result,
1000                              Value srcMemRef, AffineMap srcMap,
1001                              ValueRange srcIndices, Value destMemRef,
1002                              AffineMap dstMap, ValueRange destIndices,
1003                              Value tagMemRef, AffineMap tagMap,
1004                              ValueRange tagIndices, Value numElements,
1005                              Value stride, Value elementsPerStride) {
1006   result.addOperands(srcMemRef);
1007   result.addAttribute(getSrcMapAttrName(), AffineMapAttr::get(srcMap));
1008   result.addOperands(srcIndices);
1009   result.addOperands(destMemRef);
1010   result.addAttribute(getDstMapAttrName(), AffineMapAttr::get(dstMap));
1011   result.addOperands(destIndices);
1012   result.addOperands(tagMemRef);
1013   result.addAttribute(getTagMapAttrName(), AffineMapAttr::get(tagMap));
1014   result.addOperands(tagIndices);
1015   result.addOperands(numElements);
1016   if (stride) {
1017     result.addOperands({stride, elementsPerStride});
1018   }
1019 }
1020 
1021 void AffineDmaStartOp::print(OpAsmPrinter &p) {
1022   p << " " << getSrcMemRef() << '[';
1023   p.printAffineMapOfSSAIds(getSrcMapAttr(), getSrcIndices());
1024   p << "], " << getDstMemRef() << '[';
1025   p.printAffineMapOfSSAIds(getDstMapAttr(), getDstIndices());
1026   p << "], " << getTagMemRef() << '[';
1027   p.printAffineMapOfSSAIds(getTagMapAttr(), getTagIndices());
1028   p << "], " << getNumElements();
1029   if (isStrided()) {
1030     p << ", " << getStride();
1031     p << ", " << getNumElementsPerStride();
1032   }
1033   p << " : " << getSrcMemRefType() << ", " << getDstMemRefType() << ", "
1034     << getTagMemRefType();
1035 }
1036 
1037 // Parse AffineDmaStartOp.
1038 // Ex:
1039 //   affine.dma_start %src[%i, %j], %dst[%k, %l], %tag[%index], %size,
1040 //     %stride, %num_elt_per_stride
1041 //       : memref<3076 x f32, 0>, memref<1024 x f32, 2>, memref<1 x i32>
1042 //
1043 ParseResult AffineDmaStartOp::parse(OpAsmParser &parser,
1044                                     OperationState &result) {
1045   OpAsmParser::UnresolvedOperand srcMemRefInfo;
1046   AffineMapAttr srcMapAttr;
1047   SmallVector<OpAsmParser::UnresolvedOperand, 4> srcMapOperands;
1048   OpAsmParser::UnresolvedOperand dstMemRefInfo;
1049   AffineMapAttr dstMapAttr;
1050   SmallVector<OpAsmParser::UnresolvedOperand, 4> dstMapOperands;
1051   OpAsmParser::UnresolvedOperand tagMemRefInfo;
1052   AffineMapAttr tagMapAttr;
1053   SmallVector<OpAsmParser::UnresolvedOperand, 4> tagMapOperands;
1054   OpAsmParser::UnresolvedOperand numElementsInfo;
1055   SmallVector<OpAsmParser::UnresolvedOperand, 2> strideInfo;
1056 
1057   SmallVector<Type, 3> types;
1058   auto indexType = parser.getBuilder().getIndexType();
1059 
1060   // Parse and resolve the following list of operands:
1061   // *) dst memref followed by its affine maps operands (in square brackets).
1062   // *) src memref followed by its affine map operands (in square brackets).
1063   // *) tag memref followed by its affine map operands (in square brackets).
1064   // *) number of elements transferred by DMA operation.
1065   if (parser.parseOperand(srcMemRefInfo) ||
1066       parser.parseAffineMapOfSSAIds(srcMapOperands, srcMapAttr,
1067                                     getSrcMapAttrName(), result.attributes) ||
1068       parser.parseComma() || parser.parseOperand(dstMemRefInfo) ||
1069       parser.parseAffineMapOfSSAIds(dstMapOperands, dstMapAttr,
1070                                     getDstMapAttrName(), result.attributes) ||
1071       parser.parseComma() || parser.parseOperand(tagMemRefInfo) ||
1072       parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
1073                                     getTagMapAttrName(), result.attributes) ||
1074       parser.parseComma() || parser.parseOperand(numElementsInfo))
1075     return failure();
1076 
1077   // Parse optional stride and elements per stride.
1078   if (parser.parseTrailingOperandList(strideInfo)) {
1079     return failure();
1080   }
1081   if (!strideInfo.empty() && strideInfo.size() != 2) {
1082     return parser.emitError(parser.getNameLoc(),
1083                             "expected two stride related operands");
1084   }
1085   bool isStrided = strideInfo.size() == 2;
1086 
1087   if (parser.parseColonTypeList(types))
1088     return failure();
1089 
1090   if (types.size() != 3)
1091     return parser.emitError(parser.getNameLoc(), "expected three types");
1092 
1093   if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) ||
1094       parser.resolveOperands(srcMapOperands, indexType, result.operands) ||
1095       parser.resolveOperand(dstMemRefInfo, types[1], result.operands) ||
1096       parser.resolveOperands(dstMapOperands, indexType, result.operands) ||
1097       parser.resolveOperand(tagMemRefInfo, types[2], result.operands) ||
1098       parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
1099       parser.resolveOperand(numElementsInfo, indexType, result.operands))
1100     return failure();
1101 
1102   if (isStrided) {
1103     if (parser.resolveOperands(strideInfo, indexType, result.operands))
1104       return failure();
1105   }
1106 
1107   // Check that src/dst/tag operand counts match their map.numInputs.
1108   if (srcMapOperands.size() != srcMapAttr.getValue().getNumInputs() ||
1109       dstMapOperands.size() != dstMapAttr.getValue().getNumInputs() ||
1110       tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
1111     return parser.emitError(parser.getNameLoc(),
1112                             "memref operand count not equal to map.numInputs");
1113   return success();
1114 }
1115 
1116 LogicalResult AffineDmaStartOp::verifyInvariantsImpl() {
1117   if (!getOperand(getSrcMemRefOperandIndex()).getType().isa<MemRefType>())
1118     return emitOpError("expected DMA source to be of memref type");
1119   if (!getOperand(getDstMemRefOperandIndex()).getType().isa<MemRefType>())
1120     return emitOpError("expected DMA destination to be of memref type");
1121   if (!getOperand(getTagMemRefOperandIndex()).getType().isa<MemRefType>())
1122     return emitOpError("expected DMA tag to be of memref type");
1123 
1124   unsigned numInputsAllMaps = getSrcMap().getNumInputs() +
1125                               getDstMap().getNumInputs() +
1126                               getTagMap().getNumInputs();
1127   if (getNumOperands() != numInputsAllMaps + 3 + 1 &&
1128       getNumOperands() != numInputsAllMaps + 3 + 1 + 2) {
1129     return emitOpError("incorrect number of operands");
1130   }
1131 
1132   Region *scope = getAffineScope(*this);
1133   for (auto idx : getSrcIndices()) {
1134     if (!idx.getType().isIndex())
1135       return emitOpError("src index to dma_start must have 'index' type");
1136     if (!isValidAffineIndexOperand(idx, scope))
1137       return emitOpError("src index must be a dimension or symbol identifier");
1138   }
1139   for (auto idx : getDstIndices()) {
1140     if (!idx.getType().isIndex())
1141       return emitOpError("dst index to dma_start must have 'index' type");
1142     if (!isValidAffineIndexOperand(idx, scope))
1143       return emitOpError("dst index must be a dimension or symbol identifier");
1144   }
1145   for (auto idx : getTagIndices()) {
1146     if (!idx.getType().isIndex())
1147       return emitOpError("tag index to dma_start must have 'index' type");
1148     if (!isValidAffineIndexOperand(idx, scope))
1149       return emitOpError("tag index must be a dimension or symbol identifier");
1150   }
1151   return success();
1152 }
1153 
1154 LogicalResult AffineDmaStartOp::fold(ArrayRef<Attribute> cstOperands,
1155                                      SmallVectorImpl<OpFoldResult> &results) {
1156   /// dma_start(memrefcast) -> dma_start
1157   return foldMemRefCast(*this);
1158 }
1159 
1160 //===----------------------------------------------------------------------===//
1161 // AffineDmaWaitOp
1162 //===----------------------------------------------------------------------===//
1163 
1164 // TODO: Check that map operands are loop IVs or symbols.
1165 void AffineDmaWaitOp::build(OpBuilder &builder, OperationState &result,
1166                             Value tagMemRef, AffineMap tagMap,
1167                             ValueRange tagIndices, Value numElements) {
1168   result.addOperands(tagMemRef);
1169   result.addAttribute(getTagMapAttrName(), AffineMapAttr::get(tagMap));
1170   result.addOperands(tagIndices);
1171   result.addOperands(numElements);
1172 }
1173 
1174 void AffineDmaWaitOp::print(OpAsmPrinter &p) {
1175   p << " " << getTagMemRef() << '[';
1176   SmallVector<Value, 2> operands(getTagIndices());
1177   p.printAffineMapOfSSAIds(getTagMapAttr(), operands);
1178   p << "], ";
1179   p.printOperand(getNumElements());
1180   p << " : " << getTagMemRef().getType();
1181 }
1182 
1183 // Parse AffineDmaWaitOp.
1184 // Eg:
1185 //   affine.dma_wait %tag[%index], %num_elements
1186 //     : memref<1 x i32, (d0) -> (d0), 4>
1187 //
1188 ParseResult AffineDmaWaitOp::parse(OpAsmParser &parser,
1189                                    OperationState &result) {
1190   OpAsmParser::UnresolvedOperand tagMemRefInfo;
1191   AffineMapAttr tagMapAttr;
1192   SmallVector<OpAsmParser::UnresolvedOperand, 2> tagMapOperands;
1193   Type type;
1194   auto indexType = parser.getBuilder().getIndexType();
1195   OpAsmParser::UnresolvedOperand numElementsInfo;
1196 
1197   // Parse tag memref, its map operands, and dma size.
1198   if (parser.parseOperand(tagMemRefInfo) ||
1199       parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
1200                                     getTagMapAttrName(), result.attributes) ||
1201       parser.parseComma() || parser.parseOperand(numElementsInfo) ||
1202       parser.parseColonType(type) ||
1203       parser.resolveOperand(tagMemRefInfo, type, result.operands) ||
1204       parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
1205       parser.resolveOperand(numElementsInfo, indexType, result.operands))
1206     return failure();
1207 
1208   if (!type.isa<MemRefType>())
1209     return parser.emitError(parser.getNameLoc(),
1210                             "expected tag to be of memref type");
1211 
1212   if (tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
1213     return parser.emitError(parser.getNameLoc(),
1214                             "tag memref operand count != to map.numInputs");
1215   return success();
1216 }
1217 
1218 LogicalResult AffineDmaWaitOp::verifyInvariantsImpl() {
1219   if (!getOperand(0).getType().isa<MemRefType>())
1220     return emitOpError("expected DMA tag to be of memref type");
1221   Region *scope = getAffineScope(*this);
1222   for (auto idx : getTagIndices()) {
1223     if (!idx.getType().isIndex())
1224       return emitOpError("index to dma_wait must have 'index' type");
1225     if (!isValidAffineIndexOperand(idx, scope))
1226       return emitOpError("index must be a dimension or symbol identifier");
1227   }
1228   return success();
1229 }
1230 
1231 LogicalResult AffineDmaWaitOp::fold(ArrayRef<Attribute> cstOperands,
1232                                     SmallVectorImpl<OpFoldResult> &results) {
1233   /// dma_wait(memrefcast) -> dma_wait
1234   return foldMemRefCast(*this);
1235 }
1236 
1237 //===----------------------------------------------------------------------===//
1238 // AffineForOp
1239 //===----------------------------------------------------------------------===//
1240 
1241 /// 'bodyBuilder' is used to build the body of affine.for. If iterArgs and
1242 /// bodyBuilder are empty/null, we include default terminator op.
1243 void AffineForOp::build(OpBuilder &builder, OperationState &result,
1244                         ValueRange lbOperands, AffineMap lbMap,
1245                         ValueRange ubOperands, AffineMap ubMap, int64_t step,
1246                         ValueRange iterArgs, BodyBuilderFn bodyBuilder) {
1247   assert(((!lbMap && lbOperands.empty()) ||
1248           lbOperands.size() == lbMap.getNumInputs()) &&
1249          "lower bound operand count does not match the affine map");
1250   assert(((!ubMap && ubOperands.empty()) ||
1251           ubOperands.size() == ubMap.getNumInputs()) &&
1252          "upper bound operand count does not match the affine map");
1253   assert(step > 0 && "step has to be a positive integer constant");
1254 
1255   for (Value val : iterArgs)
1256     result.addTypes(val.getType());
1257 
1258   // Add an attribute for the step.
1259   result.addAttribute(getStepAttrName(),
1260                       builder.getIntegerAttr(builder.getIndexType(), step));
1261 
1262   // Add the lower bound.
1263   result.addAttribute(getLowerBoundAttrName(), AffineMapAttr::get(lbMap));
1264   result.addOperands(lbOperands);
1265 
1266   // Add the upper bound.
1267   result.addAttribute(getUpperBoundAttrName(), AffineMapAttr::get(ubMap));
1268   result.addOperands(ubOperands);
1269 
1270   result.addOperands(iterArgs);
1271   // Create a region and a block for the body.  The argument of the region is
1272   // the loop induction variable.
1273   Region *bodyRegion = result.addRegion();
1274   bodyRegion->push_back(new Block);
1275   Block &bodyBlock = bodyRegion->front();
1276   Value inductionVar =
1277       bodyBlock.addArgument(builder.getIndexType(), result.location);
1278   for (Value val : iterArgs)
1279     bodyBlock.addArgument(val.getType(), val.getLoc());
1280 
1281   // Create the default terminator if the builder is not provided and if the
1282   // iteration arguments are not provided. Otherwise, leave this to the caller
1283   // because we don't know which values to return from the loop.
1284   if (iterArgs.empty() && !bodyBuilder) {
1285     ensureTerminator(*bodyRegion, builder, result.location);
1286   } else if (bodyBuilder) {
1287     OpBuilder::InsertionGuard guard(builder);
1288     builder.setInsertionPointToStart(&bodyBlock);
1289     bodyBuilder(builder, result.location, inductionVar,
1290                 bodyBlock.getArguments().drop_front());
1291   }
1292 }
1293 
1294 void AffineForOp::build(OpBuilder &builder, OperationState &result, int64_t lb,
1295                         int64_t ub, int64_t step, ValueRange iterArgs,
1296                         BodyBuilderFn bodyBuilder) {
1297   auto lbMap = AffineMap::getConstantMap(lb, builder.getContext());
1298   auto ubMap = AffineMap::getConstantMap(ub, builder.getContext());
1299   return build(builder, result, {}, lbMap, {}, ubMap, step, iterArgs,
1300                bodyBuilder);
1301 }
1302 
1303 LogicalResult AffineForOp::verifyRegions() {
1304   // Check that the body defines as single block argument for the induction
1305   // variable.
1306   auto *body = getBody();
1307   if (body->getNumArguments() == 0 || !body->getArgument(0).getType().isIndex())
1308     return emitOpError("expected body to have a single index argument for the "
1309                        "induction variable");
1310 
1311   // Verify that the bound operands are valid dimension/symbols.
1312   /// Lower bound.
1313   if (getLowerBoundMap().getNumInputs() > 0)
1314     if (failed(verifyDimAndSymbolIdentifiers(*this, getLowerBoundOperands(),
1315                                              getLowerBoundMap().getNumDims())))
1316       return failure();
1317   /// Upper bound.
1318   if (getUpperBoundMap().getNumInputs() > 0)
1319     if (failed(verifyDimAndSymbolIdentifiers(*this, getUpperBoundOperands(),
1320                                              getUpperBoundMap().getNumDims())))
1321       return failure();
1322 
1323   unsigned opNumResults = getNumResults();
1324   if (opNumResults == 0)
1325     return success();
1326 
1327   // If ForOp defines values, check that the number and types of the defined
1328   // values match ForOp initial iter operands and backedge basic block
1329   // arguments.
1330   if (getNumIterOperands() != opNumResults)
1331     return emitOpError(
1332         "mismatch between the number of loop-carried values and results");
1333   if (getNumRegionIterArgs() != opNumResults)
1334     return emitOpError(
1335         "mismatch between the number of basic block args and results");
1336 
1337   return success();
1338 }
1339 
1340 /// Parse a for operation loop bounds.
1341 static ParseResult parseBound(bool isLower, OperationState &result,
1342                               OpAsmParser &p) {
1343   // 'min' / 'max' prefixes are generally syntactic sugar, but are required if
1344   // the map has multiple results.
1345   bool failedToParsedMinMax =
1346       failed(p.parseOptionalKeyword(isLower ? "max" : "min"));
1347 
1348   auto &builder = p.getBuilder();
1349   auto boundAttrName = isLower ? AffineForOp::getLowerBoundAttrName()
1350                                : AffineForOp::getUpperBoundAttrName();
1351 
1352   // Parse ssa-id as identity map.
1353   SmallVector<OpAsmParser::UnresolvedOperand, 1> boundOpInfos;
1354   if (p.parseOperandList(boundOpInfos))
1355     return failure();
1356 
1357   if (!boundOpInfos.empty()) {
1358     // Check that only one operand was parsed.
1359     if (boundOpInfos.size() > 1)
1360       return p.emitError(p.getNameLoc(),
1361                          "expected only one loop bound operand");
1362 
1363     // TODO: improve error message when SSA value is not of index type.
1364     // Currently it is 'use of value ... expects different type than prior uses'
1365     if (p.resolveOperand(boundOpInfos.front(), builder.getIndexType(),
1366                          result.operands))
1367       return failure();
1368 
1369     // Create an identity map using symbol id. This representation is optimized
1370     // for storage. Analysis passes may expand it into a multi-dimensional map
1371     // if desired.
1372     AffineMap map = builder.getSymbolIdentityMap();
1373     result.addAttribute(boundAttrName, AffineMapAttr::get(map));
1374     return success();
1375   }
1376 
1377   // Get the attribute location.
1378   SMLoc attrLoc = p.getCurrentLocation();
1379 
1380   Attribute boundAttr;
1381   if (p.parseAttribute(boundAttr, builder.getIndexType(), boundAttrName,
1382                        result.attributes))
1383     return failure();
1384 
1385   // Parse full form - affine map followed by dim and symbol list.
1386   if (auto affineMapAttr = boundAttr.dyn_cast<AffineMapAttr>()) {
1387     unsigned currentNumOperands = result.operands.size();
1388     unsigned numDims;
1389     if (parseDimAndSymbolList(p, result.operands, numDims))
1390       return failure();
1391 
1392     auto map = affineMapAttr.getValue();
1393     if (map.getNumDims() != numDims)
1394       return p.emitError(
1395           p.getNameLoc(),
1396           "dim operand count and affine map dim count must match");
1397 
1398     unsigned numDimAndSymbolOperands =
1399         result.operands.size() - currentNumOperands;
1400     if (numDims + map.getNumSymbols() != numDimAndSymbolOperands)
1401       return p.emitError(
1402           p.getNameLoc(),
1403           "symbol operand count and affine map symbol count must match");
1404 
1405     // If the map has multiple results, make sure that we parsed the min/max
1406     // prefix.
1407     if (map.getNumResults() > 1 && failedToParsedMinMax) {
1408       if (isLower) {
1409         return p.emitError(attrLoc, "lower loop bound affine map with "
1410                                     "multiple results requires 'max' prefix");
1411       }
1412       return p.emitError(attrLoc, "upper loop bound affine map with multiple "
1413                                   "results requires 'min' prefix");
1414     }
1415     return success();
1416   }
1417 
1418   // Parse custom assembly form.
1419   if (auto integerAttr = boundAttr.dyn_cast<IntegerAttr>()) {
1420     result.attributes.pop_back();
1421     result.addAttribute(
1422         boundAttrName,
1423         AffineMapAttr::get(builder.getConstantAffineMap(integerAttr.getInt())));
1424     return success();
1425   }
1426 
1427   return p.emitError(
1428       p.getNameLoc(),
1429       "expected valid affine map representation for loop bounds");
1430 }
1431 
1432 ParseResult AffineForOp::parse(OpAsmParser &parser, OperationState &result) {
1433   auto &builder = parser.getBuilder();
1434   OpAsmParser::UnresolvedOperand inductionVariable;
1435   // Parse the induction variable followed by '='.
1436   if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual())
1437     return failure();
1438 
1439   // Parse loop bounds.
1440   if (parseBound(/*isLower=*/true, result, parser) ||
1441       parser.parseKeyword("to", " between bounds") ||
1442       parseBound(/*isLower=*/false, result, parser))
1443     return failure();
1444 
1445   // Parse the optional loop step, we default to 1 if one is not present.
1446   if (parser.parseOptionalKeyword("step")) {
1447     result.addAttribute(
1448         AffineForOp::getStepAttrName(),
1449         builder.getIntegerAttr(builder.getIndexType(), /*value=*/1));
1450   } else {
1451     SMLoc stepLoc = parser.getCurrentLocation();
1452     IntegerAttr stepAttr;
1453     if (parser.parseAttribute(stepAttr, builder.getIndexType(),
1454                               AffineForOp::getStepAttrName().data(),
1455                               result.attributes))
1456       return failure();
1457 
1458     if (stepAttr.getValue().getSExtValue() < 0)
1459       return parser.emitError(
1460           stepLoc,
1461           "expected step to be representable as a positive signed integer");
1462   }
1463 
1464   // Parse the optional initial iteration arguments.
1465   SmallVector<OpAsmParser::UnresolvedOperand, 4> regionArgs, operands;
1466   SmallVector<Type, 4> argTypes;
1467   regionArgs.push_back(inductionVariable);
1468 
1469   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1470     // Parse assignment list and results type list.
1471     if (parser.parseAssignmentList(regionArgs, operands) ||
1472         parser.parseArrowTypeList(result.types))
1473       return failure();
1474     // Resolve input operands.
1475     for (auto operandType : llvm::zip(operands, result.types))
1476       if (parser.resolveOperand(std::get<0>(operandType),
1477                                 std::get<1>(operandType), result.operands))
1478         return failure();
1479   }
1480   // Induction variable.
1481   Type indexType = builder.getIndexType();
1482   argTypes.push_back(indexType);
1483   // Loop carried variables.
1484   argTypes.append(result.types.begin(), result.types.end());
1485   // Parse the body region.
1486   Region *body = result.addRegion();
1487   if (regionArgs.size() != argTypes.size())
1488     return parser.emitError(
1489         parser.getNameLoc(),
1490         "mismatch between the number of loop-carried values and results");
1491   if (parser.parseRegion(*body, regionArgs, argTypes))
1492     return failure();
1493 
1494   AffineForOp::ensureTerminator(*body, builder, result.location);
1495 
1496   // Parse the optional attribute list.
1497   return parser.parseOptionalAttrDict(result.attributes);
1498 }
1499 
1500 static void printBound(AffineMapAttr boundMap,
1501                        Operation::operand_range boundOperands,
1502                        const char *prefix, OpAsmPrinter &p) {
1503   AffineMap map = boundMap.getValue();
1504 
1505   // Check if this bound should be printed using custom assembly form.
1506   // The decision to restrict printing custom assembly form to trivial cases
1507   // comes from the will to roundtrip MLIR binary -> text -> binary in a
1508   // lossless way.
1509   // Therefore, custom assembly form parsing and printing is only supported for
1510   // zero-operand constant maps and single symbol operand identity maps.
1511   if (map.getNumResults() == 1) {
1512     AffineExpr expr = map.getResult(0);
1513 
1514     // Print constant bound.
1515     if (map.getNumDims() == 0 && map.getNumSymbols() == 0) {
1516       if (auto constExpr = expr.dyn_cast<AffineConstantExpr>()) {
1517         p << constExpr.getValue();
1518         return;
1519       }
1520     }
1521 
1522     // Print bound that consists of a single SSA symbol if the map is over a
1523     // single symbol.
1524     if (map.getNumDims() == 0 && map.getNumSymbols() == 1) {
1525       if (auto symExpr = expr.dyn_cast<AffineSymbolExpr>()) {
1526         p.printOperand(*boundOperands.begin());
1527         return;
1528       }
1529     }
1530   } else {
1531     // Map has multiple results. Print 'min' or 'max' prefix.
1532     p << prefix << ' ';
1533   }
1534 
1535   // Print the map and its operands.
1536   p << boundMap;
1537   printDimAndSymbolList(boundOperands.begin(), boundOperands.end(),
1538                         map.getNumDims(), p);
1539 }
1540 
1541 unsigned AffineForOp::getNumIterOperands() {
1542   AffineMap lbMap = getLowerBoundMapAttr().getValue();
1543   AffineMap ubMap = getUpperBoundMapAttr().getValue();
1544 
1545   return getNumOperands() - lbMap.getNumInputs() - ubMap.getNumInputs();
1546 }
1547 
1548 void AffineForOp::print(OpAsmPrinter &p) {
1549   p << ' ';
1550   p.printOperand(getBody()->getArgument(0));
1551   p << " = ";
1552   printBound(getLowerBoundMapAttr(), getLowerBoundOperands(), "max", p);
1553   p << " to ";
1554   printBound(getUpperBoundMapAttr(), getUpperBoundOperands(), "min", p);
1555 
1556   if (getStep() != 1)
1557     p << " step " << getStep();
1558 
1559   bool printBlockTerminators = false;
1560   if (getNumIterOperands() > 0) {
1561     p << " iter_args(";
1562     auto regionArgs = getRegionIterArgs();
1563     auto operands = getIterOperands();
1564 
1565     llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
1566       p << std::get<0>(it) << " = " << std::get<1>(it);
1567     });
1568     p << ") -> (" << getResultTypes() << ")";
1569     printBlockTerminators = true;
1570   }
1571 
1572   p << ' ';
1573   p.printRegion(region(), /*printEntryBlockArgs=*/false, printBlockTerminators);
1574   p.printOptionalAttrDict((*this)->getAttrs(),
1575                           /*elidedAttrs=*/{getLowerBoundAttrName(),
1576                                            getUpperBoundAttrName(),
1577                                            getStepAttrName()});
1578 }
1579 
1580 /// Fold the constant bounds of a loop.
1581 static LogicalResult foldLoopBounds(AffineForOp forOp) {
1582   auto foldLowerOrUpperBound = [&forOp](bool lower) {
1583     // Check to see if each of the operands is the result of a constant.  If
1584     // so, get the value.  If not, ignore it.
1585     SmallVector<Attribute, 8> operandConstants;
1586     auto boundOperands =
1587         lower ? forOp.getLowerBoundOperands() : forOp.getUpperBoundOperands();
1588     for (auto operand : boundOperands) {
1589       Attribute operandCst;
1590       matchPattern(operand, m_Constant(&operandCst));
1591       operandConstants.push_back(operandCst);
1592     }
1593 
1594     AffineMap boundMap =
1595         lower ? forOp.getLowerBoundMap() : forOp.getUpperBoundMap();
1596     assert(boundMap.getNumResults() >= 1 &&
1597            "bound maps should have at least one result");
1598     SmallVector<Attribute, 4> foldedResults;
1599     if (failed(boundMap.constantFold(operandConstants, foldedResults)))
1600       return failure();
1601 
1602     // Compute the max or min as applicable over the results.
1603     assert(!foldedResults.empty() && "bounds should have at least one result");
1604     auto maxOrMin = foldedResults[0].cast<IntegerAttr>().getValue();
1605     for (unsigned i = 1, e = foldedResults.size(); i < e; i++) {
1606       auto foldedResult = foldedResults[i].cast<IntegerAttr>().getValue();
1607       maxOrMin = lower ? llvm::APIntOps::smax(maxOrMin, foldedResult)
1608                        : llvm::APIntOps::smin(maxOrMin, foldedResult);
1609     }
1610     lower ? forOp.setConstantLowerBound(maxOrMin.getSExtValue())
1611           : forOp.setConstantUpperBound(maxOrMin.getSExtValue());
1612     return success();
1613   };
1614 
1615   // Try to fold the lower bound.
1616   bool folded = false;
1617   if (!forOp.hasConstantLowerBound())
1618     folded |= succeeded(foldLowerOrUpperBound(/*lower=*/true));
1619 
1620   // Try to fold the upper bound.
1621   if (!forOp.hasConstantUpperBound())
1622     folded |= succeeded(foldLowerOrUpperBound(/*lower=*/false));
1623   return success(folded);
1624 }
1625 
1626 /// Canonicalize the bounds of the given loop.
1627 static LogicalResult canonicalizeLoopBounds(AffineForOp forOp) {
1628   SmallVector<Value, 4> lbOperands(forOp.getLowerBoundOperands());
1629   SmallVector<Value, 4> ubOperands(forOp.getUpperBoundOperands());
1630 
1631   auto lbMap = forOp.getLowerBoundMap();
1632   auto ubMap = forOp.getUpperBoundMap();
1633   auto prevLbMap = lbMap;
1634   auto prevUbMap = ubMap;
1635 
1636   composeAffineMapAndOperands(&lbMap, &lbOperands);
1637   canonicalizeMapAndOperands(&lbMap, &lbOperands);
1638   lbMap = removeDuplicateExprs(lbMap);
1639 
1640   composeAffineMapAndOperands(&ubMap, &ubOperands);
1641   canonicalizeMapAndOperands(&ubMap, &ubOperands);
1642   ubMap = removeDuplicateExprs(ubMap);
1643 
1644   // Any canonicalization change always leads to updated map(s).
1645   if (lbMap == prevLbMap && ubMap == prevUbMap)
1646     return failure();
1647 
1648   if (lbMap != prevLbMap)
1649     forOp.setLowerBound(lbOperands, lbMap);
1650   if (ubMap != prevUbMap)
1651     forOp.setUpperBound(ubOperands, ubMap);
1652   return success();
1653 }
1654 
1655 namespace {
1656 /// Returns constant trip count in trivial cases.
1657 static Optional<uint64_t> getTrivialConstantTripCount(AffineForOp forOp) {
1658   int64_t step = forOp.getStep();
1659   if (!forOp.hasConstantBounds() || step <= 0)
1660     return None;
1661   int64_t lb = forOp.getConstantLowerBound();
1662   int64_t ub = forOp.getConstantUpperBound();
1663   return ub - lb <= 0 ? 0 : (ub - lb + step - 1) / step;
1664 }
1665 
1666 /// This is a pattern to fold trivially empty loop bodies.
1667 /// TODO: This should be moved into the folding hook.
1668 struct AffineForEmptyLoopFolder : public OpRewritePattern<AffineForOp> {
1669   using OpRewritePattern<AffineForOp>::OpRewritePattern;
1670 
1671   LogicalResult matchAndRewrite(AffineForOp forOp,
1672                                 PatternRewriter &rewriter) const override {
1673     // Check that the body only contains a yield.
1674     if (!llvm::hasSingleElement(*forOp.getBody()))
1675       return failure();
1676     if (forOp.getNumResults() == 0)
1677       return success();
1678     Optional<uint64_t> tripCount = getTrivialConstantTripCount(forOp);
1679     if (tripCount.hasValue() && tripCount.getValue() == 0) {
1680       // The initial values of the iteration arguments would be the op's
1681       // results.
1682       rewriter.replaceOp(forOp, forOp.getIterOperands());
1683       return success();
1684     }
1685     SmallVector<Value, 4> replacements;
1686     auto yieldOp = cast<AffineYieldOp>(forOp.getBody()->getTerminator());
1687     auto iterArgs = forOp.getRegionIterArgs();
1688     bool hasValDefinedOutsideLoop = false;
1689     bool iterArgsNotInOrder = false;
1690     for (unsigned i = 0, e = yieldOp->getNumOperands(); i < e; ++i) {
1691       Value val = yieldOp.getOperand(i);
1692       auto *iterArgIt = llvm::find(iterArgs, val);
1693       if (iterArgIt == iterArgs.end()) {
1694         // `val` is defined outside of the loop.
1695         assert(forOp.isDefinedOutsideOfLoop(val) &&
1696                "must be defined outside of the loop");
1697         hasValDefinedOutsideLoop = true;
1698         replacements.push_back(val);
1699       } else {
1700         unsigned pos = std::distance(iterArgs.begin(), iterArgIt);
1701         if (pos != i)
1702           iterArgsNotInOrder = true;
1703         replacements.push_back(forOp.getIterOperands()[pos]);
1704       }
1705     }
1706     // Bail out when the trip count is unknown and the loop returns any value
1707     // defined outside of the loop or any iterArg out of order.
1708     if (!tripCount.hasValue() &&
1709         (hasValDefinedOutsideLoop || iterArgsNotInOrder))
1710       return failure();
1711     // Bail out when the loop iterates more than once and it returns any iterArg
1712     // out of order.
1713     if (tripCount.hasValue() && tripCount.getValue() >= 2 && iterArgsNotInOrder)
1714       return failure();
1715     rewriter.replaceOp(forOp, replacements);
1716     return success();
1717   }
1718 };
1719 } // namespace
1720 
1721 void AffineForOp::getCanonicalizationPatterns(RewritePatternSet &results,
1722                                               MLIRContext *context) {
1723   results.add<AffineForEmptyLoopFolder>(context);
1724 }
1725 
1726 /// Return operands used when entering the region at 'index'. These operands
1727 /// correspond to the loop iterator operands, i.e., those excluding the
1728 /// induction variable. AffineForOp only has one region, so zero is the only
1729 /// valid value for `index`.
1730 OperandRange AffineForOp::getSuccessorEntryOperands(unsigned index) {
1731   assert(index == 0 && "invalid region index");
1732 
1733   // The initial operands map to the loop arguments after the induction
1734   // variable.
1735   return getIterOperands();
1736 }
1737 
1738 /// Given the region at `index`, or the parent operation if `index` is None,
1739 /// return the successor regions. These are the regions that may be selected
1740 /// during the flow of control. `operands` is a set of optional attributes that
1741 /// correspond to a constant value for each operand, or null if that operand is
1742 /// not a constant.
1743 void AffineForOp::getSuccessorRegions(
1744     Optional<unsigned> index, ArrayRef<Attribute> operands,
1745     SmallVectorImpl<RegionSuccessor> &regions) {
1746   assert((!index.hasValue() || index.getValue() == 0) &&
1747          "expected loop region");
1748   // The loop may typically branch back to its body or to the parent operation.
1749   // If the predecessor is the parent op and the trip count is known to be at
1750   // least one, branch into the body using the iterator arguments. And in cases
1751   // we know the trip count is zero, it can only branch back to its parent.
1752   Optional<uint64_t> tripCount = getTrivialConstantTripCount(*this);
1753   if (!index.hasValue() && tripCount.hasValue()) {
1754     if (tripCount.getValue() > 0) {
1755       regions.push_back(RegionSuccessor(&getLoopBody(), getRegionIterArgs()));
1756       return;
1757     }
1758     if (tripCount.getValue() == 0) {
1759       regions.push_back(RegionSuccessor(getResults()));
1760       return;
1761     }
1762   }
1763 
1764   // From the loop body, if the trip count is one, we can only branch back to
1765   // the parent.
1766   if (index.hasValue() && tripCount.hasValue() && tripCount.getValue() == 1) {
1767     regions.push_back(RegionSuccessor(getResults()));
1768     return;
1769   }
1770 
1771   // In all other cases, the loop may branch back to itself or the parent
1772   // operation.
1773   regions.push_back(RegionSuccessor(&getLoopBody(), getRegionIterArgs()));
1774   regions.push_back(RegionSuccessor(getResults()));
1775 }
1776 
1777 /// Returns true if the affine.for has zero iterations in trivial cases.
1778 static bool hasTrivialZeroTripCount(AffineForOp op) {
1779   Optional<uint64_t> tripCount = getTrivialConstantTripCount(op);
1780   return tripCount.hasValue() && tripCount.getValue() == 0;
1781 }
1782 
1783 LogicalResult AffineForOp::fold(ArrayRef<Attribute> operands,
1784                                 SmallVectorImpl<OpFoldResult> &results) {
1785   bool folded = succeeded(foldLoopBounds(*this));
1786   folded |= succeeded(canonicalizeLoopBounds(*this));
1787   if (hasTrivialZeroTripCount(*this)) {
1788     // The initial values of the loop-carried variables (iter_args) are the
1789     // results of the op.
1790     results.assign(getIterOperands().begin(), getIterOperands().end());
1791     folded = true;
1792   }
1793   return success(folded);
1794 }
1795 
1796 AffineBound AffineForOp::getLowerBound() {
1797   auto lbMap = getLowerBoundMap();
1798   return AffineBound(AffineForOp(*this), 0, lbMap.getNumInputs(), lbMap);
1799 }
1800 
1801 AffineBound AffineForOp::getUpperBound() {
1802   auto lbMap = getLowerBoundMap();
1803   auto ubMap = getUpperBoundMap();
1804   return AffineBound(AffineForOp(*this), lbMap.getNumInputs(),
1805                      lbMap.getNumInputs() + ubMap.getNumInputs(), ubMap);
1806 }
1807 
1808 void AffineForOp::setLowerBound(ValueRange lbOperands, AffineMap map) {
1809   assert(lbOperands.size() == map.getNumInputs());
1810   assert(map.getNumResults() >= 1 && "bound map has at least one result");
1811 
1812   SmallVector<Value, 4> newOperands(lbOperands.begin(), lbOperands.end());
1813 
1814   auto ubOperands = getUpperBoundOperands();
1815   newOperands.append(ubOperands.begin(), ubOperands.end());
1816   auto iterOperands = getIterOperands();
1817   newOperands.append(iterOperands.begin(), iterOperands.end());
1818   (*this)->setOperands(newOperands);
1819 
1820   (*this)->setAttr(getLowerBoundAttrName(), AffineMapAttr::get(map));
1821 }
1822 
1823 void AffineForOp::setUpperBound(ValueRange ubOperands, AffineMap map) {
1824   assert(ubOperands.size() == map.getNumInputs());
1825   assert(map.getNumResults() >= 1 && "bound map has at least one result");
1826 
1827   SmallVector<Value, 4> newOperands(getLowerBoundOperands());
1828   newOperands.append(ubOperands.begin(), ubOperands.end());
1829   auto iterOperands = getIterOperands();
1830   newOperands.append(iterOperands.begin(), iterOperands.end());
1831   (*this)->setOperands(newOperands);
1832 
1833   (*this)->setAttr(getUpperBoundAttrName(), AffineMapAttr::get(map));
1834 }
1835 
1836 void AffineForOp::setLowerBoundMap(AffineMap map) {
1837   auto lbMap = getLowerBoundMap();
1838   assert(lbMap.getNumDims() == map.getNumDims() &&
1839          lbMap.getNumSymbols() == map.getNumSymbols());
1840   assert(map.getNumResults() >= 1 && "bound map has at least one result");
1841   (void)lbMap;
1842   (*this)->setAttr(getLowerBoundAttrName(), AffineMapAttr::get(map));
1843 }
1844 
1845 void AffineForOp::setUpperBoundMap(AffineMap map) {
1846   auto ubMap = getUpperBoundMap();
1847   assert(ubMap.getNumDims() == map.getNumDims() &&
1848          ubMap.getNumSymbols() == map.getNumSymbols());
1849   assert(map.getNumResults() >= 1 && "bound map has at least one result");
1850   (void)ubMap;
1851   (*this)->setAttr(getUpperBoundAttrName(), AffineMapAttr::get(map));
1852 }
1853 
1854 bool AffineForOp::hasConstantLowerBound() {
1855   return getLowerBoundMap().isSingleConstant();
1856 }
1857 
1858 bool AffineForOp::hasConstantUpperBound() {
1859   return getUpperBoundMap().isSingleConstant();
1860 }
1861 
1862 int64_t AffineForOp::getConstantLowerBound() {
1863   return getLowerBoundMap().getSingleConstantResult();
1864 }
1865 
1866 int64_t AffineForOp::getConstantUpperBound() {
1867   return getUpperBoundMap().getSingleConstantResult();
1868 }
1869 
1870 void AffineForOp::setConstantLowerBound(int64_t value) {
1871   setLowerBound({}, AffineMap::getConstantMap(value, getContext()));
1872 }
1873 
1874 void AffineForOp::setConstantUpperBound(int64_t value) {
1875   setUpperBound({}, AffineMap::getConstantMap(value, getContext()));
1876 }
1877 
1878 AffineForOp::operand_range AffineForOp::getLowerBoundOperands() {
1879   return {operand_begin(), operand_begin() + getLowerBoundMap().getNumInputs()};
1880 }
1881 
1882 AffineForOp::operand_range AffineForOp::getUpperBoundOperands() {
1883   return {operand_begin() + getLowerBoundMap().getNumInputs(),
1884           operand_begin() + getLowerBoundMap().getNumInputs() +
1885               getUpperBoundMap().getNumInputs()};
1886 }
1887 
1888 AffineForOp::operand_range AffineForOp::getControlOperands() {
1889   return {operand_begin(), operand_begin() + getLowerBoundMap().getNumInputs() +
1890                                getUpperBoundMap().getNumInputs()};
1891 }
1892 
1893 bool AffineForOp::matchingBoundOperandList() {
1894   auto lbMap = getLowerBoundMap();
1895   auto ubMap = getUpperBoundMap();
1896   if (lbMap.getNumDims() != ubMap.getNumDims() ||
1897       lbMap.getNumSymbols() != ubMap.getNumSymbols())
1898     return false;
1899 
1900   unsigned numOperands = lbMap.getNumInputs();
1901   for (unsigned i = 0, e = lbMap.getNumInputs(); i < e; i++) {
1902     // Compare Value 's.
1903     if (getOperand(i) != getOperand(numOperands + i))
1904       return false;
1905   }
1906   return true;
1907 }
1908 
1909 Region &AffineForOp::getLoopBody() { return region(); }
1910 
1911 Optional<Value> AffineForOp::getSingleInductionVar() {
1912   return getInductionVar();
1913 }
1914 
1915 Optional<OpFoldResult> AffineForOp::getSingleLowerBound() {
1916   if (!hasConstantLowerBound())
1917     return llvm::None;
1918   OpBuilder b(getContext());
1919   return OpFoldResult(b.getI64IntegerAttr(getConstantLowerBound()));
1920 }
1921 
1922 Optional<OpFoldResult> AffineForOp::getSingleStep() {
1923   OpBuilder b(getContext());
1924   return OpFoldResult(b.getI64IntegerAttr(getStep()));
1925 }
1926 
1927 Optional<OpFoldResult> AffineForOp::getSingleUpperBound() {
1928   if (!hasConstantUpperBound())
1929     return llvm::None;
1930   OpBuilder b(getContext());
1931   return OpFoldResult(b.getI64IntegerAttr(getConstantUpperBound()));
1932 }
1933 
1934 /// Returns true if the provided value is the induction variable of a
1935 /// AffineForOp.
1936 bool mlir::isForInductionVar(Value val) {
1937   return getForInductionVarOwner(val) != AffineForOp();
1938 }
1939 
1940 /// Returns the loop parent of an induction variable. If the provided value is
1941 /// not an induction variable, then return nullptr.
1942 AffineForOp mlir::getForInductionVarOwner(Value val) {
1943   auto ivArg = val.dyn_cast<BlockArgument>();
1944   if (!ivArg || !ivArg.getOwner())
1945     return AffineForOp();
1946   auto *containingInst = ivArg.getOwner()->getParent()->getParentOp();
1947   if (auto forOp = dyn_cast<AffineForOp>(containingInst))
1948     // Check to make sure `val` is the induction variable, not an iter_arg.
1949     return forOp.getInductionVar() == val ? forOp : AffineForOp();
1950   return AffineForOp();
1951 }
1952 
1953 /// Extracts the induction variables from a list of AffineForOps and returns
1954 /// them.
1955 void mlir::extractForInductionVars(ArrayRef<AffineForOp> forInsts,
1956                                    SmallVectorImpl<Value> *ivs) {
1957   ivs->reserve(forInsts.size());
1958   for (auto forInst : forInsts)
1959     ivs->push_back(forInst.getInductionVar());
1960 }
1961 
1962 /// Builds an affine loop nest, using "loopCreatorFn" to create individual loop
1963 /// operations.
1964 template <typename BoundListTy, typename LoopCreatorTy>
1965 static void buildAffineLoopNestImpl(
1966     OpBuilder &builder, Location loc, BoundListTy lbs, BoundListTy ubs,
1967     ArrayRef<int64_t> steps,
1968     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn,
1969     LoopCreatorTy &&loopCreatorFn) {
1970   assert(lbs.size() == ubs.size() && "Mismatch in number of arguments");
1971   assert(lbs.size() == steps.size() && "Mismatch in number of arguments");
1972 
1973   // If there are no loops to be constructed, construct the body anyway.
1974   OpBuilder::InsertionGuard guard(builder);
1975   if (lbs.empty()) {
1976     if (bodyBuilderFn)
1977       bodyBuilderFn(builder, loc, ValueRange());
1978     return;
1979   }
1980 
1981   // Create the loops iteratively and store the induction variables.
1982   SmallVector<Value, 4> ivs;
1983   ivs.reserve(lbs.size());
1984   for (unsigned i = 0, e = lbs.size(); i < e; ++i) {
1985     // Callback for creating the loop body, always creates the terminator.
1986     auto loopBody = [&](OpBuilder &nestedBuilder, Location nestedLoc, Value iv,
1987                         ValueRange iterArgs) {
1988       ivs.push_back(iv);
1989       // In the innermost loop, call the body builder.
1990       if (i == e - 1 && bodyBuilderFn) {
1991         OpBuilder::InsertionGuard nestedGuard(nestedBuilder);
1992         bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
1993       }
1994       nestedBuilder.create<AffineYieldOp>(nestedLoc);
1995     };
1996 
1997     // Delegate actual loop creation to the callback in order to dispatch
1998     // between constant- and variable-bound loops.
1999     auto loop = loopCreatorFn(builder, loc, lbs[i], ubs[i], steps[i], loopBody);
2000     builder.setInsertionPointToStart(loop.getBody());
2001   }
2002 }
2003 
2004 /// Creates an affine loop from the bounds known to be constants.
2005 static AffineForOp
2006 buildAffineLoopFromConstants(OpBuilder &builder, Location loc, int64_t lb,
2007                              int64_t ub, int64_t step,
2008                              AffineForOp::BodyBuilderFn bodyBuilderFn) {
2009   return builder.create<AffineForOp>(loc, lb, ub, step, /*iterArgs=*/llvm::None,
2010                                      bodyBuilderFn);
2011 }
2012 
2013 /// Creates an affine loop from the bounds that may or may not be constants.
2014 static AffineForOp
2015 buildAffineLoopFromValues(OpBuilder &builder, Location loc, Value lb, Value ub,
2016                           int64_t step,
2017                           AffineForOp::BodyBuilderFn bodyBuilderFn) {
2018   auto lbConst = lb.getDefiningOp<arith::ConstantIndexOp>();
2019   auto ubConst = ub.getDefiningOp<arith::ConstantIndexOp>();
2020   if (lbConst && ubConst)
2021     return buildAffineLoopFromConstants(builder, loc, lbConst.value(),
2022                                         ubConst.value(), step, bodyBuilderFn);
2023   return builder.create<AffineForOp>(loc, lb, builder.getDimIdentityMap(), ub,
2024                                      builder.getDimIdentityMap(), step,
2025                                      /*iterArgs=*/llvm::None, bodyBuilderFn);
2026 }
2027 
2028 void mlir::buildAffineLoopNest(
2029     OpBuilder &builder, Location loc, ArrayRef<int64_t> lbs,
2030     ArrayRef<int64_t> ubs, ArrayRef<int64_t> steps,
2031     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
2032   buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
2033                           buildAffineLoopFromConstants);
2034 }
2035 
2036 void mlir::buildAffineLoopNest(
2037     OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
2038     ArrayRef<int64_t> steps,
2039     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
2040   buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
2041                           buildAffineLoopFromValues);
2042 }
2043 
2044 AffineForOp mlir::replaceForOpWithNewYields(OpBuilder &b, AffineForOp loop,
2045                                             ValueRange newIterOperands,
2046                                             ValueRange newYieldedValues,
2047                                             ValueRange newIterArgs,
2048                                             bool replaceLoopResults) {
2049   assert(newIterOperands.size() == newYieldedValues.size() &&
2050          "newIterOperands must be of the same size as newYieldedValues");
2051   // Create a new loop before the existing one, with the extra operands.
2052   OpBuilder::InsertionGuard g(b);
2053   b.setInsertionPoint(loop);
2054   auto operands = llvm::to_vector<4>(loop.getIterOperands());
2055   operands.append(newIterOperands.begin(), newIterOperands.end());
2056   SmallVector<Value, 4> lbOperands(loop.getLowerBoundOperands());
2057   SmallVector<Value, 4> ubOperands(loop.getUpperBoundOperands());
2058   SmallVector<Value, 4> steps(loop.getStep());
2059   auto lbMap = loop.getLowerBoundMap();
2060   auto ubMap = loop.getUpperBoundMap();
2061   AffineForOp newLoop =
2062       b.create<AffineForOp>(loop.getLoc(), lbOperands, lbMap, ubOperands, ubMap,
2063                             loop.getStep(), operands);
2064   // Take the body of the original parent loop.
2065   newLoop.getLoopBody().takeBody(loop.getLoopBody());
2066   for (Value val : newIterArgs)
2067     newLoop.getLoopBody().addArgument(val.getType(), val.getLoc());
2068 
2069   // Update yield operation with new values to be added.
2070   if (!newYieldedValues.empty()) {
2071     auto yield = cast<AffineYieldOp>(newLoop.getBody()->getTerminator());
2072     b.setInsertionPoint(yield);
2073     auto yieldOperands = llvm::to_vector<4>(yield.getOperands());
2074     yieldOperands.append(newYieldedValues.begin(), newYieldedValues.end());
2075     b.create<AffineYieldOp>(yield.getLoc(), yieldOperands);
2076     yield.erase();
2077   }
2078   if (replaceLoopResults) {
2079     for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front(
2080                                                     loop.getNumResults()))) {
2081       std::get<0>(it).replaceAllUsesWith(std::get<1>(it));
2082     }
2083   }
2084   return newLoop;
2085 }
2086 
2087 //===----------------------------------------------------------------------===//
2088 // AffineIfOp
2089 //===----------------------------------------------------------------------===//
2090 
2091 namespace {
2092 /// Remove else blocks that have nothing other than a zero value yield.
2093 struct SimplifyDeadElse : public OpRewritePattern<AffineIfOp> {
2094   using OpRewritePattern<AffineIfOp>::OpRewritePattern;
2095 
2096   LogicalResult matchAndRewrite(AffineIfOp ifOp,
2097                                 PatternRewriter &rewriter) const override {
2098     if (ifOp.elseRegion().empty() ||
2099         !llvm::hasSingleElement(*ifOp.getElseBlock()) || ifOp.getNumResults())
2100       return failure();
2101 
2102     rewriter.startRootUpdate(ifOp);
2103     rewriter.eraseBlock(ifOp.getElseBlock());
2104     rewriter.finalizeRootUpdate(ifOp);
2105     return success();
2106   }
2107 };
2108 
2109 /// Removes affine.if cond if the condition is always true or false in certain
2110 /// trivial cases. Promotes the then/else block in the parent operation block.
2111 struct AlwaysTrueOrFalseIf : public OpRewritePattern<AffineIfOp> {
2112   using OpRewritePattern<AffineIfOp>::OpRewritePattern;
2113 
2114   LogicalResult matchAndRewrite(AffineIfOp op,
2115                                 PatternRewriter &rewriter) const override {
2116 
2117     auto isTriviallyFalse = [](IntegerSet iSet) {
2118       return iSet.isEmptyIntegerSet();
2119     };
2120 
2121     auto isTriviallyTrue = [](IntegerSet iSet) {
2122       return (iSet.getNumEqualities() == 1 && iSet.getNumInequalities() == 0 &&
2123               iSet.getConstraint(0) == 0);
2124     };
2125 
2126     IntegerSet affineIfConditions = op.getIntegerSet();
2127     Block *blockToMove;
2128     if (isTriviallyFalse(affineIfConditions)) {
2129       // The absence, or equivalently, the emptiness of the else region need not
2130       // be checked when affine.if is returning results because if an affine.if
2131       // operation is returning results, it always has a non-empty else region.
2132       if (op.getNumResults() == 0 && !op.hasElse()) {
2133         // If the else region is absent, or equivalently, empty, remove the
2134         // affine.if operation (which is not returning any results).
2135         rewriter.eraseOp(op);
2136         return success();
2137       }
2138       blockToMove = op.getElseBlock();
2139     } else if (isTriviallyTrue(affineIfConditions)) {
2140       blockToMove = op.getThenBlock();
2141     } else {
2142       return failure();
2143     }
2144     Operation *blockToMoveTerminator = blockToMove->getTerminator();
2145     // Promote the "blockToMove" block to the parent operation block between the
2146     // prologue and epilogue of "op".
2147     rewriter.mergeBlockBefore(blockToMove, op);
2148     // Replace the "op" operation with the operands of the
2149     // "blockToMoveTerminator" operation. Note that "blockToMoveTerminator" is
2150     // the affine.yield operation present in the "blockToMove" block. It has no
2151     // operands when affine.if is not returning results and therefore, in that
2152     // case, replaceOp just erases "op". When affine.if is not returning
2153     // results, the affine.yield operation can be omitted. It gets inserted
2154     // implicitly.
2155     rewriter.replaceOp(op, blockToMoveTerminator->getOperands());
2156     // Erase the "blockToMoveTerminator" operation since it is now in the parent
2157     // operation block, which already has its own terminator.
2158     rewriter.eraseOp(blockToMoveTerminator);
2159     return success();
2160   }
2161 };
2162 } // namespace
2163 
2164 LogicalResult AffineIfOp::verify() {
2165   // Verify that we have a condition attribute.
2166   // FIXME: This should be specified in the arguments list in ODS.
2167   auto conditionAttr =
2168       (*this)->getAttrOfType<IntegerSetAttr>(getConditionAttrName());
2169   if (!conditionAttr)
2170     return emitOpError("requires an integer set attribute named 'condition'");
2171 
2172   // Verify that there are enough operands for the condition.
2173   IntegerSet condition = conditionAttr.getValue();
2174   if (getNumOperands() != condition.getNumInputs())
2175     return emitOpError("operand count and condition integer set dimension and "
2176                        "symbol count must match");
2177 
2178   // Verify that the operands are valid dimension/symbols.
2179   if (failed(verifyDimAndSymbolIdentifiers(*this, getOperands(),
2180                                            condition.getNumDims())))
2181     return failure();
2182 
2183   return success();
2184 }
2185 
2186 ParseResult AffineIfOp::parse(OpAsmParser &parser, OperationState &result) {
2187   // Parse the condition attribute set.
2188   IntegerSetAttr conditionAttr;
2189   unsigned numDims;
2190   if (parser.parseAttribute(conditionAttr, AffineIfOp::getConditionAttrName(),
2191                             result.attributes) ||
2192       parseDimAndSymbolList(parser, result.operands, numDims))
2193     return failure();
2194 
2195   // Verify the condition operands.
2196   auto set = conditionAttr.getValue();
2197   if (set.getNumDims() != numDims)
2198     return parser.emitError(
2199         parser.getNameLoc(),
2200         "dim operand count and integer set dim count must match");
2201   if (numDims + set.getNumSymbols() != result.operands.size())
2202     return parser.emitError(
2203         parser.getNameLoc(),
2204         "symbol operand count and integer set symbol count must match");
2205 
2206   if (parser.parseOptionalArrowTypeList(result.types))
2207     return failure();
2208 
2209   // Create the regions for 'then' and 'else'.  The latter must be created even
2210   // if it remains empty for the validity of the operation.
2211   result.regions.reserve(2);
2212   Region *thenRegion = result.addRegion();
2213   Region *elseRegion = result.addRegion();
2214 
2215   // Parse the 'then' region.
2216   if (parser.parseRegion(*thenRegion, {}, {}))
2217     return failure();
2218   AffineIfOp::ensureTerminator(*thenRegion, parser.getBuilder(),
2219                                result.location);
2220 
2221   // If we find an 'else' keyword then parse the 'else' region.
2222   if (!parser.parseOptionalKeyword("else")) {
2223     if (parser.parseRegion(*elseRegion, {}, {}))
2224       return failure();
2225     AffineIfOp::ensureTerminator(*elseRegion, parser.getBuilder(),
2226                                  result.location);
2227   }
2228 
2229   // Parse the optional attribute list.
2230   if (parser.parseOptionalAttrDict(result.attributes))
2231     return failure();
2232 
2233   return success();
2234 }
2235 
2236 void AffineIfOp::print(OpAsmPrinter &p) {
2237   auto conditionAttr =
2238       (*this)->getAttrOfType<IntegerSetAttr>(getConditionAttrName());
2239   p << " " << conditionAttr;
2240   printDimAndSymbolList(operand_begin(), operand_end(),
2241                         conditionAttr.getValue().getNumDims(), p);
2242   p.printOptionalArrowTypeList(getResultTypes());
2243   p << ' ';
2244   p.printRegion(thenRegion(), /*printEntryBlockArgs=*/false,
2245                 /*printBlockTerminators=*/getNumResults());
2246 
2247   // Print the 'else' regions if it has any blocks.
2248   auto &elseRegion = this->elseRegion();
2249   if (!elseRegion.empty()) {
2250     p << " else ";
2251     p.printRegion(elseRegion,
2252                   /*printEntryBlockArgs=*/false,
2253                   /*printBlockTerminators=*/getNumResults());
2254   }
2255 
2256   // Print the attribute list.
2257   p.printOptionalAttrDict((*this)->getAttrs(),
2258                           /*elidedAttrs=*/getConditionAttrName());
2259 }
2260 
2261 IntegerSet AffineIfOp::getIntegerSet() {
2262   return (*this)
2263       ->getAttrOfType<IntegerSetAttr>(getConditionAttrName())
2264       .getValue();
2265 }
2266 
2267 void AffineIfOp::setIntegerSet(IntegerSet newSet) {
2268   (*this)->setAttr(getConditionAttrName(), IntegerSetAttr::get(newSet));
2269 }
2270 
2271 void AffineIfOp::setConditional(IntegerSet set, ValueRange operands) {
2272   setIntegerSet(set);
2273   (*this)->setOperands(operands);
2274 }
2275 
2276 void AffineIfOp::build(OpBuilder &builder, OperationState &result,
2277                        TypeRange resultTypes, IntegerSet set, ValueRange args,
2278                        bool withElseRegion) {
2279   assert(resultTypes.empty() || withElseRegion);
2280   result.addTypes(resultTypes);
2281   result.addOperands(args);
2282   result.addAttribute(getConditionAttrName(), IntegerSetAttr::get(set));
2283 
2284   Region *thenRegion = result.addRegion();
2285   thenRegion->push_back(new Block());
2286   if (resultTypes.empty())
2287     AffineIfOp::ensureTerminator(*thenRegion, builder, result.location);
2288 
2289   Region *elseRegion = result.addRegion();
2290   if (withElseRegion) {
2291     elseRegion->push_back(new Block());
2292     if (resultTypes.empty())
2293       AffineIfOp::ensureTerminator(*elseRegion, builder, result.location);
2294   }
2295 }
2296 
2297 void AffineIfOp::build(OpBuilder &builder, OperationState &result,
2298                        IntegerSet set, ValueRange args, bool withElseRegion) {
2299   AffineIfOp::build(builder, result, /*resultTypes=*/{}, set, args,
2300                     withElseRegion);
2301 }
2302 
2303 /// Canonicalize an affine if op's conditional (integer set + operands).
2304 LogicalResult AffineIfOp::fold(ArrayRef<Attribute>,
2305                                SmallVectorImpl<OpFoldResult> &) {
2306   auto set = getIntegerSet();
2307   SmallVector<Value, 4> operands(getOperands());
2308   canonicalizeSetAndOperands(&set, &operands);
2309 
2310   // Any canonicalization change always leads to either a reduction in the
2311   // number of operands or a change in the number of symbolic operands
2312   // (promotion of dims to symbols).
2313   if (operands.size() < getIntegerSet().getNumInputs() ||
2314       set.getNumSymbols() > getIntegerSet().getNumSymbols()) {
2315     setConditional(set, operands);
2316     return success();
2317   }
2318 
2319   return failure();
2320 }
2321 
2322 void AffineIfOp::getCanonicalizationPatterns(RewritePatternSet &results,
2323                                              MLIRContext *context) {
2324   results.add<SimplifyDeadElse, AlwaysTrueOrFalseIf>(context);
2325 }
2326 
2327 //===----------------------------------------------------------------------===//
2328 // AffineLoadOp
2329 //===----------------------------------------------------------------------===//
2330 
2331 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
2332                          AffineMap map, ValueRange operands) {
2333   assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
2334   result.addOperands(operands);
2335   if (map)
2336     result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
2337   auto memrefType = operands[0].getType().cast<MemRefType>();
2338   result.types.push_back(memrefType.getElementType());
2339 }
2340 
2341 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
2342                          Value memref, AffineMap map, ValueRange mapOperands) {
2343   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
2344   result.addOperands(memref);
2345   result.addOperands(mapOperands);
2346   auto memrefType = memref.getType().cast<MemRefType>();
2347   result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
2348   result.types.push_back(memrefType.getElementType());
2349 }
2350 
2351 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
2352                          Value memref, ValueRange indices) {
2353   auto memrefType = memref.getType().cast<MemRefType>();
2354   int64_t rank = memrefType.getRank();
2355   // Create identity map for memrefs with at least one dimension or () -> ()
2356   // for zero-dimensional memrefs.
2357   auto map =
2358       rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
2359   build(builder, result, memref, map, indices);
2360 }
2361 
2362 ParseResult AffineLoadOp::parse(OpAsmParser &parser, OperationState &result) {
2363   auto &builder = parser.getBuilder();
2364   auto indexTy = builder.getIndexType();
2365 
2366   MemRefType type;
2367   OpAsmParser::UnresolvedOperand memrefInfo;
2368   AffineMapAttr mapAttr;
2369   SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
2370   return failure(
2371       parser.parseOperand(memrefInfo) ||
2372       parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
2373                                     AffineLoadOp::getMapAttrName(),
2374                                     result.attributes) ||
2375       parser.parseOptionalAttrDict(result.attributes) ||
2376       parser.parseColonType(type) ||
2377       parser.resolveOperand(memrefInfo, type, result.operands) ||
2378       parser.resolveOperands(mapOperands, indexTy, result.operands) ||
2379       parser.addTypeToList(type.getElementType(), result.types));
2380 }
2381 
2382 void AffineLoadOp::print(OpAsmPrinter &p) {
2383   p << " " << getMemRef() << '[';
2384   if (AffineMapAttr mapAttr =
2385           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()))
2386     p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
2387   p << ']';
2388   p.printOptionalAttrDict((*this)->getAttrs(),
2389                           /*elidedAttrs=*/{getMapAttrName()});
2390   p << " : " << getMemRefType();
2391 }
2392 
2393 /// Verify common indexing invariants of affine.load, affine.store,
2394 /// affine.vector_load and affine.vector_store.
2395 static LogicalResult
2396 verifyMemoryOpIndexing(Operation *op, AffineMapAttr mapAttr,
2397                        Operation::operand_range mapOperands,
2398                        MemRefType memrefType, unsigned numIndexOperands) {
2399   if (mapAttr) {
2400     AffineMap map = mapAttr.getValue();
2401     if (map.getNumResults() != memrefType.getRank())
2402       return op->emitOpError("affine map num results must equal memref rank");
2403     if (map.getNumInputs() != numIndexOperands)
2404       return op->emitOpError("expects as many subscripts as affine map inputs");
2405   } else {
2406     if (memrefType.getRank() != numIndexOperands)
2407       return op->emitOpError(
2408           "expects the number of subscripts to be equal to memref rank");
2409   }
2410 
2411   Region *scope = getAffineScope(op);
2412   for (auto idx : mapOperands) {
2413     if (!idx.getType().isIndex())
2414       return op->emitOpError("index to load must have 'index' type");
2415     if (!isValidAffineIndexOperand(idx, scope))
2416       return op->emitOpError("index must be a dimension or symbol identifier");
2417   }
2418 
2419   return success();
2420 }
2421 
2422 LogicalResult AffineLoadOp::verify() {
2423   auto memrefType = getMemRefType();
2424   if (getType() != memrefType.getElementType())
2425     return emitOpError("result type must match element type of memref");
2426 
2427   if (failed(verifyMemoryOpIndexing(
2428           getOperation(),
2429           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()),
2430           getMapOperands(), memrefType,
2431           /*numIndexOperands=*/getNumOperands() - 1)))
2432     return failure();
2433 
2434   return success();
2435 }
2436 
2437 void AffineLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
2438                                                MLIRContext *context) {
2439   results.add<SimplifyAffineOp<AffineLoadOp>>(context);
2440 }
2441 
2442 OpFoldResult AffineLoadOp::fold(ArrayRef<Attribute> cstOperands) {
2443   /// load(memrefcast) -> load
2444   if (succeeded(foldMemRefCast(*this)))
2445     return getResult();
2446 
2447   // Fold load from a global constant memref.
2448   auto getGlobalOp = memref().getDefiningOp<memref::GetGlobalOp>();
2449   if (!getGlobalOp)
2450     return {};
2451   // Get to the memref.global defining the symbol.
2452   auto *symbolTableOp = getGlobalOp->getParentWithTrait<OpTrait::SymbolTable>();
2453   if (!symbolTableOp)
2454     return {};
2455   auto global = dyn_cast_or_null<memref::GlobalOp>(
2456       SymbolTable::lookupSymbolIn(symbolTableOp, getGlobalOp.nameAttr()));
2457   if (!global)
2458     return {};
2459 
2460   // Check if the global memref is a constant.
2461   auto cstAttr =
2462       global.getConstantInitValue().dyn_cast_or_null<DenseElementsAttr>();
2463   if (!cstAttr)
2464     return {};
2465   // If it's a splat constant, we can fold irrespective of indices.
2466   if (auto splatAttr = cstAttr.dyn_cast<SplatElementsAttr>())
2467     return splatAttr.getSplatValue<Attribute>();
2468   // Otherwise, we can fold only if we know the indices.
2469   if (!getAffineMap().isConstant())
2470     return {};
2471   auto indices = llvm::to_vector<4>(
2472       llvm::map_range(getAffineMap().getConstantResults(),
2473                       [](int64_t v) -> uint64_t { return v; }));
2474   return cstAttr.getValues<Attribute>()[indices];
2475 }
2476 
2477 //===----------------------------------------------------------------------===//
2478 // AffineStoreOp
2479 //===----------------------------------------------------------------------===//
2480 
2481 void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
2482                           Value valueToStore, Value memref, AffineMap map,
2483                           ValueRange mapOperands) {
2484   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
2485   result.addOperands(valueToStore);
2486   result.addOperands(memref);
2487   result.addOperands(mapOperands);
2488   result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
2489 }
2490 
2491 // Use identity map.
2492 void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
2493                           Value valueToStore, Value memref,
2494                           ValueRange indices) {
2495   auto memrefType = memref.getType().cast<MemRefType>();
2496   int64_t rank = memrefType.getRank();
2497   // Create identity map for memrefs with at least one dimension or () -> ()
2498   // for zero-dimensional memrefs.
2499   auto map =
2500       rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
2501   build(builder, result, valueToStore, memref, map, indices);
2502 }
2503 
2504 ParseResult AffineStoreOp::parse(OpAsmParser &parser, OperationState &result) {
2505   auto indexTy = parser.getBuilder().getIndexType();
2506 
2507   MemRefType type;
2508   OpAsmParser::UnresolvedOperand storeValueInfo;
2509   OpAsmParser::UnresolvedOperand memrefInfo;
2510   AffineMapAttr mapAttr;
2511   SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
2512   return failure(parser.parseOperand(storeValueInfo) || parser.parseComma() ||
2513                  parser.parseOperand(memrefInfo) ||
2514                  parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
2515                                                AffineStoreOp::getMapAttrName(),
2516                                                result.attributes) ||
2517                  parser.parseOptionalAttrDict(result.attributes) ||
2518                  parser.parseColonType(type) ||
2519                  parser.resolveOperand(storeValueInfo, type.getElementType(),
2520                                        result.operands) ||
2521                  parser.resolveOperand(memrefInfo, type, result.operands) ||
2522                  parser.resolveOperands(mapOperands, indexTy, result.operands));
2523 }
2524 
2525 void AffineStoreOp::print(OpAsmPrinter &p) {
2526   p << " " << getValueToStore();
2527   p << ", " << getMemRef() << '[';
2528   if (AffineMapAttr mapAttr =
2529           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()))
2530     p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
2531   p << ']';
2532   p.printOptionalAttrDict((*this)->getAttrs(),
2533                           /*elidedAttrs=*/{getMapAttrName()});
2534   p << " : " << getMemRefType();
2535 }
2536 
2537 LogicalResult AffineStoreOp::verify() {
2538   // The value to store must have the same type as memref element type.
2539   auto memrefType = getMemRefType();
2540   if (getValueToStore().getType() != memrefType.getElementType())
2541     return emitOpError(
2542         "value to store must have the same type as memref element type");
2543 
2544   if (failed(verifyMemoryOpIndexing(
2545           getOperation(),
2546           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()),
2547           getMapOperands(), memrefType,
2548           /*numIndexOperands=*/getNumOperands() - 2)))
2549     return failure();
2550 
2551   return success();
2552 }
2553 
2554 void AffineStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
2555                                                 MLIRContext *context) {
2556   results.add<SimplifyAffineOp<AffineStoreOp>>(context);
2557 }
2558 
2559 LogicalResult AffineStoreOp::fold(ArrayRef<Attribute> cstOperands,
2560                                   SmallVectorImpl<OpFoldResult> &results) {
2561   /// store(memrefcast) -> store
2562   return foldMemRefCast(*this, getValueToStore());
2563 }
2564 
2565 //===----------------------------------------------------------------------===//
2566 // AffineMinMaxOpBase
2567 //===----------------------------------------------------------------------===//
2568 
2569 template <typename T> static LogicalResult verifyAffineMinMaxOp(T op) {
2570   // Verify that operand count matches affine map dimension and symbol count.
2571   if (op.getNumOperands() != op.map().getNumDims() + op.map().getNumSymbols())
2572     return op.emitOpError(
2573         "operand count and affine map dimension and symbol count must match");
2574   return success();
2575 }
2576 
2577 template <typename T> static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
2578   p << ' ' << op->getAttr(T::getMapAttrName());
2579   auto operands = op.getOperands();
2580   unsigned numDims = op.map().getNumDims();
2581   p << '(' << operands.take_front(numDims) << ')';
2582 
2583   if (operands.size() != numDims)
2584     p << '[' << operands.drop_front(numDims) << ']';
2585   p.printOptionalAttrDict(op->getAttrs(),
2586                           /*elidedAttrs=*/{T::getMapAttrName()});
2587 }
2588 
2589 template <typename T>
2590 static ParseResult parseAffineMinMaxOp(OpAsmParser &parser,
2591                                        OperationState &result) {
2592   auto &builder = parser.getBuilder();
2593   auto indexType = builder.getIndexType();
2594   SmallVector<OpAsmParser::UnresolvedOperand, 8> dimInfos;
2595   SmallVector<OpAsmParser::UnresolvedOperand, 8> symInfos;
2596   AffineMapAttr mapAttr;
2597   return failure(
2598       parser.parseAttribute(mapAttr, T::getMapAttrName(), result.attributes) ||
2599       parser.parseOperandList(dimInfos, OpAsmParser::Delimiter::Paren) ||
2600       parser.parseOperandList(symInfos,
2601                               OpAsmParser::Delimiter::OptionalSquare) ||
2602       parser.parseOptionalAttrDict(result.attributes) ||
2603       parser.resolveOperands(dimInfos, indexType, result.operands) ||
2604       parser.resolveOperands(symInfos, indexType, result.operands) ||
2605       parser.addTypeToList(indexType, result.types));
2606 }
2607 
2608 /// Fold an affine min or max operation with the given operands. The operand
2609 /// list may contain nulls, which are interpreted as the operand not being a
2610 /// constant.
2611 template <typename T>
2612 static OpFoldResult foldMinMaxOp(T op, ArrayRef<Attribute> operands) {
2613   static_assert(llvm::is_one_of<T, AffineMinOp, AffineMaxOp>::value,
2614                 "expected affine min or max op");
2615 
2616   // Fold the affine map.
2617   // TODO: Fold more cases:
2618   // min(some_affine, some_affine + constant, ...), etc.
2619   SmallVector<int64_t, 2> results;
2620   auto foldedMap = op.map().partialConstantFold(operands, &results);
2621 
2622   // If some of the map results are not constant, try changing the map in-place.
2623   if (results.empty()) {
2624     // If the map is the same, report that folding did not happen.
2625     if (foldedMap == op.map())
2626       return {};
2627     op->setAttr("map", AffineMapAttr::get(foldedMap));
2628     return op.getResult();
2629   }
2630 
2631   // Otherwise, completely fold the op into a constant.
2632   auto resultIt = std::is_same<T, AffineMinOp>::value
2633                       ? std::min_element(results.begin(), results.end())
2634                       : std::max_element(results.begin(), results.end());
2635   if (resultIt == results.end())
2636     return {};
2637   return IntegerAttr::get(IndexType::get(op.getContext()), *resultIt);
2638 }
2639 
2640 /// Remove duplicated expressions in affine min/max ops.
2641 template <typename T>
2642 struct DeduplicateAffineMinMaxExpressions : public OpRewritePattern<T> {
2643   using OpRewritePattern<T>::OpRewritePattern;
2644 
2645   LogicalResult matchAndRewrite(T affineOp,
2646                                 PatternRewriter &rewriter) const override {
2647     AffineMap oldMap = affineOp.getAffineMap();
2648 
2649     SmallVector<AffineExpr, 4> newExprs;
2650     for (AffineExpr expr : oldMap.getResults()) {
2651       // This is a linear scan over newExprs, but it should be fine given that
2652       // we typically just have a few expressions per op.
2653       if (!llvm::is_contained(newExprs, expr))
2654         newExprs.push_back(expr);
2655     }
2656 
2657     if (newExprs.size() == oldMap.getNumResults())
2658       return failure();
2659 
2660     auto newMap = AffineMap::get(oldMap.getNumDims(), oldMap.getNumSymbols(),
2661                                  newExprs, rewriter.getContext());
2662     rewriter.replaceOpWithNewOp<T>(affineOp, newMap, affineOp.getMapOperands());
2663 
2664     return success();
2665   }
2666 };
2667 
2668 /// Merge an affine min/max op to its consumers if its consumer is also an
2669 /// affine min/max op.
2670 ///
2671 /// This pattern requires the producer affine min/max op is bound to a
2672 /// dimension/symbol that is used as a standalone expression in the consumer
2673 /// affine op's map.
2674 ///
2675 /// For example, a pattern like the following:
2676 ///
2677 ///   %0 = affine.min affine_map<()[s0] -> (s0 + 16, s0 * 8)> ()[%sym1]
2678 ///   %1 = affine.min affine_map<(d0)[s0] -> (s0 + 4, d0)> (%0)[%sym2]
2679 ///
2680 /// Can be turned into:
2681 ///
2682 ///   %1 = affine.min affine_map<
2683 ///          ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1]
2684 template <typename T> struct MergeAffineMinMaxOp : public OpRewritePattern<T> {
2685   using OpRewritePattern<T>::OpRewritePattern;
2686 
2687   LogicalResult matchAndRewrite(T affineOp,
2688                                 PatternRewriter &rewriter) const override {
2689     AffineMap oldMap = affineOp.getAffineMap();
2690     ValueRange dimOperands =
2691         affineOp.getMapOperands().take_front(oldMap.getNumDims());
2692     ValueRange symOperands =
2693         affineOp.getMapOperands().take_back(oldMap.getNumSymbols());
2694 
2695     auto newDimOperands = llvm::to_vector<8>(dimOperands);
2696     auto newSymOperands = llvm::to_vector<8>(symOperands);
2697     SmallVector<AffineExpr, 4> newExprs;
2698     SmallVector<T, 4> producerOps;
2699 
2700     // Go over each expression to see whether it's a single dimension/symbol
2701     // with the corresponding operand which is the result of another affine
2702     // min/max op. If So it can be merged into this affine op.
2703     for (AffineExpr expr : oldMap.getResults()) {
2704       if (auto symExpr = expr.dyn_cast<AffineSymbolExpr>()) {
2705         Value symValue = symOperands[symExpr.getPosition()];
2706         if (auto producerOp = symValue.getDefiningOp<T>()) {
2707           producerOps.push_back(producerOp);
2708           continue;
2709         }
2710       } else if (auto dimExpr = expr.dyn_cast<AffineDimExpr>()) {
2711         Value dimValue = dimOperands[dimExpr.getPosition()];
2712         if (auto producerOp = dimValue.getDefiningOp<T>()) {
2713           producerOps.push_back(producerOp);
2714           continue;
2715         }
2716       }
2717       // For the above cases we will remove the expression by merging the
2718       // producer affine min/max's affine expressions. Otherwise we need to
2719       // keep the existing expression.
2720       newExprs.push_back(expr);
2721     }
2722 
2723     if (producerOps.empty())
2724       return failure();
2725 
2726     unsigned numUsedDims = oldMap.getNumDims();
2727     unsigned numUsedSyms = oldMap.getNumSymbols();
2728 
2729     // Now go over all producer affine ops and merge their expressions.
2730     for (T producerOp : producerOps) {
2731       AffineMap producerMap = producerOp.getAffineMap();
2732       unsigned numProducerDims = producerMap.getNumDims();
2733       unsigned numProducerSyms = producerMap.getNumSymbols();
2734 
2735       // Collect all dimension/symbol values.
2736       ValueRange dimValues =
2737           producerOp.getMapOperands().take_front(numProducerDims);
2738       ValueRange symValues =
2739           producerOp.getMapOperands().take_back(numProducerSyms);
2740       newDimOperands.append(dimValues.begin(), dimValues.end());
2741       newSymOperands.append(symValues.begin(), symValues.end());
2742 
2743       // For expressions we need to shift to avoid overlap.
2744       for (AffineExpr expr : producerMap.getResults()) {
2745         newExprs.push_back(expr.shiftDims(numProducerDims, numUsedDims)
2746                                .shiftSymbols(numProducerSyms, numUsedSyms));
2747       }
2748 
2749       numUsedDims += numProducerDims;
2750       numUsedSyms += numProducerSyms;
2751     }
2752 
2753     auto newMap = AffineMap::get(numUsedDims, numUsedSyms, newExprs,
2754                                  rewriter.getContext());
2755     auto newOperands =
2756         llvm::to_vector<8>(llvm::concat<Value>(newDimOperands, newSymOperands));
2757     rewriter.replaceOpWithNewOp<T>(affineOp, newMap, newOperands);
2758 
2759     return success();
2760   }
2761 };
2762 
2763 /// Canonicalize the result expression order of an affine map and return success
2764 /// if the order changed.
2765 ///
2766 /// The function flattens the map's affine expressions to coefficient arrays and
2767 /// sorts them in lexicographic order. A coefficient array contains a multiplier
2768 /// for every dimension/symbol and a constant term. The canonicalization fails
2769 /// if a result expression is not pure or if the flattening requires local
2770 /// variables that, unlike dimensions and symbols, have no global order.
2771 static LogicalResult canonicalizeMapExprAndTermOrder(AffineMap &map) {
2772   SmallVector<SmallVector<int64_t>> flattenedExprs;
2773   for (const AffineExpr &resultExpr : map.getResults()) {
2774     // Fail if the expression is not pure.
2775     if (!resultExpr.isPureAffine())
2776       return failure();
2777 
2778     SimpleAffineExprFlattener flattener(map.getNumDims(), map.getNumSymbols());
2779     flattener.walkPostOrder(resultExpr);
2780 
2781     // Fail if the flattened expression has local variables.
2782     if (flattener.operandExprStack.back().size() !=
2783         map.getNumDims() + map.getNumSymbols() + 1)
2784       return failure();
2785 
2786     flattenedExprs.emplace_back(flattener.operandExprStack.back().begin(),
2787                                 flattener.operandExprStack.back().end());
2788   }
2789 
2790   // Fail if sorting is not necessary.
2791   if (llvm::is_sorted(flattenedExprs))
2792     return failure();
2793 
2794   // Reorder the result expressions according to their flattened form.
2795   SmallVector<unsigned> resultPermutation =
2796       llvm::to_vector(llvm::seq<unsigned>(0, map.getNumResults()));
2797   llvm::sort(resultPermutation, [&](unsigned lhs, unsigned rhs) {
2798     return flattenedExprs[lhs] < flattenedExprs[rhs];
2799   });
2800   SmallVector<AffineExpr> newExprs;
2801   for (unsigned idx : resultPermutation)
2802     newExprs.push_back(map.getResult(idx));
2803 
2804   map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), newExprs,
2805                        map.getContext());
2806   return success();
2807 }
2808 
2809 /// Canonicalize the affine map result expression order of an affine min/max
2810 /// operation.
2811 ///
2812 /// The pattern calls `canonicalizeMapExprAndTermOrder` to order the result
2813 /// expressions and replaces the operation if the order changed.
2814 ///
2815 /// For example, the following operation:
2816 ///
2817 ///   %0 = affine.min affine_map<(d0, d1) -> (d0 + d1, d1 + 16, 32)> (%i0, %i1)
2818 ///
2819 /// Turns into:
2820 ///
2821 ///   %0 = affine.min affine_map<(d0, d1) -> (32, d1 + 16, d0 + d1)> (%i0, %i1)
2822 template <typename T>
2823 struct CanonicalizeAffineMinMaxOpExprAndTermOrder : public OpRewritePattern<T> {
2824   using OpRewritePattern<T>::OpRewritePattern;
2825 
2826   LogicalResult matchAndRewrite(T affineOp,
2827                                 PatternRewriter &rewriter) const override {
2828     AffineMap map = affineOp.getAffineMap();
2829     if (failed(canonicalizeMapExprAndTermOrder(map)))
2830       return failure();
2831 
2832     rewriter.replaceOpWithNewOp<T>(affineOp, map, affineOp.getMapOperands());
2833     return success();
2834   }
2835 };
2836 
2837 template <typename T>
2838 struct CanonicalizeSingleResultAffineMinMaxOp : public OpRewritePattern<T> {
2839   using OpRewritePattern<T>::OpRewritePattern;
2840 
2841   LogicalResult matchAndRewrite(T affineOp,
2842                                 PatternRewriter &rewriter) const override {
2843     if (affineOp.map().getNumResults() != 1)
2844       return failure();
2845     rewriter.replaceOpWithNewOp<AffineApplyOp>(affineOp, affineOp.map(),
2846                                                affineOp.getOperands());
2847     return success();
2848   }
2849 };
2850 
2851 //===----------------------------------------------------------------------===//
2852 // AffineMinOp
2853 //===----------------------------------------------------------------------===//
2854 //
2855 //   %0 = affine.min (d0) -> (1000, d0 + 512) (%i0)
2856 //
2857 
2858 OpFoldResult AffineMinOp::fold(ArrayRef<Attribute> operands) {
2859   return foldMinMaxOp(*this, operands);
2860 }
2861 
2862 void AffineMinOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2863                                               MLIRContext *context) {
2864   patterns.add<CanonicalizeSingleResultAffineMinMaxOp<AffineMinOp>,
2865                DeduplicateAffineMinMaxExpressions<AffineMinOp>,
2866                MergeAffineMinMaxOp<AffineMinOp>, SimplifyAffineOp<AffineMinOp>,
2867                CanonicalizeAffineMinMaxOpExprAndTermOrder<AffineMinOp>>(
2868       context);
2869 }
2870 
2871 LogicalResult AffineMinOp::verify() { return verifyAffineMinMaxOp(*this); }
2872 
2873 ParseResult AffineMinOp::parse(OpAsmParser &parser, OperationState &result) {
2874   return parseAffineMinMaxOp<AffineMinOp>(parser, result);
2875 }
2876 
2877 void AffineMinOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
2878 
2879 //===----------------------------------------------------------------------===//
2880 // AffineMaxOp
2881 //===----------------------------------------------------------------------===//
2882 //
2883 //   %0 = affine.max (d0) -> (1000, d0 + 512) (%i0)
2884 //
2885 
2886 OpFoldResult AffineMaxOp::fold(ArrayRef<Attribute> operands) {
2887   return foldMinMaxOp(*this, operands);
2888 }
2889 
2890 void AffineMaxOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2891                                               MLIRContext *context) {
2892   patterns.add<CanonicalizeSingleResultAffineMinMaxOp<AffineMaxOp>,
2893                DeduplicateAffineMinMaxExpressions<AffineMaxOp>,
2894                MergeAffineMinMaxOp<AffineMaxOp>, SimplifyAffineOp<AffineMaxOp>,
2895                CanonicalizeAffineMinMaxOpExprAndTermOrder<AffineMaxOp>>(
2896       context);
2897 }
2898 
2899 LogicalResult AffineMaxOp::verify() { return verifyAffineMinMaxOp(*this); }
2900 
2901 ParseResult AffineMaxOp::parse(OpAsmParser &parser, OperationState &result) {
2902   return parseAffineMinMaxOp<AffineMaxOp>(parser, result);
2903 }
2904 
2905 void AffineMaxOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
2906 
2907 //===----------------------------------------------------------------------===//
2908 // AffinePrefetchOp
2909 //===----------------------------------------------------------------------===//
2910 
2911 //
2912 // affine.prefetch %0[%i, %j + 5], read, locality<3>, data : memref<400x400xi32>
2913 //
2914 ParseResult AffinePrefetchOp::parse(OpAsmParser &parser,
2915                                     OperationState &result) {
2916   auto &builder = parser.getBuilder();
2917   auto indexTy = builder.getIndexType();
2918 
2919   MemRefType type;
2920   OpAsmParser::UnresolvedOperand memrefInfo;
2921   IntegerAttr hintInfo;
2922   auto i32Type = parser.getBuilder().getIntegerType(32);
2923   StringRef readOrWrite, cacheType;
2924 
2925   AffineMapAttr mapAttr;
2926   SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
2927   if (parser.parseOperand(memrefInfo) ||
2928       parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
2929                                     AffinePrefetchOp::getMapAttrName(),
2930                                     result.attributes) ||
2931       parser.parseComma() || parser.parseKeyword(&readOrWrite) ||
2932       parser.parseComma() || parser.parseKeyword("locality") ||
2933       parser.parseLess() ||
2934       parser.parseAttribute(hintInfo, i32Type,
2935                             AffinePrefetchOp::getLocalityHintAttrName(),
2936                             result.attributes) ||
2937       parser.parseGreater() || parser.parseComma() ||
2938       parser.parseKeyword(&cacheType) ||
2939       parser.parseOptionalAttrDict(result.attributes) ||
2940       parser.parseColonType(type) ||
2941       parser.resolveOperand(memrefInfo, type, result.operands) ||
2942       parser.resolveOperands(mapOperands, indexTy, result.operands))
2943     return failure();
2944 
2945   if (!readOrWrite.equals("read") && !readOrWrite.equals("write"))
2946     return parser.emitError(parser.getNameLoc(),
2947                             "rw specifier has to be 'read' or 'write'");
2948   result.addAttribute(
2949       AffinePrefetchOp::getIsWriteAttrName(),
2950       parser.getBuilder().getBoolAttr(readOrWrite.equals("write")));
2951 
2952   if (!cacheType.equals("data") && !cacheType.equals("instr"))
2953     return parser.emitError(parser.getNameLoc(),
2954                             "cache type has to be 'data' or 'instr'");
2955 
2956   result.addAttribute(
2957       AffinePrefetchOp::getIsDataCacheAttrName(),
2958       parser.getBuilder().getBoolAttr(cacheType.equals("data")));
2959 
2960   return success();
2961 }
2962 
2963 void AffinePrefetchOp::print(OpAsmPrinter &p) {
2964   p << " " << memref() << '[';
2965   AffineMapAttr mapAttr =
2966       (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName());
2967   if (mapAttr)
2968     p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
2969   p << ']' << ", " << (isWrite() ? "write" : "read") << ", "
2970     << "locality<" << localityHint() << ">, "
2971     << (isDataCache() ? "data" : "instr");
2972   p.printOptionalAttrDict(
2973       (*this)->getAttrs(),
2974       /*elidedAttrs=*/{getMapAttrName(), getLocalityHintAttrName(),
2975                        getIsDataCacheAttrName(), getIsWriteAttrName()});
2976   p << " : " << getMemRefType();
2977 }
2978 
2979 LogicalResult AffinePrefetchOp::verify() {
2980   auto mapAttr = (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName());
2981   if (mapAttr) {
2982     AffineMap map = mapAttr.getValue();
2983     if (map.getNumResults() != getMemRefType().getRank())
2984       return emitOpError("affine.prefetch affine map num results must equal"
2985                          " memref rank");
2986     if (map.getNumInputs() + 1 != getNumOperands())
2987       return emitOpError("too few operands");
2988   } else {
2989     if (getNumOperands() != 1)
2990       return emitOpError("too few operands");
2991   }
2992 
2993   Region *scope = getAffineScope(*this);
2994   for (auto idx : getMapOperands()) {
2995     if (!isValidAffineIndexOperand(idx, scope))
2996       return emitOpError("index must be a dimension or symbol identifier");
2997   }
2998   return success();
2999 }
3000 
3001 void AffinePrefetchOp::getCanonicalizationPatterns(RewritePatternSet &results,
3002                                                    MLIRContext *context) {
3003   // prefetch(memrefcast) -> prefetch
3004   results.add<SimplifyAffineOp<AffinePrefetchOp>>(context);
3005 }
3006 
3007 LogicalResult AffinePrefetchOp::fold(ArrayRef<Attribute> cstOperands,
3008                                      SmallVectorImpl<OpFoldResult> &results) {
3009   /// prefetch(memrefcast) -> prefetch
3010   return foldMemRefCast(*this);
3011 }
3012 
3013 //===----------------------------------------------------------------------===//
3014 // AffineParallelOp
3015 //===----------------------------------------------------------------------===//
3016 
3017 void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
3018                              TypeRange resultTypes,
3019                              ArrayRef<arith::AtomicRMWKind> reductions,
3020                              ArrayRef<int64_t> ranges) {
3021   SmallVector<AffineMap> lbs(ranges.size(), builder.getConstantAffineMap(0));
3022   auto ubs = llvm::to_vector<4>(llvm::map_range(ranges, [&](int64_t value) {
3023     return builder.getConstantAffineMap(value);
3024   }));
3025   SmallVector<int64_t> steps(ranges.size(), 1);
3026   build(builder, result, resultTypes, reductions, lbs, /*lbArgs=*/{}, ubs,
3027         /*ubArgs=*/{}, steps);
3028 }
3029 
3030 void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
3031                              TypeRange resultTypes,
3032                              ArrayRef<arith::AtomicRMWKind> reductions,
3033                              ArrayRef<AffineMap> lbMaps, ValueRange lbArgs,
3034                              ArrayRef<AffineMap> ubMaps, ValueRange ubArgs,
3035                              ArrayRef<int64_t> steps) {
3036   assert(llvm::all_of(lbMaps,
3037                       [lbMaps](AffineMap m) {
3038                         return m.getNumDims() == lbMaps[0].getNumDims() &&
3039                                m.getNumSymbols() == lbMaps[0].getNumSymbols();
3040                       }) &&
3041          "expected all lower bounds maps to have the same number of dimensions "
3042          "and symbols");
3043   assert(llvm::all_of(ubMaps,
3044                       [ubMaps](AffineMap m) {
3045                         return m.getNumDims() == ubMaps[0].getNumDims() &&
3046                                m.getNumSymbols() == ubMaps[0].getNumSymbols();
3047                       }) &&
3048          "expected all upper bounds maps to have the same number of dimensions "
3049          "and symbols");
3050   assert((lbMaps.empty() || lbMaps[0].getNumInputs() == lbArgs.size()) &&
3051          "expected lower bound maps to have as many inputs as lower bound "
3052          "operands");
3053   assert((ubMaps.empty() || ubMaps[0].getNumInputs() == ubArgs.size()) &&
3054          "expected upper bound maps to have as many inputs as upper bound "
3055          "operands");
3056 
3057   result.addTypes(resultTypes);
3058 
3059   // Convert the reductions to integer attributes.
3060   SmallVector<Attribute, 4> reductionAttrs;
3061   for (arith::AtomicRMWKind reduction : reductions)
3062     reductionAttrs.push_back(
3063         builder.getI64IntegerAttr(static_cast<int64_t>(reduction)));
3064   result.addAttribute(getReductionsAttrName(),
3065                       builder.getArrayAttr(reductionAttrs));
3066 
3067   // Concatenates maps defined in the same input space (same dimensions and
3068   // symbols), assumes there is at least one map.
3069   auto concatMapsSameInput = [&builder](ArrayRef<AffineMap> maps,
3070                                         SmallVectorImpl<int32_t> &groups) {
3071     if (maps.empty())
3072       return AffineMap::get(builder.getContext());
3073     SmallVector<AffineExpr> exprs;
3074     groups.reserve(groups.size() + maps.size());
3075     exprs.reserve(maps.size());
3076     for (AffineMap m : maps) {
3077       llvm::append_range(exprs, m.getResults());
3078       groups.push_back(m.getNumResults());
3079     }
3080     return AffineMap::get(maps[0].getNumDims(), maps[0].getNumSymbols(), exprs,
3081                           maps[0].getContext());
3082   };
3083 
3084   // Set up the bounds.
3085   SmallVector<int32_t> lbGroups, ubGroups;
3086   AffineMap lbMap = concatMapsSameInput(lbMaps, lbGroups);
3087   AffineMap ubMap = concatMapsSameInput(ubMaps, ubGroups);
3088   result.addAttribute(getLowerBoundsMapAttrName(), AffineMapAttr::get(lbMap));
3089   result.addAttribute(getLowerBoundsGroupsAttrName(),
3090                       builder.getI32TensorAttr(lbGroups));
3091   result.addAttribute(getUpperBoundsMapAttrName(), AffineMapAttr::get(ubMap));
3092   result.addAttribute(getUpperBoundsGroupsAttrName(),
3093                       builder.getI32TensorAttr(ubGroups));
3094   result.addAttribute(getStepsAttrName(), builder.getI64ArrayAttr(steps));
3095   result.addOperands(lbArgs);
3096   result.addOperands(ubArgs);
3097 
3098   // Create a region and a block for the body.
3099   auto *bodyRegion = result.addRegion();
3100   auto *body = new Block();
3101   // Add all the block arguments.
3102   for (unsigned i = 0, e = steps.size(); i < e; ++i)
3103     body->addArgument(IndexType::get(builder.getContext()), result.location);
3104   bodyRegion->push_back(body);
3105   if (resultTypes.empty())
3106     ensureTerminator(*bodyRegion, builder, result.location);
3107 }
3108 
3109 Region &AffineParallelOp::getLoopBody() { return region(); }
3110 
3111 unsigned AffineParallelOp::getNumDims() { return steps().size(); }
3112 
3113 AffineParallelOp::operand_range AffineParallelOp::getLowerBoundsOperands() {
3114   return getOperands().take_front(lowerBoundsMap().getNumInputs());
3115 }
3116 
3117 AffineParallelOp::operand_range AffineParallelOp::getUpperBoundsOperands() {
3118   return getOperands().drop_front(lowerBoundsMap().getNumInputs());
3119 }
3120 
3121 AffineMap AffineParallelOp::getLowerBoundMap(unsigned pos) {
3122   auto values = lowerBoundsGroups().getValues<int32_t>();
3123   unsigned start = 0;
3124   for (unsigned i = 0; i < pos; ++i)
3125     start += values[i];
3126   return lowerBoundsMap().getSliceMap(start, values[pos]);
3127 }
3128 
3129 AffineMap AffineParallelOp::getUpperBoundMap(unsigned pos) {
3130   auto values = upperBoundsGroups().getValues<int32_t>();
3131   unsigned start = 0;
3132   for (unsigned i = 0; i < pos; ++i)
3133     start += values[i];
3134   return upperBoundsMap().getSliceMap(start, values[pos]);
3135 }
3136 
3137 AffineValueMap AffineParallelOp::getLowerBoundsValueMap() {
3138   return AffineValueMap(lowerBoundsMap(), getLowerBoundsOperands());
3139 }
3140 
3141 AffineValueMap AffineParallelOp::getUpperBoundsValueMap() {
3142   return AffineValueMap(upperBoundsMap(), getUpperBoundsOperands());
3143 }
3144 
3145 Optional<SmallVector<int64_t, 8>> AffineParallelOp::getConstantRanges() {
3146   if (hasMinMaxBounds())
3147     return llvm::None;
3148 
3149   // Try to convert all the ranges to constant expressions.
3150   SmallVector<int64_t, 8> out;
3151   AffineValueMap rangesValueMap;
3152   AffineValueMap::difference(getUpperBoundsValueMap(), getLowerBoundsValueMap(),
3153                              &rangesValueMap);
3154   out.reserve(rangesValueMap.getNumResults());
3155   for (unsigned i = 0, e = rangesValueMap.getNumResults(); i < e; ++i) {
3156     auto expr = rangesValueMap.getResult(i);
3157     auto cst = expr.dyn_cast<AffineConstantExpr>();
3158     if (!cst)
3159       return llvm::None;
3160     out.push_back(cst.getValue());
3161   }
3162   return out;
3163 }
3164 
3165 Block *AffineParallelOp::getBody() { return &region().front(); }
3166 
3167 OpBuilder AffineParallelOp::getBodyBuilder() {
3168   return OpBuilder(getBody(), std::prev(getBody()->end()));
3169 }
3170 
3171 void AffineParallelOp::setLowerBounds(ValueRange lbOperands, AffineMap map) {
3172   assert(lbOperands.size() == map.getNumInputs() &&
3173          "operands to map must match number of inputs");
3174 
3175   auto ubOperands = getUpperBoundsOperands();
3176 
3177   SmallVector<Value, 4> newOperands(lbOperands);
3178   newOperands.append(ubOperands.begin(), ubOperands.end());
3179   (*this)->setOperands(newOperands);
3180 
3181   lowerBoundsMapAttr(AffineMapAttr::get(map));
3182 }
3183 
3184 void AffineParallelOp::setUpperBounds(ValueRange ubOperands, AffineMap map) {
3185   assert(ubOperands.size() == map.getNumInputs() &&
3186          "operands to map must match number of inputs");
3187 
3188   SmallVector<Value, 4> newOperands(getLowerBoundsOperands());
3189   newOperands.append(ubOperands.begin(), ubOperands.end());
3190   (*this)->setOperands(newOperands);
3191 
3192   upperBoundsMapAttr(AffineMapAttr::get(map));
3193 }
3194 
3195 void AffineParallelOp::setLowerBoundsMap(AffineMap map) {
3196   AffineMap lbMap = lowerBoundsMap();
3197   assert(lbMap.getNumDims() == map.getNumDims() &&
3198          lbMap.getNumSymbols() == map.getNumSymbols());
3199   (void)lbMap;
3200   lowerBoundsMapAttr(AffineMapAttr::get(map));
3201 }
3202 
3203 void AffineParallelOp::setUpperBoundsMap(AffineMap map) {
3204   AffineMap ubMap = upperBoundsMap();
3205   assert(ubMap.getNumDims() == map.getNumDims() &&
3206          ubMap.getNumSymbols() == map.getNumSymbols());
3207   (void)ubMap;
3208   upperBoundsMapAttr(AffineMapAttr::get(map));
3209 }
3210 
3211 SmallVector<int64_t, 8> AffineParallelOp::getSteps() {
3212   SmallVector<int64_t, 8> result;
3213   for (Attribute attr : steps()) {
3214     result.push_back(attr.cast<IntegerAttr>().getInt());
3215   }
3216   return result;
3217 }
3218 
3219 void AffineParallelOp::setSteps(ArrayRef<int64_t> newSteps) {
3220   stepsAttr(getBodyBuilder().getI64ArrayAttr(newSteps));
3221 }
3222 
3223 LogicalResult AffineParallelOp::verify() {
3224   auto numDims = getNumDims();
3225   if (lowerBoundsGroups().getNumElements() != numDims ||
3226       upperBoundsGroups().getNumElements() != numDims ||
3227       steps().size() != numDims || getBody()->getNumArguments() != numDims) {
3228     return emitOpError() << "the number of region arguments ("
3229                          << getBody()->getNumArguments()
3230                          << ") and the number of map groups for lower ("
3231                          << lowerBoundsGroups().getNumElements()
3232                          << ") and upper bound ("
3233                          << upperBoundsGroups().getNumElements()
3234                          << "), and the number of steps (" << steps().size()
3235                          << ") must all match";
3236   }
3237 
3238   unsigned expectedNumLBResults = 0;
3239   for (APInt v : lowerBoundsGroups())
3240     expectedNumLBResults += v.getZExtValue();
3241   if (expectedNumLBResults != lowerBoundsMap().getNumResults())
3242     return emitOpError() << "expected lower bounds map to have "
3243                          << expectedNumLBResults << " results";
3244   unsigned expectedNumUBResults = 0;
3245   for (APInt v : upperBoundsGroups())
3246     expectedNumUBResults += v.getZExtValue();
3247   if (expectedNumUBResults != upperBoundsMap().getNumResults())
3248     return emitOpError() << "expected upper bounds map to have "
3249                          << expectedNumUBResults << " results";
3250 
3251   if (reductions().size() != getNumResults())
3252     return emitOpError("a reduction must be specified for each output");
3253 
3254   // Verify reduction  ops are all valid
3255   for (Attribute attr : reductions()) {
3256     auto intAttr = attr.dyn_cast<IntegerAttr>();
3257     if (!intAttr || !arith::symbolizeAtomicRMWKind(intAttr.getInt()))
3258       return emitOpError("invalid reduction attribute");
3259   }
3260 
3261   // Verify that the bound operands are valid dimension/symbols.
3262   /// Lower bounds.
3263   if (failed(verifyDimAndSymbolIdentifiers(*this, getLowerBoundsOperands(),
3264                                            lowerBoundsMap().getNumDims())))
3265     return failure();
3266   /// Upper bounds.
3267   if (failed(verifyDimAndSymbolIdentifiers(*this, getUpperBoundsOperands(),
3268                                            upperBoundsMap().getNumDims())))
3269     return failure();
3270   return success();
3271 }
3272 
3273 LogicalResult AffineValueMap::canonicalize() {
3274   SmallVector<Value, 4> newOperands{operands};
3275   auto newMap = getAffineMap();
3276   composeAffineMapAndOperands(&newMap, &newOperands);
3277   if (newMap == getAffineMap() && newOperands == operands)
3278     return failure();
3279   reset(newMap, newOperands);
3280   return success();
3281 }
3282 
3283 /// Canonicalize the bounds of the given loop.
3284 static LogicalResult canonicalizeLoopBounds(AffineParallelOp op) {
3285   AffineValueMap lb = op.getLowerBoundsValueMap();
3286   bool lbCanonicalized = succeeded(lb.canonicalize());
3287 
3288   AffineValueMap ub = op.getUpperBoundsValueMap();
3289   bool ubCanonicalized = succeeded(ub.canonicalize());
3290 
3291   // Any canonicalization change always leads to updated map(s).
3292   if (!lbCanonicalized && !ubCanonicalized)
3293     return failure();
3294 
3295   if (lbCanonicalized)
3296     op.setLowerBounds(lb.getOperands(), lb.getAffineMap());
3297   if (ubCanonicalized)
3298     op.setUpperBounds(ub.getOperands(), ub.getAffineMap());
3299 
3300   return success();
3301 }
3302 
3303 LogicalResult AffineParallelOp::fold(ArrayRef<Attribute> operands,
3304                                      SmallVectorImpl<OpFoldResult> &results) {
3305   return canonicalizeLoopBounds(*this);
3306 }
3307 
3308 /// Prints a lower(upper) bound of an affine parallel loop with max(min)
3309 /// conditions in it. `mapAttr` is a flat list of affine expressions and `group`
3310 /// identifies which of the those expressions form max/min groups. `operands`
3311 /// are the SSA values of dimensions and symbols and `keyword` is either "min"
3312 /// or "max".
3313 static void printMinMaxBound(OpAsmPrinter &p, AffineMapAttr mapAttr,
3314                              DenseIntElementsAttr group, ValueRange operands,
3315                              StringRef keyword) {
3316   AffineMap map = mapAttr.getValue();
3317   unsigned numDims = map.getNumDims();
3318   ValueRange dimOperands = operands.take_front(numDims);
3319   ValueRange symOperands = operands.drop_front(numDims);
3320   unsigned start = 0;
3321   for (llvm::APInt groupSize : group) {
3322     if (start != 0)
3323       p << ", ";
3324 
3325     unsigned size = groupSize.getZExtValue();
3326     if (size == 1) {
3327       p.printAffineExprOfSSAIds(map.getResult(start), dimOperands, symOperands);
3328       ++start;
3329     } else {
3330       p << keyword << '(';
3331       AffineMap submap = map.getSliceMap(start, size);
3332       p.printAffineMapOfSSAIds(AffineMapAttr::get(submap), operands);
3333       p << ')';
3334       start += size;
3335     }
3336   }
3337 }
3338 
3339 void AffineParallelOp::print(OpAsmPrinter &p) {
3340   p << " (" << getBody()->getArguments() << ") = (";
3341   printMinMaxBound(p, lowerBoundsMapAttr(), lowerBoundsGroupsAttr(),
3342                    getLowerBoundsOperands(), "max");
3343   p << ") to (";
3344   printMinMaxBound(p, upperBoundsMapAttr(), upperBoundsGroupsAttr(),
3345                    getUpperBoundsOperands(), "min");
3346   p << ')';
3347   SmallVector<int64_t, 8> steps = getSteps();
3348   bool elideSteps = llvm::all_of(steps, [](int64_t step) { return step == 1; });
3349   if (!elideSteps) {
3350     p << " step (";
3351     llvm::interleaveComma(steps, p);
3352     p << ')';
3353   }
3354   if (getNumResults()) {
3355     p << " reduce (";
3356     llvm::interleaveComma(reductions(), p, [&](auto &attr) {
3357       arith::AtomicRMWKind sym = *arith::symbolizeAtomicRMWKind(
3358           attr.template cast<IntegerAttr>().getInt());
3359       p << "\"" << arith::stringifyAtomicRMWKind(sym) << "\"";
3360     });
3361     p << ") -> (" << getResultTypes() << ")";
3362   }
3363 
3364   p << ' ';
3365   p.printRegion(region(), /*printEntryBlockArgs=*/false,
3366                 /*printBlockTerminators=*/getNumResults());
3367   p.printOptionalAttrDict(
3368       (*this)->getAttrs(),
3369       /*elidedAttrs=*/{AffineParallelOp::getReductionsAttrName(),
3370                        AffineParallelOp::getLowerBoundsMapAttrName(),
3371                        AffineParallelOp::getLowerBoundsGroupsAttrName(),
3372                        AffineParallelOp::getUpperBoundsMapAttrName(),
3373                        AffineParallelOp::getUpperBoundsGroupsAttrName(),
3374                        AffineParallelOp::getStepsAttrName()});
3375 }
3376 
3377 /// Given a list of lists of parsed operands, populates `uniqueOperands` with
3378 /// unique operands. Also populates `replacements with affine expressions of
3379 /// `kind` that can be used to update affine maps previously accepting a
3380 /// `operands` to accept `uniqueOperands` instead.
3381 static void deduplicateAndResolveOperands(
3382     OpAsmParser &parser,
3383     ArrayRef<SmallVector<OpAsmParser::UnresolvedOperand>> operands,
3384     SmallVectorImpl<Value> &uniqueOperands,
3385     SmallVectorImpl<AffineExpr> &replacements, AffineExprKind kind) {
3386   assert((kind == AffineExprKind::DimId || kind == AffineExprKind::SymbolId) &&
3387          "expected operands to be dim or symbol expression");
3388 
3389   Type indexType = parser.getBuilder().getIndexType();
3390   for (const auto &list : operands) {
3391     SmallVector<Value> valueOperands;
3392     parser.resolveOperands(list, indexType, valueOperands);
3393     for (Value operand : valueOperands) {
3394       unsigned pos = std::distance(uniqueOperands.begin(),
3395                                    llvm::find(uniqueOperands, operand));
3396       if (pos == uniqueOperands.size())
3397         uniqueOperands.push_back(operand);
3398       replacements.push_back(
3399           kind == AffineExprKind::DimId
3400               ? getAffineDimExpr(pos, parser.getContext())
3401               : getAffineSymbolExpr(pos, parser.getContext()));
3402     }
3403   }
3404 }
3405 
3406 namespace {
3407 enum class MinMaxKind { Min, Max };
3408 } // namespace
3409 
3410 /// Parses an affine map that can contain a min/max for groups of its results,
3411 /// e.g., max(expr-1, expr-2), expr-3, max(expr-4, expr-5, expr-6). Populates
3412 /// `result` attributes with the map (flat list of expressions) and the grouping
3413 /// (list of integers that specify how many expressions to put into each
3414 /// min/max) attributes. Deduplicates repeated operands.
3415 ///
3416 /// parallel-bound       ::= `(` parallel-group-list `)`
3417 /// parallel-group-list  ::= parallel-group (`,` parallel-group-list)?
3418 /// parallel-group       ::= simple-group | min-max-group
3419 /// simple-group         ::= expr-of-ssa-ids
3420 /// min-max-group        ::= ( `min` | `max` ) `(` expr-of-ssa-ids-list `)`
3421 /// expr-of-ssa-ids-list ::= expr-of-ssa-ids (`,` expr-of-ssa-id-list)?
3422 ///
3423 /// Examples:
3424 ///   (%0, min(%1 + %2, %3), %4, min(%5 floordiv 32, %6))
3425 ///   (%0, max(%1 - 2 * %2))
3426 static ParseResult parseAffineMapWithMinMax(OpAsmParser &parser,
3427                                             OperationState &result,
3428                                             MinMaxKind kind) {
3429   constexpr llvm::StringLiteral tmpAttrName = "__pseudo_bound_map";
3430 
3431   StringRef mapName = kind == MinMaxKind::Min
3432                           ? AffineParallelOp::getUpperBoundsMapAttrName()
3433                           : AffineParallelOp::getLowerBoundsMapAttrName();
3434   StringRef groupsName = kind == MinMaxKind::Min
3435                              ? AffineParallelOp::getUpperBoundsGroupsAttrName()
3436                              : AffineParallelOp::getLowerBoundsGroupsAttrName();
3437 
3438   if (failed(parser.parseLParen()))
3439     return failure();
3440 
3441   if (succeeded(parser.parseOptionalRParen())) {
3442     result.addAttribute(
3443         mapName, AffineMapAttr::get(parser.getBuilder().getEmptyAffineMap()));
3444     result.addAttribute(groupsName, parser.getBuilder().getI32TensorAttr({}));
3445     return success();
3446   }
3447 
3448   SmallVector<AffineExpr> flatExprs;
3449   SmallVector<SmallVector<OpAsmParser::UnresolvedOperand>> flatDimOperands;
3450   SmallVector<SmallVector<OpAsmParser::UnresolvedOperand>> flatSymOperands;
3451   SmallVector<int32_t> numMapsPerGroup;
3452   SmallVector<OpAsmParser::UnresolvedOperand> mapOperands;
3453   do {
3454     if (succeeded(parser.parseOptionalKeyword(
3455             kind == MinMaxKind::Min ? "min" : "max"))) {
3456       mapOperands.clear();
3457       AffineMapAttr map;
3458       if (failed(parser.parseAffineMapOfSSAIds(mapOperands, map, tmpAttrName,
3459                                                result.attributes,
3460                                                OpAsmParser::Delimiter::Paren)))
3461         return failure();
3462       result.attributes.erase(tmpAttrName);
3463       llvm::append_range(flatExprs, map.getValue().getResults());
3464       auto operandsRef = llvm::makeArrayRef(mapOperands);
3465       auto dimsRef = operandsRef.take_front(map.getValue().getNumDims());
3466       SmallVector<OpAsmParser::UnresolvedOperand> dims(dimsRef.begin(),
3467                                                        dimsRef.end());
3468       auto symsRef = operandsRef.drop_front(map.getValue().getNumDims());
3469       SmallVector<OpAsmParser::UnresolvedOperand> syms(symsRef.begin(),
3470                                                        symsRef.end());
3471       flatDimOperands.append(map.getValue().getNumResults(), dims);
3472       flatSymOperands.append(map.getValue().getNumResults(), syms);
3473       numMapsPerGroup.push_back(map.getValue().getNumResults());
3474     } else {
3475       if (failed(parser.parseAffineExprOfSSAIds(flatDimOperands.emplace_back(),
3476                                                 flatSymOperands.emplace_back(),
3477                                                 flatExprs.emplace_back())))
3478         return failure();
3479       numMapsPerGroup.push_back(1);
3480     }
3481   } while (succeeded(parser.parseOptionalComma()));
3482 
3483   if (failed(parser.parseRParen()))
3484     return failure();
3485 
3486   unsigned totalNumDims = 0;
3487   unsigned totalNumSyms = 0;
3488   for (unsigned i = 0, e = flatExprs.size(); i < e; ++i) {
3489     unsigned numDims = flatDimOperands[i].size();
3490     unsigned numSyms = flatSymOperands[i].size();
3491     flatExprs[i] = flatExprs[i]
3492                        .shiftDims(numDims, totalNumDims)
3493                        .shiftSymbols(numSyms, totalNumSyms);
3494     totalNumDims += numDims;
3495     totalNumSyms += numSyms;
3496   }
3497 
3498   // Deduplicate map operands.
3499   SmallVector<Value> dimOperands, symOperands;
3500   SmallVector<AffineExpr> dimRplacements, symRepacements;
3501   deduplicateAndResolveOperands(parser, flatDimOperands, dimOperands,
3502                                 dimRplacements, AffineExprKind::DimId);
3503   deduplicateAndResolveOperands(parser, flatSymOperands, symOperands,
3504                                 symRepacements, AffineExprKind::SymbolId);
3505 
3506   result.operands.append(dimOperands.begin(), dimOperands.end());
3507   result.operands.append(symOperands.begin(), symOperands.end());
3508 
3509   Builder &builder = parser.getBuilder();
3510   auto flatMap = AffineMap::get(totalNumDims, totalNumSyms, flatExprs,
3511                                 parser.getContext());
3512   flatMap = flatMap.replaceDimsAndSymbols(
3513       dimRplacements, symRepacements, dimOperands.size(), symOperands.size());
3514 
3515   result.addAttribute(mapName, AffineMapAttr::get(flatMap));
3516   result.addAttribute(groupsName, builder.getI32TensorAttr(numMapsPerGroup));
3517   return success();
3518 }
3519 
3520 //
3521 // operation ::= `affine.parallel` `(` ssa-ids `)` `=` parallel-bound
3522 //               `to` parallel-bound steps? region attr-dict?
3523 // steps     ::= `steps` `(` integer-literals `)`
3524 //
3525 ParseResult AffineParallelOp::parse(OpAsmParser &parser,
3526                                     OperationState &result) {
3527   auto &builder = parser.getBuilder();
3528   auto indexType = builder.getIndexType();
3529   SmallVector<OpAsmParser::UnresolvedOperand, 4> ivs;
3530   if (parser.parseRegionArgumentList(ivs, /*requiredOperandCount=*/-1,
3531                                      OpAsmParser::Delimiter::Paren) ||
3532       parser.parseEqual() ||
3533       parseAffineMapWithMinMax(parser, result, MinMaxKind::Max) ||
3534       parser.parseKeyword("to") ||
3535       parseAffineMapWithMinMax(parser, result, MinMaxKind::Min))
3536     return failure();
3537 
3538   AffineMapAttr stepsMapAttr;
3539   NamedAttrList stepsAttrs;
3540   SmallVector<OpAsmParser::UnresolvedOperand, 4> stepsMapOperands;
3541   if (failed(parser.parseOptionalKeyword("step"))) {
3542     SmallVector<int64_t, 4> steps(ivs.size(), 1);
3543     result.addAttribute(AffineParallelOp::getStepsAttrName(),
3544                         builder.getI64ArrayAttr(steps));
3545   } else {
3546     if (parser.parseAffineMapOfSSAIds(stepsMapOperands, stepsMapAttr,
3547                                       AffineParallelOp::getStepsAttrName(),
3548                                       stepsAttrs,
3549                                       OpAsmParser::Delimiter::Paren))
3550       return failure();
3551 
3552     // Convert steps from an AffineMap into an I64ArrayAttr.
3553     SmallVector<int64_t, 4> steps;
3554     auto stepsMap = stepsMapAttr.getValue();
3555     for (const auto &result : stepsMap.getResults()) {
3556       auto constExpr = result.dyn_cast<AffineConstantExpr>();
3557       if (!constExpr)
3558         return parser.emitError(parser.getNameLoc(),
3559                                 "steps must be constant integers");
3560       steps.push_back(constExpr.getValue());
3561     }
3562     result.addAttribute(AffineParallelOp::getStepsAttrName(),
3563                         builder.getI64ArrayAttr(steps));
3564   }
3565 
3566   // Parse optional clause of the form: `reduce ("addf", "maxf")`, where the
3567   // quoted strings are a member of the enum AtomicRMWKind.
3568   SmallVector<Attribute, 4> reductions;
3569   if (succeeded(parser.parseOptionalKeyword("reduce"))) {
3570     if (parser.parseLParen())
3571       return failure();
3572     do {
3573       // Parse a single quoted string via the attribute parsing, and then
3574       // verify it is a member of the enum and convert to it's integer
3575       // representation.
3576       StringAttr attrVal;
3577       NamedAttrList attrStorage;
3578       auto loc = parser.getCurrentLocation();
3579       if (parser.parseAttribute(attrVal, builder.getNoneType(), "reduce",
3580                                 attrStorage))
3581         return failure();
3582       llvm::Optional<arith::AtomicRMWKind> reduction =
3583           arith::symbolizeAtomicRMWKind(attrVal.getValue());
3584       if (!reduction)
3585         return parser.emitError(loc, "invalid reduction value: ") << attrVal;
3586       reductions.push_back(builder.getI64IntegerAttr(
3587           static_cast<int64_t>(reduction.getValue())));
3588       // While we keep getting commas, keep parsing.
3589     } while (succeeded(parser.parseOptionalComma()));
3590     if (parser.parseRParen())
3591       return failure();
3592   }
3593   result.addAttribute(AffineParallelOp::getReductionsAttrName(),
3594                       builder.getArrayAttr(reductions));
3595 
3596   // Parse return types of reductions (if any)
3597   if (parser.parseOptionalArrowTypeList(result.types))
3598     return failure();
3599 
3600   // Now parse the body.
3601   Region *body = result.addRegion();
3602   SmallVector<Type, 4> types(ivs.size(), indexType);
3603   if (parser.parseRegion(*body, ivs, types) ||
3604       parser.parseOptionalAttrDict(result.attributes))
3605     return failure();
3606 
3607   // Add a terminator if none was parsed.
3608   AffineParallelOp::ensureTerminator(*body, builder, result.location);
3609   return success();
3610 }
3611 
3612 //===----------------------------------------------------------------------===//
3613 // AffineYieldOp
3614 //===----------------------------------------------------------------------===//
3615 
3616 LogicalResult AffineYieldOp::verify() {
3617   auto *parentOp = (*this)->getParentOp();
3618   auto results = parentOp->getResults();
3619   auto operands = getOperands();
3620 
3621   if (!isa<AffineParallelOp, AffineIfOp, AffineForOp>(parentOp))
3622     return emitOpError() << "only terminates affine.if/for/parallel regions";
3623   if (parentOp->getNumResults() != getNumOperands())
3624     return emitOpError() << "parent of yield must have same number of "
3625                             "results as the yield operands";
3626   for (auto it : llvm::zip(results, operands)) {
3627     if (std::get<0>(it).getType() != std::get<1>(it).getType())
3628       return emitOpError() << "types mismatch between yield op and its parent";
3629   }
3630 
3631   return success();
3632 }
3633 
3634 //===----------------------------------------------------------------------===//
3635 // AffineVectorLoadOp
3636 //===----------------------------------------------------------------------===//
3637 
3638 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
3639                                VectorType resultType, AffineMap map,
3640                                ValueRange operands) {
3641   assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
3642   result.addOperands(operands);
3643   if (map)
3644     result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
3645   result.types.push_back(resultType);
3646 }
3647 
3648 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
3649                                VectorType resultType, Value memref,
3650                                AffineMap map, ValueRange mapOperands) {
3651   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3652   result.addOperands(memref);
3653   result.addOperands(mapOperands);
3654   result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
3655   result.types.push_back(resultType);
3656 }
3657 
3658 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
3659                                VectorType resultType, Value memref,
3660                                ValueRange indices) {
3661   auto memrefType = memref.getType().cast<MemRefType>();
3662   int64_t rank = memrefType.getRank();
3663   // Create identity map for memrefs with at least one dimension or () -> ()
3664   // for zero-dimensional memrefs.
3665   auto map =
3666       rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3667   build(builder, result, resultType, memref, map, indices);
3668 }
3669 
3670 void AffineVectorLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3671                                                      MLIRContext *context) {
3672   results.add<SimplifyAffineOp<AffineVectorLoadOp>>(context);
3673 }
3674 
3675 ParseResult AffineVectorLoadOp::parse(OpAsmParser &parser,
3676                                       OperationState &result) {
3677   auto &builder = parser.getBuilder();
3678   auto indexTy = builder.getIndexType();
3679 
3680   MemRefType memrefType;
3681   VectorType resultType;
3682   OpAsmParser::UnresolvedOperand memrefInfo;
3683   AffineMapAttr mapAttr;
3684   SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
3685   return failure(
3686       parser.parseOperand(memrefInfo) ||
3687       parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3688                                     AffineVectorLoadOp::getMapAttrName(),
3689                                     result.attributes) ||
3690       parser.parseOptionalAttrDict(result.attributes) ||
3691       parser.parseColonType(memrefType) || parser.parseComma() ||
3692       parser.parseType(resultType) ||
3693       parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
3694       parser.resolveOperands(mapOperands, indexTy, result.operands) ||
3695       parser.addTypeToList(resultType, result.types));
3696 }
3697 
3698 void AffineVectorLoadOp::print(OpAsmPrinter &p) {
3699   p << " " << getMemRef() << '[';
3700   if (AffineMapAttr mapAttr =
3701           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()))
3702     p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3703   p << ']';
3704   p.printOptionalAttrDict((*this)->getAttrs(),
3705                           /*elidedAttrs=*/{getMapAttrName()});
3706   p << " : " << getMemRefType() << ", " << getType();
3707 }
3708 
3709 /// Verify common invariants of affine.vector_load and affine.vector_store.
3710 static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType,
3711                                           VectorType vectorType) {
3712   // Check that memref and vector element types match.
3713   if (memrefType.getElementType() != vectorType.getElementType())
3714     return op->emitOpError(
3715         "requires memref and vector types of the same elemental type");
3716   return success();
3717 }
3718 
3719 LogicalResult AffineVectorLoadOp::verify() {
3720   MemRefType memrefType = getMemRefType();
3721   if (failed(verifyMemoryOpIndexing(
3722           getOperation(),
3723           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()),
3724           getMapOperands(), memrefType,
3725           /*numIndexOperands=*/getNumOperands() - 1)))
3726     return failure();
3727 
3728   if (failed(verifyVectorMemoryOp(getOperation(), memrefType, getVectorType())))
3729     return failure();
3730 
3731   return success();
3732 }
3733 
3734 //===----------------------------------------------------------------------===//
3735 // AffineVectorStoreOp
3736 //===----------------------------------------------------------------------===//
3737 
3738 void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &result,
3739                                 Value valueToStore, Value memref, AffineMap map,
3740                                 ValueRange mapOperands) {
3741   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3742   result.addOperands(valueToStore);
3743   result.addOperands(memref);
3744   result.addOperands(mapOperands);
3745   result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
3746 }
3747 
3748 // Use identity map.
3749 void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &result,
3750                                 Value valueToStore, Value memref,
3751                                 ValueRange indices) {
3752   auto memrefType = memref.getType().cast<MemRefType>();
3753   int64_t rank = memrefType.getRank();
3754   // Create identity map for memrefs with at least one dimension or () -> ()
3755   // for zero-dimensional memrefs.
3756   auto map =
3757       rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3758   build(builder, result, valueToStore, memref, map, indices);
3759 }
3760 void AffineVectorStoreOp::getCanonicalizationPatterns(
3761     RewritePatternSet &results, MLIRContext *context) {
3762   results.add<SimplifyAffineOp<AffineVectorStoreOp>>(context);
3763 }
3764 
3765 ParseResult AffineVectorStoreOp::parse(OpAsmParser &parser,
3766                                        OperationState &result) {
3767   auto indexTy = parser.getBuilder().getIndexType();
3768 
3769   MemRefType memrefType;
3770   VectorType resultType;
3771   OpAsmParser::UnresolvedOperand storeValueInfo;
3772   OpAsmParser::UnresolvedOperand memrefInfo;
3773   AffineMapAttr mapAttr;
3774   SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
3775   return failure(
3776       parser.parseOperand(storeValueInfo) || parser.parseComma() ||
3777       parser.parseOperand(memrefInfo) ||
3778       parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3779                                     AffineVectorStoreOp::getMapAttrName(),
3780                                     result.attributes) ||
3781       parser.parseOptionalAttrDict(result.attributes) ||
3782       parser.parseColonType(memrefType) || parser.parseComma() ||
3783       parser.parseType(resultType) ||
3784       parser.resolveOperand(storeValueInfo, resultType, result.operands) ||
3785       parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
3786       parser.resolveOperands(mapOperands, indexTy, result.operands));
3787 }
3788 
3789 void AffineVectorStoreOp::print(OpAsmPrinter &p) {
3790   p << " " << getValueToStore();
3791   p << ", " << getMemRef() << '[';
3792   if (AffineMapAttr mapAttr =
3793           (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()))
3794     p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3795   p << ']';
3796   p.printOptionalAttrDict((*this)->getAttrs(),
3797                           /*elidedAttrs=*/{getMapAttrName()});
3798   p << " : " << getMemRefType() << ", " << getValueToStore().getType();
3799 }
3800 
3801 LogicalResult AffineVectorStoreOp::verify() {
3802   MemRefType memrefType = getMemRefType();
3803   if (failed(verifyMemoryOpIndexing(
3804           *this, (*this)->getAttrOfType<AffineMapAttr>(getMapAttrName()),
3805           getMapOperands(), memrefType,
3806           /*numIndexOperands=*/getNumOperands() - 2)))
3807     return failure();
3808 
3809   if (failed(verifyVectorMemoryOp(*this, memrefType, getVectorType())))
3810     return failure();
3811 
3812   return success();
3813 }
3814 
3815 //===----------------------------------------------------------------------===//
3816 // TableGen'd op method definitions
3817 //===----------------------------------------------------------------------===//
3818 
3819 #define GET_OP_CLASSES
3820 #include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
3821