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