MLIR  22.0.0git
AffineOps.cpp
Go to the documentation of this file.
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 
14 #include "mlir/IR/AffineExpr.h"
16 #include "mlir/IR/IRMapping.h"
17 #include "mlir/IR/IntegerSet.h"
18 #include "mlir/IR/Matchers.h"
19 #include "mlir/IR/OpDefinition.h"
20 #include "mlir/IR/PatternMatch.h"
21 #include "mlir/IR/Value.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallBitVector.h"
27 #include "llvm/ADT/SmallVectorExtras.h"
28 #include "llvm/ADT/TypeSwitch.h"
29 #include "llvm/Support/DebugLog.h"
30 #include "llvm/Support/LogicalResult.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <numeric>
33 #include <optional>
34 
35 using namespace mlir;
36 using namespace mlir::affine;
37 
38 using llvm::divideCeilSigned;
39 using llvm::divideFloorSigned;
40 using llvm::mod;
41 
42 #define DEBUG_TYPE "affine-ops"
43 
44 #include "mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc"
45 
46 /// A utility function to check if a value is defined at the top level of
47 /// `region` or is an argument of `region`. A value of index type defined at the
48 /// top level of a `AffineScope` region is always a valid symbol for all
49 /// uses in that region.
51  if (auto arg = dyn_cast<BlockArgument>(value))
52  return arg.getParentRegion() == region;
53  return value.getDefiningOp()->getParentRegion() == region;
54 }
55 
56 /// Checks if `value` known to be a legal affine dimension or symbol in `src`
57 /// region remains legal if the operation that uses it is inlined into `dest`
58 /// with the given value mapping. `legalityCheck` is either `isValidDim` or
59 /// `isValidSymbol`, depending on the value being required to remain a valid
60 /// dimension or symbol.
61 static bool
63  const IRMapping &mapping,
64  function_ref<bool(Value, Region *)> legalityCheck) {
65  // If the value is a valid dimension for any other reason than being
66  // a top-level value, it will remain valid: constants get inlined
67  // with the function, transitive affine applies also get inlined and
68  // will be checked themselves, etc.
69  if (!isTopLevelValue(value, src))
70  return true;
71 
72  // If it's a top-level value because it's a block operand, i.e. a
73  // function argument, check whether the value replacing it after
74  // inlining is a valid dimension in the new region.
75  if (llvm::isa<BlockArgument>(value))
76  return legalityCheck(mapping.lookup(value), dest);
77 
78  // If it's a top-level value because it's defined in the region,
79  // it can only be inlined if the defining op is a constant or a
80  // `dim`, which can appear anywhere and be valid, since the defining
81  // op won't be top-level anymore after inlining.
82  Attribute operandCst;
83  bool isDimLikeOp = isa<ShapedDimOpInterface>(value.getDefiningOp());
84  return matchPattern(value.getDefiningOp(), m_Constant(&operandCst)) ||
85  isDimLikeOp;
86 }
87 
88 /// Checks if all values known to be legal affine dimensions or symbols in `src`
89 /// remain so if their respective users are inlined into `dest`.
90 static bool
92  const IRMapping &mapping,
93  function_ref<bool(Value, Region *)> legalityCheck) {
94  return llvm::all_of(values, [&](Value v) {
95  return remainsLegalAfterInline(v, src, dest, mapping, legalityCheck);
96  });
97 }
98 
99 /// Checks if an affine read or write operation remains legal after inlining
100 /// from `src` to `dest`.
101 template <typename OpTy>
102 static bool remainsLegalAfterInline(OpTy op, Region *src, Region *dest,
103  const IRMapping &mapping) {
104  static_assert(llvm::is_one_of<OpTy, AffineReadOpInterface,
105  AffineWriteOpInterface>::value,
106  "only ops with affine read/write interface are supported");
107 
108  AffineMap map = op.getAffineMap();
109  ValueRange dimOperands = op.getMapOperands().take_front(map.getNumDims());
110  ValueRange symbolOperands =
111  op.getMapOperands().take_back(map.getNumSymbols());
113  dimOperands, src, dest, mapping,
114  static_cast<bool (*)(Value, Region *)>(isValidDim)))
115  return false;
117  symbolOperands, src, dest, mapping,
118  static_cast<bool (*)(Value, Region *)>(isValidSymbol)))
119  return false;
120  return true;
121 }
122 
123 /// Checks if an affine apply operation remains legal after inlining from `src`
124 /// to `dest`.
125 // Use "unused attribute" marker to silence clang-tidy warning stemming from
126 // the inability to see through "llvm::TypeSwitch".
127 template <>
128 bool LLVM_ATTRIBUTE_UNUSED remainsLegalAfterInline(AffineApplyOp op,
129  Region *src, Region *dest,
130  const IRMapping &mapping) {
131  // If it's a valid dimension, we need to check that it remains so.
132  if (isValidDim(op.getResult(), src))
134  op.getMapOperands(), src, dest, mapping,
135  static_cast<bool (*)(Value, Region *)>(isValidDim));
136 
137  // Otherwise it must be a valid symbol, check that it remains so.
139  op.getMapOperands(), src, dest, mapping,
140  static_cast<bool (*)(Value, Region *)>(isValidSymbol));
141 }
142 
143 //===----------------------------------------------------------------------===//
144 // AffineDialect Interfaces
145 //===----------------------------------------------------------------------===//
146 
147 namespace {
148 /// This class defines the interface for handling inlining with affine
149 /// operations.
150 struct AffineInlinerInterface : public DialectInlinerInterface {
152 
153  //===--------------------------------------------------------------------===//
154  // Analysis Hooks
155  //===--------------------------------------------------------------------===//
156 
157  /// Returns true if the given region 'src' can be inlined into the region
158  /// 'dest' that is attached to an operation registered to the current dialect.
159  /// 'wouldBeCloned' is set if the region is cloned into its new location
160  /// rather than moved, indicating there may be other users.
161  bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
162  IRMapping &valueMapping) const final {
163  // We can inline into affine loops and conditionals if this doesn't break
164  // affine value categorization rules.
165  Operation *destOp = dest->getParentOp();
166  if (!isa<AffineParallelOp, AffineForOp, AffineIfOp>(destOp))
167  return false;
168 
169  // Multi-block regions cannot be inlined into affine constructs, all of
170  // which require single-block regions.
171  if (!src->hasOneBlock())
172  return false;
173 
174  // Side-effecting operations that the affine dialect cannot understand
175  // should not be inlined.
176  Block &srcBlock = src->front();
177  for (Operation &op : srcBlock) {
178  // Ops with no side effects are fine,
179  if (auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
180  if (iface.hasNoEffect())
181  continue;
182  }
183 
184  // Assuming the inlined region is valid, we only need to check if the
185  // inlining would change it.
186  bool remainsValid =
188  .Case<AffineApplyOp, AffineReadOpInterface,
189  AffineWriteOpInterface>([&](auto op) {
190  return remainsLegalAfterInline(op, src, dest, valueMapping);
191  })
192  .Default([](Operation *) {
193  // Conservatively disallow inlining ops we cannot reason about.
194  return false;
195  });
196 
197  if (!remainsValid)
198  return false;
199  }
200 
201  return true;
202  }
203 
204  /// Returns true if the given operation 'op', that is registered to this
205  /// dialect, can be inlined into the given region, false otherwise.
206  bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
207  IRMapping &valueMapping) const final {
208  // Always allow inlining affine operations into a region that is marked as
209  // affine scope, or into affine loops and conditionals. There are some edge
210  // cases when inlining *into* affine structures, but that is handled in the
211  // other 'isLegalToInline' hook above.
212  Operation *parentOp = region->getParentOp();
213  return parentOp->hasTrait<OpTrait::AffineScope>() ||
214  isa<AffineForOp, AffineParallelOp, AffineIfOp>(parentOp);
215  }
216 
217  /// Affine regions should be analyzed recursively.
218  bool shouldAnalyzeRecursively(Operation *op) const final { return true; }
219 };
220 } // namespace
221 
222 //===----------------------------------------------------------------------===//
223 // AffineDialect
224 //===----------------------------------------------------------------------===//
225 
226 void AffineDialect::initialize() {
227  addOperations<AffineDmaStartOp, AffineDmaWaitOp,
228 #define GET_OP_LIST
229 #include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
230  >();
231  addInterfaces<AffineInlinerInterface>();
232  declarePromisedInterfaces<ValueBoundsOpInterface, AffineApplyOp, AffineMaxOp,
233  AffineMinOp>();
234 }
235 
236 /// Materialize a single constant operation from a given attribute value with
237 /// the desired resultant type.
239  Attribute value, Type type,
240  Location loc) {
241  if (auto poison = dyn_cast<ub::PoisonAttr>(value))
242  return ub::PoisonOp::create(builder, loc, type, poison);
243  return arith::ConstantOp::materialize(builder, value, type, loc);
244 }
245 
246 /// A utility function to check if a value is defined at the top level of an
247 /// op with trait `AffineScope`. If the value is defined in an unlinked region,
248 /// conservatively assume it is not top-level. A value of index type defined at
249 /// the top level is always a valid symbol.
251  if (auto arg = dyn_cast<BlockArgument>(value)) {
252  // The block owning the argument may be unlinked, e.g. when the surrounding
253  // region has not yet been attached to an Op, at which point the parent Op
254  // is null.
255  Operation *parentOp = arg.getOwner()->getParentOp();
256  return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
257  }
258  // The defining Op may live in an unlinked block so its parent Op may be null.
259  Operation *parentOp = value.getDefiningOp()->getParentOp();
260  return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
261 }
262 
263 /// Returns the closest region enclosing `op` that is held by an operation with
264 /// trait `AffineScope`; `nullptr` if there is no such region.
266  auto *curOp = op;
267  while (auto *parentOp = curOp->getParentOp()) {
268  if (parentOp->hasTrait<OpTrait::AffineScope>())
269  return curOp->getParentRegion();
270  curOp = parentOp;
271  }
272  return nullptr;
273 }
274 
276  Operation *curOp = op;
277  while (auto *parentOp = curOp->getParentOp()) {
278  if (!isa<AffineForOp, AffineIfOp, AffineParallelOp>(parentOp))
279  return curOp->getParentRegion();
280  curOp = parentOp;
281  }
282  return nullptr;
283 }
284 
285 // A Value can be used as a dimension id iff it meets one of the following
286 // conditions:
287 // *) It is valid as a symbol.
288 // *) It is an induction variable.
289 // *) It is the result of affine apply operation with dimension id arguments.
291  // The value must be an index type.
292  if (!value.getType().isIndex())
293  return false;
294 
295  if (auto *defOp = value.getDefiningOp())
296  return isValidDim(value, getAffineScope(defOp));
297 
298  // This value has to be a block argument for an op that has the
299  // `AffineScope` trait or an induction var of an affine.for or
300  // affine.parallel.
301  if (isAffineInductionVar(value))
302  return true;
303  auto *parentOp = llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
304  return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
305 }
306 
307 // Value can be used as a dimension id iff it meets one of the following
308 // conditions:
309 // *) It is valid as a symbol.
310 // *) It is an induction variable.
311 // *) It is the result of an affine apply operation with dimension id operands.
312 // *) It is the result of a more specialized index transformation (ex.
313 // delinearize_index or linearize_index) with dimension id operands.
314 bool mlir::affine::isValidDim(Value value, Region *region) {
315  // The value must be an index type.
316  if (!value.getType().isIndex())
317  return false;
318 
319  // All valid symbols are okay.
320  if (isValidSymbol(value, region))
321  return true;
322 
323  auto *op = value.getDefiningOp();
324  if (!op) {
325  // This value has to be an induction var for an affine.for or an
326  // affine.parallel.
327  return isAffineInductionVar(value);
328  }
329 
330  // Affine apply operation is ok if all of its operands are ok.
331  if (auto applyOp = dyn_cast<AffineApplyOp>(op))
332  return applyOp.isValidDim(region);
333  // delinearize_index and linearize_index are special forms of apply
334  // and so are valid dimensions if all their arguments are valid dimensions.
335  if (isa<AffineDelinearizeIndexOp, AffineLinearizeIndexOp>(op))
336  return llvm::all_of(op->getOperands(),
337  [&](Value arg) { return ::isValidDim(arg, region); });
338  // The dim op is okay if its operand memref/tensor is defined at the top
339  // level.
340  if (auto dimOp = dyn_cast<ShapedDimOpInterface>(op))
341  return isTopLevelValue(dimOp.getShapedValue());
342  return false;
343 }
344 
345 /// Returns true if the 'index' dimension of the `memref` defined by
346 /// `memrefDefOp` is a statically shaped one or defined using a valid symbol
347 /// for `region`.
348 template <typename AnyMemRefDefOp>
349 static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index,
350  Region *region) {
351  MemRefType memRefType = memrefDefOp.getType();
352 
353  // Dimension index is out of bounds.
354  if (index >= memRefType.getRank()) {
355  return false;
356  }
357 
358  // Statically shaped.
359  if (!memRefType.isDynamicDim(index))
360  return true;
361  // Get the position of the dimension among dynamic dimensions;
362  unsigned dynamicDimPos = memRefType.getDynamicDimIndex(index);
363  return isValidSymbol(*(memrefDefOp.getDynamicSizes().begin() + dynamicDimPos),
364  region);
365 }
366 
367 /// Returns true if the result of the dim op is a valid symbol for `region`.
368 static bool isDimOpValidSymbol(ShapedDimOpInterface dimOp, Region *region) {
369  // The dim op is okay if its source is defined at the top level.
370  if (isTopLevelValue(dimOp.getShapedValue()))
371  return true;
372 
373  // Conservatively handle remaining BlockArguments as non-valid symbols.
374  // E.g. scf.for iterArgs.
375  if (llvm::isa<BlockArgument>(dimOp.getShapedValue()))
376  return false;
377 
378  // The dim op is also okay if its operand memref is a view/subview whose
379  // corresponding size is a valid symbol.
380  std::optional<int64_t> index = getConstantIntValue(dimOp.getDimension());
381 
382  // Be conservative if we can't understand the dimension.
383  if (!index.has_value())
384  return false;
385 
386  // Skip over all memref.cast ops (if any).
387  Operation *op = dimOp.getShapedValue().getDefiningOp();
388  while (auto castOp = dyn_cast<memref::CastOp>(op)) {
389  // Bail on unranked memrefs.
390  if (isa<UnrankedMemRefType>(castOp.getSource().getType()))
391  return false;
392  op = castOp.getSource().getDefiningOp();
393  if (!op)
394  return false;
395  }
396 
397  int64_t i = index.value();
399  .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
400  [&](auto op) { return isMemRefSizeValidSymbol(op, i, region); })
401  .Default([](Operation *) { return false; });
402 }
403 
404 // A value can be used as a symbol (at all its use sites) iff it meets one of
405 // the following conditions:
406 // *) It is a constant.
407 // *) Its defining op or block arg appearance is immediately enclosed by an op
408 // with `AffineScope` trait.
409 // *) It is the result of an affine.apply operation with symbol operands.
410 // *) It is a result of the dim op on a memref whose corresponding size is a
411 // valid symbol.
413  if (!value)
414  return false;
415 
416  // The value must be an index type.
417  if (!value.getType().isIndex())
418  return false;
419 
420  // Check that the value is a top level value.
421  if (isTopLevelValue(value))
422  return true;
423 
424  if (auto *defOp = value.getDefiningOp())
425  return isValidSymbol(value, getAffineScope(defOp));
426 
427  return false;
428 }
429 
430 /// A utility function to check if a value is defined at the top level of
431 /// `region` or is an argument of `region` or is defined above the region.
432 static bool isTopLevelValueOrAbove(Value value, Region *region) {
433  Region *parentRegion = value.getParentRegion();
434  do {
435  if (parentRegion == region)
436  return true;
437  Operation *regionOp = region->getParentOp();
438  if (regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
439  break;
440  region = region->getParentOp()->getParentRegion();
441  } while (region);
442  return false;
443 }
444 
445 /// A value can be used as a symbol for `region` iff it meets one of the
446 /// following conditions:
447 /// *) It is a constant.
448 /// *) It is a result of a `Pure` operation whose operands are valid symbolic
449 /// *) identifiers.
450 /// *) It is a result of the dim op on a memref whose corresponding size is
451 /// a valid symbol.
452 /// *) It is defined at the top level of 'region' or is its argument.
453 /// *) It dominates `region`'s parent op.
454 /// If `region` is null, conservatively assume the symbol definition scope does
455 /// not exist and only accept the values that would be symbols regardless of
456 /// the surrounding region structure, i.e. the first three cases above.
458  // The value must be an index type.
459  if (!value.getType().isIndex())
460  return false;
461 
462  // A top-level value is a valid symbol.
463  if (region && isTopLevelValueOrAbove(value, region))
464  return true;
465 
466  auto *defOp = value.getDefiningOp();
467  if (!defOp)
468  return false;
469 
470  // Constant operation is ok.
471  Attribute operandCst;
472  if (matchPattern(defOp, m_Constant(&operandCst)))
473  return true;
474 
475  // `Pure` operation that whose operands are valid symbolic identifiers.
476  if (isPure(defOp) && llvm::all_of(defOp->getOperands(), [&](Value operand) {
477  return affine::isValidSymbol(operand, region);
478  })) {
479  return true;
480  }
481 
482  // Dim op results could be valid symbols at any level.
483  if (auto dimOp = dyn_cast<ShapedDimOpInterface>(defOp))
484  return isDimOpValidSymbol(dimOp, region);
485 
486  return false;
487 }
488 
489 // Returns true if 'value' is a valid index to an affine operation (e.g.
490 // affine.load, affine.store, affine.dma_start, affine.dma_wait) where
491 // `region` provides the polyhedral symbol scope. Returns false otherwise.
492 static bool isValidAffineIndexOperand(Value value, Region *region) {
493  return isValidDim(value, region) || isValidSymbol(value, region);
494 }
495 
496 /// Prints dimension and symbol list.
499  unsigned numDims, OpAsmPrinter &printer) {
500  OperandRange operands(begin, end);
501  printer << '(' << operands.take_front(numDims) << ')';
502  if (operands.size() > numDims)
503  printer << '[' << operands.drop_front(numDims) << ']';
504 }
505 
506 /// Parses dimension and symbol list and returns true if parsing failed.
508  OpAsmParser &parser, SmallVectorImpl<Value> &operands, unsigned &numDims) {
510  if (parser.parseOperandList(opInfos, OpAsmParser::Delimiter::Paren))
511  return failure();
512  // Store number of dimensions for validation by caller.
513  numDims = opInfos.size();
514 
515  // Parse the optional symbol operands.
516  auto indexTy = parser.getBuilder().getIndexType();
517  return failure(parser.parseOperandList(
519  parser.resolveOperands(opInfos, indexTy, operands));
520 }
521 
522 /// Utility function to verify that a set of operands are valid dimension and
523 /// symbol identifiers. The operands should be laid out such that the dimension
524 /// operands are before the symbol operands. This function returns failure if
525 /// there was an invalid operand. An operation is provided to emit any necessary
526 /// errors.
527 template <typename OpTy>
528 static LogicalResult
530  unsigned numDims) {
531  unsigned opIt = 0;
532  for (auto operand : operands) {
533  if (opIt++ < numDims) {
534  if (!isValidDim(operand, getAffineScope(op)))
535  return op.emitOpError("operand cannot be used as a dimension id");
536  } else if (!isValidSymbol(operand, getAffineScope(op))) {
537  return op.emitOpError("operand cannot be used as a symbol");
538  }
539  }
540  return success();
541 }
542 
543 //===----------------------------------------------------------------------===//
544 // AffineApplyOp
545 //===----------------------------------------------------------------------===//
546 
547 AffineValueMap AffineApplyOp::getAffineValueMap() {
548  return AffineValueMap(getAffineMap(), getOperands(), getResult());
549 }
550 
551 ParseResult AffineApplyOp::parse(OpAsmParser &parser, OperationState &result) {
552  auto &builder = parser.getBuilder();
553  auto indexTy = builder.getIndexType();
554 
555  AffineMapAttr mapAttr;
556  unsigned numDims;
557  if (parser.parseAttribute(mapAttr, "map", result.attributes) ||
558  parseDimAndSymbolList(parser, result.operands, numDims) ||
559  parser.parseOptionalAttrDict(result.attributes))
560  return failure();
561  auto map = mapAttr.getValue();
562 
563  if (map.getNumDims() != numDims ||
564  numDims + map.getNumSymbols() != result.operands.size()) {
565  return parser.emitError(parser.getNameLoc(),
566  "dimension or symbol index mismatch");
567  }
568 
569  result.types.append(map.getNumResults(), indexTy);
570  return success();
571 }
572 
574  p << " " << getMapAttr();
575  printDimAndSymbolList(operand_begin(), operand_end(),
576  getAffineMap().getNumDims(), p);
577  p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{"map"});
578 }
579 
580 LogicalResult AffineApplyOp::verify() {
581  // Check input and output dimensions match.
582  AffineMap affineMap = getMap();
583 
584  // Verify that operand count matches affine map dimension and symbol count.
585  if (getNumOperands() != affineMap.getNumDims() + affineMap.getNumSymbols())
586  return emitOpError(
587  "operand count and affine map dimension and symbol count must match");
588 
589  // Verify that the map only produces one result.
590  if (affineMap.getNumResults() != 1)
591  return emitOpError("mapping must produce one value");
592 
593  // Do not allow valid dims to be used in symbol positions. We do allow
594  // affine.apply to use operands for values that may neither qualify as affine
595  // dims or affine symbols due to usage outside of affine ops, analyses, etc.
596  Region *region = getAffineScope(*this);
597  for (Value operand : getMapOperands().drop_front(affineMap.getNumDims())) {
598  if (::isValidDim(operand, region) && !::isValidSymbol(operand, region))
599  return emitError("dimensional operand cannot be used as a symbol");
600  }
601 
602  return success();
603 }
604 
605 // The result of the affine apply operation can be used as a dimension id if all
606 // its operands are valid dimension ids.
608  return llvm::all_of(getOperands(),
609  [](Value op) { return affine::isValidDim(op); });
610 }
611 
612 // The result of the affine apply operation can be used as a dimension id if all
613 // its operands are valid dimension ids with the parent operation of `region`
614 // defining the polyhedral scope for symbols.
615 bool AffineApplyOp::isValidDim(Region *region) {
616  return llvm::all_of(getOperands(),
617  [&](Value op) { return ::isValidDim(op, region); });
618 }
619 
620 // The result of the affine apply operation can be used as a symbol if all its
621 // operands are symbols.
623  return llvm::all_of(getOperands(),
624  [](Value op) { return affine::isValidSymbol(op); });
625 }
626 
627 // The result of the affine apply operation can be used as a symbol in `region`
628 // if all its operands are symbols in `region`.
629 bool AffineApplyOp::isValidSymbol(Region *region) {
630  return llvm::all_of(getOperands(), [&](Value operand) {
631  return affine::isValidSymbol(operand, region);
632  });
633 }
634 
635 OpFoldResult AffineApplyOp::fold(FoldAdaptor adaptor) {
636  auto map = getAffineMap();
637 
638  // Fold dims and symbols to existing values.
639  auto expr = map.getResult(0);
640  if (auto dim = dyn_cast<AffineDimExpr>(expr))
641  return getOperand(dim.getPosition());
642  if (auto sym = dyn_cast<AffineSymbolExpr>(expr))
643  return getOperand(map.getNumDims() + sym.getPosition());
644 
645  // Otherwise, default to folding the map.
647  bool hasPoison = false;
648  auto foldResult =
649  map.constantFold(adaptor.getMapOperands(), result, &hasPoison);
650  if (hasPoison)
652  if (failed(foldResult))
653  return {};
654  return result[0];
655 }
656 
657 /// Returns the largest known divisor of `e`. Exploits information from the
658 /// values in `operands`.
659 static int64_t getLargestKnownDivisor(AffineExpr e, ArrayRef<Value> operands) {
660  // This method isn't aware of `operands`.
661  int64_t div = e.getLargestKnownDivisor();
662 
663  // We now make use of operands for the case `e` is a dim expression.
664  // TODO: More powerful simplification would have to modify
665  // getLargestKnownDivisor to take `operands` and exploit that information as
666  // well for dim/sym expressions, but in that case, getLargestKnownDivisor
667  // can't be part of the IR library but of the `Analysis` library. The IR
668  // library can only really depend on simple O(1) checks.
669  auto dimExpr = dyn_cast<AffineDimExpr>(e);
670  // If it's not a dim expr, `div` is the best we have.
671  if (!dimExpr)
672  return div;
673 
674  // We simply exploit information from loop IVs.
675  // We don't need to use mlir::getLargestKnownDivisorOfValue since the other
676  // desired simplifications are expected to be part of other
677  // canonicalizations. Also, mlir::getLargestKnownDivisorOfValue is part of the
678  // LoopAnalysis library.
679  Value operand = operands[dimExpr.getPosition()];
680  int64_t operandDivisor = 1;
681  // TODO: With the right accessors, this can be extended to
682  // LoopLikeOpInterface.
683  if (AffineForOp forOp = getForInductionVarOwner(operand)) {
684  if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() == 0) {
685  operandDivisor = forOp.getStepAsInt();
686  } else {
687  uint64_t lbLargestKnownDivisor =
688  forOp.getLowerBoundMap().getLargestKnownDivisorOfMapExprs();
689  operandDivisor = std::gcd(lbLargestKnownDivisor, forOp.getStepAsInt());
690  }
691  }
692  return operandDivisor;
693 }
694 
695 /// Check if `e` is known to be: 0 <= `e` < `k`. Handles the simple cases of `e`
696 /// being an affine dim expression or a constant.
698  int64_t k) {
699  if (auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
700  int64_t constVal = constExpr.getValue();
701  return constVal >= 0 && constVal < k;
702  }
703  auto dimExpr = dyn_cast<AffineDimExpr>(e);
704  if (!dimExpr)
705  return false;
706  Value operand = operands[dimExpr.getPosition()];
707  // TODO: With the right accessors, this can be extended to
708  // LoopLikeOpInterface.
709  if (AffineForOp forOp = getForInductionVarOwner(operand)) {
710  if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() >= 0 &&
711  forOp.hasConstantUpperBound() && forOp.getConstantUpperBound() <= k) {
712  return true;
713  }
714  }
715 
716  // We don't consider other cases like `operand` being defined by a constant or
717  // an affine.apply op since such cases will already be handled by other
718  // patterns and propagation of loop IVs or constant would happen.
719  return false;
720 }
721 
722 /// Check if expression `e` is of the form d*e_1 + e_2 where 0 <= e_2 < d.
723 /// Set `div` to `d`, `quotientTimesDiv` to e_1 and `rem` to e_2 if the
724 /// expression is in that form.
725 static bool isQTimesDPlusR(AffineExpr e, ArrayRef<Value> operands, int64_t &div,
726  AffineExpr &quotientTimesDiv, AffineExpr &rem) {
727  auto bin = dyn_cast<AffineBinaryOpExpr>(e);
728  if (!bin || bin.getKind() != AffineExprKind::Add)
729  return false;
730 
731  AffineExpr llhs = bin.getLHS();
732  AffineExpr rlhs = bin.getRHS();
733  div = getLargestKnownDivisor(llhs, operands);
734  if (isNonNegativeBoundedBy(rlhs, operands, div)) {
735  quotientTimesDiv = llhs;
736  rem = rlhs;
737  return true;
738  }
739  div = getLargestKnownDivisor(rlhs, operands);
740  if (isNonNegativeBoundedBy(llhs, operands, div)) {
741  quotientTimesDiv = rlhs;
742  rem = llhs;
743  return true;
744  }
745  return false;
746 }
747 
748 /// Gets the constant lower bound on an `iv`.
749 static std::optional<int64_t> getLowerBound(Value iv) {
750  AffineForOp forOp = getForInductionVarOwner(iv);
751  if (forOp && forOp.hasConstantLowerBound())
752  return forOp.getConstantLowerBound();
753  return std::nullopt;
754 }
755 
756 /// Gets the constant upper bound on an affine.for `iv`.
757 static std::optional<int64_t> getUpperBound(Value iv) {
758  AffineForOp forOp = getForInductionVarOwner(iv);
759  if (!forOp || !forOp.hasConstantUpperBound())
760  return std::nullopt;
761 
762  // If its lower bound is also known, we can get a more precise bound
763  // whenever the step is not one.
764  if (forOp.hasConstantLowerBound()) {
765  return forOp.getConstantUpperBound() - 1 -
766  (forOp.getConstantUpperBound() - forOp.getConstantLowerBound() - 1) %
767  forOp.getStepAsInt();
768  }
769  return forOp.getConstantUpperBound() - 1;
770 }
771 
772 /// Determine a constant upper bound for `expr` if one exists while exploiting
773 /// values in `operands`. Note that the upper bound is an inclusive one. `expr`
774 /// is guaranteed to be less than or equal to it.
775 static std::optional<int64_t> getUpperBound(AffineExpr expr, unsigned numDims,
776  unsigned numSymbols,
777  ArrayRef<Value> operands) {
778  // Get the constant lower or upper bounds on the operands.
779  SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
780  constLowerBounds.reserve(operands.size());
781  constUpperBounds.reserve(operands.size());
782  for (Value operand : operands) {
783  constLowerBounds.push_back(getLowerBound(operand));
784  constUpperBounds.push_back(getUpperBound(operand));
785  }
786 
787  if (auto constExpr = dyn_cast<AffineConstantExpr>(expr))
788  return constExpr.getValue();
789 
790  return getBoundForAffineExpr(expr, numDims, numSymbols, constLowerBounds,
791  constUpperBounds,
792  /*isUpper=*/true);
793 }
794 
795 /// Determine a constant lower bound for `expr` if one exists while exploiting
796 /// values in `operands`. Note that the upper bound is an inclusive one. `expr`
797 /// is guaranteed to be less than or equal to it.
798 static std::optional<int64_t> getLowerBound(AffineExpr expr, unsigned numDims,
799  unsigned numSymbols,
800  ArrayRef<Value> operands) {
801  // Get the constant lower or upper bounds on the operands.
802  SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
803  constLowerBounds.reserve(operands.size());
804  constUpperBounds.reserve(operands.size());
805  for (Value operand : operands) {
806  constLowerBounds.push_back(getLowerBound(operand));
807  constUpperBounds.push_back(getUpperBound(operand));
808  }
809 
810  std::optional<int64_t> lowerBound;
811  if (auto constExpr = dyn_cast<AffineConstantExpr>(expr)) {
812  lowerBound = constExpr.getValue();
813  } else {
814  lowerBound = getBoundForAffineExpr(expr, numDims, numSymbols,
815  constLowerBounds, constUpperBounds,
816  /*isUpper=*/false);
817  }
818  return lowerBound;
819 }
820 
821 /// Simplify `expr` while exploiting information from the values in `operands`.
822 static void simplifyExprAndOperands(AffineExpr &expr, unsigned numDims,
823  unsigned numSymbols,
824  ArrayRef<Value> operands) {
825  // We do this only for certain floordiv/mod expressions.
826  auto binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
827  if (!binExpr)
828  return;
829 
830  // Simplify the child expressions first.
831  AffineExpr lhs = binExpr.getLHS();
832  AffineExpr rhs = binExpr.getRHS();
833  simplifyExprAndOperands(lhs, numDims, numSymbols, operands);
834  simplifyExprAndOperands(rhs, numDims, numSymbols, operands);
835  expr = getAffineBinaryOpExpr(binExpr.getKind(), lhs, rhs);
836 
837  binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
838  if (!binExpr || (expr.getKind() != AffineExprKind::FloorDiv &&
839  expr.getKind() != AffineExprKind::CeilDiv &&
840  expr.getKind() != AffineExprKind::Mod)) {
841  return;
842  }
843 
844  // The `lhs` and `rhs` may be different post construction of simplified expr.
845  lhs = binExpr.getLHS();
846  rhs = binExpr.getRHS();
847  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
848  if (!rhsConst)
849  return;
850 
851  int64_t rhsConstVal = rhsConst.getValue();
852  // Undefined exprsessions aren't touched; IR can still be valid with them.
853  if (rhsConstVal <= 0)
854  return;
855 
856  // Exploit constant lower/upper bounds to simplify a floordiv or mod.
857  MLIRContext *context = expr.getContext();
858  std::optional<int64_t> lhsLbConst =
859  getLowerBound(lhs, numDims, numSymbols, operands);
860  std::optional<int64_t> lhsUbConst =
861  getUpperBound(lhs, numDims, numSymbols, operands);
862  if (lhsLbConst && lhsUbConst) {
863  int64_t lhsLbConstVal = *lhsLbConst;
864  int64_t lhsUbConstVal = *lhsUbConst;
865  // lhs floordiv c is a single value lhs is bounded in a range `c` that has
866  // the same quotient.
867  if (binExpr.getKind() == AffineExprKind::FloorDiv &&
868  divideFloorSigned(lhsLbConstVal, rhsConstVal) ==
869  divideFloorSigned(lhsUbConstVal, rhsConstVal)) {
870  expr = getAffineConstantExpr(
871  divideFloorSigned(lhsLbConstVal, rhsConstVal), context);
872  return;
873  }
874  // lhs ceildiv c is a single value if the entire range has the same ceil
875  // quotient.
876  if (binExpr.getKind() == AffineExprKind::CeilDiv &&
877  divideCeilSigned(lhsLbConstVal, rhsConstVal) ==
878  divideCeilSigned(lhsUbConstVal, rhsConstVal)) {
879  expr = getAffineConstantExpr(divideCeilSigned(lhsLbConstVal, rhsConstVal),
880  context);
881  return;
882  }
883  // lhs mod c is lhs if the entire range has quotient 0 w.r.t the rhs.
884  if (binExpr.getKind() == AffineExprKind::Mod && lhsLbConstVal >= 0 &&
885  lhsLbConstVal < rhsConstVal && lhsUbConstVal < rhsConstVal) {
886  expr = lhs;
887  return;
888  }
889  }
890 
891  // Simplify expressions of the form e = (e_1 + e_2) floordiv c or (e_1 + e_2)
892  // mod c, where e_1 is a multiple of `k` and 0 <= e_2 < k. In such cases, if
893  // `c` % `k` == 0, (e_1 + e_2) floordiv c can be simplified to e_1 floordiv c.
894  // And when k % c == 0, (e_1 + e_2) mod c can be simplified to e_2 mod c.
895  AffineExpr quotientTimesDiv, rem;
896  int64_t divisor;
897  if (isQTimesDPlusR(lhs, operands, divisor, quotientTimesDiv, rem)) {
898  if (rhsConstVal % divisor == 0 &&
899  binExpr.getKind() == AffineExprKind::FloorDiv) {
900  expr = quotientTimesDiv.floorDiv(rhsConst);
901  } else if (divisor % rhsConstVal == 0 &&
902  binExpr.getKind() == AffineExprKind::Mod) {
903  expr = rem % rhsConst;
904  }
905  return;
906  }
907 
908  // Handle the simple case when the LHS expression can be either upper
909  // bounded or is a known multiple of RHS constant.
910  // lhs floordiv c -> 0 if 0 <= lhs < c,
911  // lhs mod c -> 0 if lhs % c = 0.
912  if ((isNonNegativeBoundedBy(lhs, operands, rhsConstVal) &&
913  binExpr.getKind() == AffineExprKind::FloorDiv) ||
914  (getLargestKnownDivisor(lhs, operands) % rhsConstVal == 0 &&
915  binExpr.getKind() == AffineExprKind::Mod)) {
916  expr = getAffineConstantExpr(0, expr.getContext());
917  }
918 }
919 
920 /// Simplify the expressions in `map` while making use of lower or upper bounds
921 /// of its operands. If `isMax` is true, the map is to be treated as a max of
922 /// its result expressions, and min otherwise. Eg: min (d0, d1) -> (8, 4 * d0 +
923 /// d1) can be simplified to (8) if the operands are respectively lower bounded
924 /// by 2 and 0 (the second expression can't be lower than 8).
926  ArrayRef<Value> operands,
927  bool isMax) {
928  // Can't simplify.
929  if (operands.empty())
930  return;
931 
932  // Get the upper or lower bound on an affine.for op IV using its range.
933  // Get the constant lower or upper bounds on the operands.
934  SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
935  constLowerBounds.reserve(operands.size());
936  constUpperBounds.reserve(operands.size());
937  for (Value operand : operands) {
938  constLowerBounds.push_back(getLowerBound(operand));
939  constUpperBounds.push_back(getUpperBound(operand));
940  }
941 
942  // We will compute the lower and upper bounds on each of the expressions
943  // Then, we will check (depending on max or min) as to whether a specific
944  // bound is redundant by checking if its highest (in case of max) and its
945  // lowest (in the case of min) value is already lower than (or higher than)
946  // the lower bound (or upper bound in the case of min) of another bound.
947  SmallVector<std::optional<int64_t>, 4> lowerBounds, upperBounds;
948  lowerBounds.reserve(map.getNumResults());
949  upperBounds.reserve(map.getNumResults());
950  for (AffineExpr e : map.getResults()) {
951  if (auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
952  lowerBounds.push_back(constExpr.getValue());
953  upperBounds.push_back(constExpr.getValue());
954  } else {
955  lowerBounds.push_back(
957  constLowerBounds, constUpperBounds,
958  /*isUpper=*/false));
959  upperBounds.push_back(
961  constLowerBounds, constUpperBounds,
962  /*isUpper=*/true));
963  }
964  }
965 
966  // Collect expressions that are not redundant.
967  SmallVector<AffineExpr, 4> irredundantExprs;
968  for (auto exprEn : llvm::enumerate(map.getResults())) {
969  AffineExpr e = exprEn.value();
970  unsigned i = exprEn.index();
971  // Some expressions can be turned into constants.
972  if (lowerBounds[i] && upperBounds[i] && *lowerBounds[i] == *upperBounds[i])
973  e = getAffineConstantExpr(*lowerBounds[i], e.getContext());
974 
975  // Check if the expression is redundant.
976  if (isMax) {
977  if (!upperBounds[i]) {
978  irredundantExprs.push_back(e);
979  continue;
980  }
981  // If there exists another expression such that its lower bound is greater
982  // than this expression's upper bound, it's redundant.
983  if (!llvm::any_of(llvm::enumerate(lowerBounds), [&](const auto &en) {
984  auto otherLowerBound = en.value();
985  unsigned pos = en.index();
986  if (pos == i || !otherLowerBound)
987  return false;
988  if (*otherLowerBound > *upperBounds[i])
989  return true;
990  if (*otherLowerBound < *upperBounds[i])
991  return false;
992  // Equality case. When both expressions are considered redundant, we
993  // don't want to get both of them. We keep the one that appears
994  // first.
995  if (upperBounds[pos] && lowerBounds[i] &&
996  lowerBounds[i] == upperBounds[i] &&
997  otherLowerBound == *upperBounds[pos] && i < pos)
998  return false;
999  return true;
1000  }))
1001  irredundantExprs.push_back(e);
1002  } else {
1003  if (!lowerBounds[i]) {
1004  irredundantExprs.push_back(e);
1005  continue;
1006  }
1007  // Likewise for the `min` case. Use the complement of the condition above.
1008  if (!llvm::any_of(llvm::enumerate(upperBounds), [&](const auto &en) {
1009  auto otherUpperBound = en.value();
1010  unsigned pos = en.index();
1011  if (pos == i || !otherUpperBound)
1012  return false;
1013  if (*otherUpperBound < *lowerBounds[i])
1014  return true;
1015  if (*otherUpperBound > *lowerBounds[i])
1016  return false;
1017  if (lowerBounds[pos] && upperBounds[i] &&
1018  lowerBounds[i] == upperBounds[i] &&
1019  otherUpperBound == lowerBounds[pos] && i < pos)
1020  return false;
1021  return true;
1022  }))
1023  irredundantExprs.push_back(e);
1024  }
1025  }
1026 
1027  // Create the map without the redundant expressions.
1028  map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), irredundantExprs,
1029  map.getContext());
1030 }
1031 
1032 /// Simplify the map while exploiting information on the values in `operands`.
1033 // Use "unused attribute" marker to silence warning stemming from the inability
1034 // to see through the template expansion.
1035 static void LLVM_ATTRIBUTE_UNUSED
1037  assert(map.getNumInputs() == operands.size() && "invalid operands for map");
1038  SmallVector<AffineExpr> newResults;
1039  newResults.reserve(map.getNumResults());
1040  for (AffineExpr expr : map.getResults()) {
1042  operands);
1043  newResults.push_back(expr);
1044  }
1045  map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), newResults,
1046  map.getContext());
1047 }
1048 
1049 /// Assuming `dimOrSym` is a quantity in the apply op map `map` and defined by
1050 /// `minOp = affine_min(x_1, ..., x_n)`. This function checks that:
1051 /// `0 < affine_min(x_1, ..., x_n)` and proceeds with replacing the patterns:
1052 /// ```
1053 /// dimOrSym.ceildiv(x_k)
1054 /// (dimOrSym + x_k - 1).floordiv(x_k)
1055 /// ```
1056 /// by `1` for all `k` in `1, ..., n`. This is possible because `x / x_k <= 1`.
1057 ///
1058 ///
1059 /// Warning: ValueBoundsConstraintSet::computeConstantBound is needed to check
1060 /// `minOp` is positive.
1061 static LogicalResult replaceAffineMinBoundingBoxExpression(AffineMinOp minOp,
1062  AffineExpr dimOrSym,
1063  AffineMap *map,
1064  ValueRange dims,
1065  ValueRange syms) {
1066  LDBG() << "replaceAffineMinBoundingBoxExpression: `" << minOp << "`";
1067  AffineMap affineMinMap = minOp.getAffineMap();
1068 
1069  // Check the value is positive.
1070  for (unsigned i = 0, e = affineMinMap.getNumResults(); i < e; ++i) {
1071  // Compare each expression in the minimum against 0.
1073  getAsIndexOpFoldResult(minOp.getContext(), 0),
1074  ValueBoundsConstraintSet::ComparisonOperator::LT,
1076  minOp.getOperands())))
1077  return failure();
1078  }
1079 
1080  /// Convert affine symbols and dimensions in minOp to symbols or dimensions in
1081  /// the apply op affine map.
1082  DenseMap<AffineExpr, AffineExpr> dimSymConversionTable;
1083  SmallVector<unsigned> unmappedDims, unmappedSyms;
1084  for (auto [i, dim] : llvm::enumerate(minOp.getDimOperands())) {
1085  auto it = llvm::find(dims, dim);
1086  if (it == dims.end()) {
1087  unmappedDims.push_back(i);
1088  continue;
1089  }
1090  dimSymConversionTable[getAffineDimExpr(i, minOp.getContext())] =
1091  getAffineDimExpr(it.getIndex(), minOp.getContext());
1092  }
1093  for (auto [i, sym] : llvm::enumerate(minOp.getSymbolOperands())) {
1094  auto it = llvm::find(syms, sym);
1095  if (it == syms.end()) {
1096  unmappedSyms.push_back(i);
1097  continue;
1098  }
1099  dimSymConversionTable[getAffineSymbolExpr(i, minOp.getContext())] =
1100  getAffineSymbolExpr(it.getIndex(), minOp.getContext());
1101  }
1102 
1103  // Create the replacement map.
1105  AffineExpr c1 = getAffineConstantExpr(1, minOp.getContext());
1106  for (AffineExpr expr : affineMinMap.getResults()) {
1107  // If we cannot express the result in terms of the apply map symbols and
1108  // sims then continue.
1109  if (llvm::any_of(unmappedDims,
1110  [&](unsigned i) { return expr.isFunctionOfDim(i); }) ||
1111  llvm::any_of(unmappedSyms,
1112  [&](unsigned i) { return expr.isFunctionOfSymbol(i); }))
1113  continue;
1114 
1115  AffineExpr convertedExpr = expr.replace(dimSymConversionTable);
1116 
1117  // dimOrSym.ceilDiv(expr) -> 1
1118  repl[dimOrSym.ceilDiv(convertedExpr)] = c1;
1119  // (dimOrSym + expr - 1).floorDiv(expr) -> 1
1120  repl[(dimOrSym + convertedExpr - 1).floorDiv(convertedExpr)] = c1;
1121  }
1122  AffineMap initialMap = *map;
1123  *map = initialMap.replace(repl, initialMap.getNumDims(),
1124  initialMap.getNumSymbols());
1125  return success(*map != initialMap);
1126 }
1127 
1128 /// Replace all occurrences of AffineExpr at position `pos` in `map` by the
1129 /// defining AffineApplyOp expression and operands.
1130 /// When `dimOrSymbolPosition < dims.size()`, AffineDimExpr@[pos] is replaced.
1131 /// When `dimOrSymbolPosition >= dims.size()`,
1132 /// AffineSymbolExpr@[pos - dims.size()] is replaced.
1133 /// Mutate `map`,`dims` and `syms` in place as follows:
1134 /// 1. `dims` and `syms` are only appended to.
1135 /// 2. `map` dim and symbols are gradually shifted to higher positions.
1136 /// 3. Old `dim` and `sym` entries are replaced by nullptr
1137 /// This avoids the need for any bookkeeping.
1138 /// If `replaceAffineMin` is set to true, additionally triggers more expensive
1139 /// replacements involving affine_min operations.
1140 static LogicalResult replaceDimOrSym(AffineMap *map,
1141  unsigned dimOrSymbolPosition,
1142  SmallVectorImpl<Value> &dims,
1143  SmallVectorImpl<Value> &syms,
1144  bool replaceAffineMin) {
1145  MLIRContext *ctx = map->getContext();
1146  bool isDimReplacement = (dimOrSymbolPosition < dims.size());
1147  unsigned pos = isDimReplacement ? dimOrSymbolPosition
1148  : dimOrSymbolPosition - dims.size();
1149  Value &v = isDimReplacement ? dims[pos] : syms[pos];
1150  if (!v)
1151  return failure();
1152 
1153  if (auto minOp = v.getDefiningOp<AffineMinOp>(); minOp && replaceAffineMin) {
1154  AffineExpr dimOrSym = isDimReplacement ? getAffineDimExpr(pos, ctx)
1155  : getAffineSymbolExpr(pos, ctx);
1156  return replaceAffineMinBoundingBoxExpression(minOp, dimOrSym, map, dims,
1157  syms);
1158  }
1159 
1160  auto affineApply = v.getDefiningOp<AffineApplyOp>();
1161  if (!affineApply)
1162  return failure();
1163 
1164  // At this point we will perform a replacement of `v`, set the entry in `dim`
1165  // or `sym` to nullptr immediately.
1166  v = nullptr;
1167 
1168  // Compute the map, dims and symbols coming from the AffineApplyOp.
1169  AffineMap composeMap = affineApply.getAffineMap();
1170  assert(composeMap.getNumResults() == 1 && "affine.apply with >1 results");
1171  SmallVector<Value> composeOperands(affineApply.getMapOperands().begin(),
1172  affineApply.getMapOperands().end());
1173  // Canonicalize the map to promote dims to symbols when possible. This is to
1174  // avoid generating invalid maps.
1175  canonicalizeMapAndOperands(&composeMap, &composeOperands);
1176  AffineExpr replacementExpr =
1177  composeMap.shiftDims(dims.size()).shiftSymbols(syms.size()).getResult(0);
1178  ValueRange composeDims =
1179  ArrayRef<Value>(composeOperands).take_front(composeMap.getNumDims());
1180  ValueRange composeSyms =
1181  ArrayRef<Value>(composeOperands).take_back(composeMap.getNumSymbols());
1182  AffineExpr toReplace = isDimReplacement ? getAffineDimExpr(pos, ctx)
1183  : getAffineSymbolExpr(pos, ctx);
1184 
1185  // Append the dims and symbols where relevant and perform the replacement.
1186  dims.append(composeDims.begin(), composeDims.end());
1187  syms.append(composeSyms.begin(), composeSyms.end());
1188  *map = map->replace(toReplace, replacementExpr, dims.size(), syms.size());
1189 
1190  return success();
1191 }
1192 
1193 /// Iterate over `operands` and fold away all those produced by an AffineApplyOp
1194 /// iteratively. Perform canonicalization of map and operands as well as
1195 /// AffineMap simplification. `map` and `operands` are mutated in place.
1197  SmallVectorImpl<Value> *operands,
1198  bool composeAffineMin = false) {
1199  if (map->getNumResults() == 0) {
1200  canonicalizeMapAndOperands(map, operands);
1201  *map = simplifyAffineMap(*map);
1202  return;
1203  }
1204 
1205  MLIRContext *ctx = map->getContext();
1206  SmallVector<Value, 4> dims(operands->begin(),
1207  operands->begin() + map->getNumDims());
1208  SmallVector<Value, 4> syms(operands->begin() + map->getNumDims(),
1209  operands->end());
1210 
1211  // Iterate over dims and symbols coming from AffineApplyOp and replace until
1212  // exhaustion. This iteratively mutates `map`, `dims` and `syms`. Both `dims`
1213  // and `syms` can only increase by construction.
1214  // The implementation uses a `while` loop to support the case of symbols
1215  // that may be constructed from dims ;this may be overkill.
1216  while (true) {
1217  bool changed = false;
1218  for (unsigned pos = 0; pos != dims.size() + syms.size(); ++pos)
1219  if ((changed |=
1220  succeeded(replaceDimOrSym(map, pos, dims, syms, composeAffineMin))))
1221  break;
1222  if (!changed)
1223  break;
1224  }
1225 
1226  // Clear operands so we can fill them anew.
1227  operands->clear();
1228 
1229  // At this point we may have introduced null operands, prune them out before
1230  // canonicalizing map and operands.
1231  unsigned nDims = 0, nSyms = 0;
1232  SmallVector<AffineExpr, 4> dimReplacements, symReplacements;
1233  dimReplacements.reserve(dims.size());
1234  symReplacements.reserve(syms.size());
1235  for (auto *container : {&dims, &syms}) {
1236  bool isDim = (container == &dims);
1237  auto &repls = isDim ? dimReplacements : symReplacements;
1238  for (const auto &en : llvm::enumerate(*container)) {
1239  Value v = en.value();
1240  if (!v) {
1241  assert(isDim ? !map->isFunctionOfDim(en.index())
1242  : !map->isFunctionOfSymbol(en.index()) &&
1243  "map is function of unexpected expr@pos");
1244  repls.push_back(getAffineConstantExpr(0, ctx));
1245  continue;
1246  }
1247  repls.push_back(isDim ? getAffineDimExpr(nDims++, ctx)
1248  : getAffineSymbolExpr(nSyms++, ctx));
1249  operands->push_back(v);
1250  }
1251  }
1252  *map = map->replaceDimsAndSymbols(dimReplacements, symReplacements, nDims,
1253  nSyms);
1254 
1255  // Canonicalize and simplify before returning.
1256  canonicalizeMapAndOperands(map, operands);
1257  *map = simplifyAffineMap(*map);
1258 }
1259 
1261  AffineMap *map, SmallVectorImpl<Value> *operands, bool composeAffineMin) {
1262  while (llvm::any_of(*operands, [](Value v) {
1263  return isa_and_nonnull<AffineApplyOp>(v.getDefiningOp());
1264  })) {
1265  composeAffineMapAndOperands(map, operands, composeAffineMin);
1266  }
1267  // Additional trailing step for AffineMinOps in case no chains of AffineApply.
1268  if (composeAffineMin && llvm::any_of(*operands, [](Value v) {
1269  return isa_and_nonnull<AffineMinOp>(v.getDefiningOp());
1270  })) {
1271  composeAffineMapAndOperands(map, operands, composeAffineMin);
1272  }
1273 }
1274 
1275 AffineApplyOp
1277  ArrayRef<OpFoldResult> operands,
1278  bool composeAffineMin) {
1279  SmallVector<Value> valueOperands;
1280  map = foldAttributesIntoMap(b, map, operands, valueOperands);
1281  composeAffineMapAndOperands(&map, &valueOperands, composeAffineMin);
1282  assert(map);
1283  return AffineApplyOp::create(b, loc, map, valueOperands);
1284 }
1285 
1286 AffineApplyOp
1288  ArrayRef<OpFoldResult> operands,
1289  bool composeAffineMin) {
1290  return makeComposedAffineApply(
1291  b, loc,
1293  .front(),
1294  operands, composeAffineMin);
1295 }
1296 
1297 /// Composes the given affine map with the given list of operands, pulling in
1298 /// the maps from any affine.apply operations that supply the operands.
1300  SmallVectorImpl<Value> &operands,
1301  bool composeAffineMin = false) {
1302  // Compose and canonicalize each expression in the map individually because
1303  // composition only applies to single-result maps, collecting potentially
1304  // duplicate operands in a single list with shifted dimensions and symbols.
1305  SmallVector<Value> dims, symbols;
1307  for (unsigned i : llvm::seq<unsigned>(0, map.getNumResults())) {
1308  SmallVector<Value> submapOperands(operands.begin(), operands.end());
1309  AffineMap submap = map.getSubMap({i});
1310  fullyComposeAffineMapAndOperands(&submap, &submapOperands,
1311  composeAffineMin);
1312  canonicalizeMapAndOperands(&submap, &submapOperands);
1313  unsigned numNewDims = submap.getNumDims();
1314  submap = submap.shiftDims(dims.size()).shiftSymbols(symbols.size());
1315  llvm::append_range(dims,
1316  ArrayRef<Value>(submapOperands).take_front(numNewDims));
1317  llvm::append_range(symbols,
1318  ArrayRef<Value>(submapOperands).drop_front(numNewDims));
1319  exprs.push_back(submap.getResult(0));
1320  }
1321 
1322  // Canonicalize the map created from composed expressions to deduplicate the
1323  // dimension and symbol operands.
1324  operands = llvm::to_vector(llvm::concat<Value>(dims, symbols));
1325  map = AffineMap::get(dims.size(), symbols.size(), exprs, map.getContext());
1326  canonicalizeMapAndOperands(&map, &operands);
1327 }
1328 
1330  OpBuilder &b, Location loc, AffineMap map, ArrayRef<OpFoldResult> operands,
1331  bool composeAffineMin) {
1332  assert(map.getNumResults() == 1 && "building affine.apply with !=1 result");
1333 
1334  // Create new builder without a listener, so that no notification is
1335  // triggered if the op is folded.
1336  // TODO: OpBuilder::createOrFold should return OpFoldResults, then this
1337  // workaround is no longer needed.
1338  OpBuilder newBuilder(b.getContext());
1340 
1341  // Create op.
1342  AffineApplyOp applyOp =
1343  makeComposedAffineApply(newBuilder, loc, map, operands, composeAffineMin);
1344 
1345  // Get constant operands.
1346  SmallVector<Attribute> constOperands(applyOp->getNumOperands());
1347  for (unsigned i = 0, e = constOperands.size(); i != e; ++i)
1348  matchPattern(applyOp->getOperand(i), m_Constant(&constOperands[i]));
1349 
1350  // Try to fold the operation.
1351  SmallVector<OpFoldResult> foldResults;
1352  if (failed(applyOp->fold(constOperands, foldResults)) ||
1353  foldResults.empty()) {
1354  if (OpBuilder::Listener *listener = b.getListener())
1355  listener->notifyOperationInserted(applyOp, /*previous=*/{});
1356  return applyOp.getResult();
1357  }
1358 
1359  applyOp->erase();
1360  return llvm::getSingleElement(foldResults);
1361 }
1362 
1364  OpBuilder &b, Location loc, AffineExpr expr,
1365  ArrayRef<OpFoldResult> operands, bool composeAffineMin) {
1367  b, loc,
1369  .front(),
1370  operands, composeAffineMin);
1371 }
1372 
1375  OpBuilder &b, Location loc, AffineMap map, ArrayRef<OpFoldResult> operands,
1376  bool composeAffineMin) {
1377  return llvm::map_to_vector(
1378  llvm::seq<unsigned>(0, map.getNumResults()), [&](unsigned i) {
1379  return makeComposedFoldedAffineApply(b, loc, map.getSubMap({i}),
1380  operands, composeAffineMin);
1381  });
1382 }
1383 
1384 template <typename OpTy>
1386  ArrayRef<OpFoldResult> operands) {
1387  SmallVector<Value> valueOperands;
1388  map = foldAttributesIntoMap(b, map, operands, valueOperands);
1389  composeMultiResultAffineMap(map, valueOperands);
1390  return OpTy::create(b, loc, b.getIndexType(), map, valueOperands);
1391 }
1392 
1393 AffineMinOp
1395  ArrayRef<OpFoldResult> operands) {
1396  return makeComposedMinMax<AffineMinOp>(b, loc, map, operands);
1397 }
1398 
1399 template <typename OpTy>
1401  AffineMap map,
1402  ArrayRef<OpFoldResult> operands) {
1403  // Create new builder without a listener, so that no notification is
1404  // triggered if the op is folded.
1405  // TODO: OpBuilder::createOrFold should return OpFoldResults, then this
1406  // workaround is no longer needed.
1407  OpBuilder newBuilder(b.getContext());
1409 
1410  // Create op.
1411  auto minMaxOp = makeComposedMinMax<OpTy>(newBuilder, loc, map, operands);
1412 
1413  // Get constant operands.
1414  SmallVector<Attribute> constOperands(minMaxOp->getNumOperands());
1415  for (unsigned i = 0, e = constOperands.size(); i != e; ++i)
1416  matchPattern(minMaxOp->getOperand(i), m_Constant(&constOperands[i]));
1417 
1418  // Try to fold the operation.
1419  SmallVector<OpFoldResult> foldResults;
1420  if (failed(minMaxOp->fold(constOperands, foldResults)) ||
1421  foldResults.empty()) {
1422  if (OpBuilder::Listener *listener = b.getListener())
1423  listener->notifyOperationInserted(minMaxOp, /*previous=*/{});
1424  return minMaxOp.getResult();
1425  }
1426 
1427  minMaxOp->erase();
1428  return llvm::getSingleElement(foldResults);
1429 }
1430 
1433  AffineMap map,
1434  ArrayRef<OpFoldResult> operands) {
1435  return makeComposedFoldedMinMax<AffineMinOp>(b, loc, map, operands);
1436 }
1437 
1440  AffineMap map,
1441  ArrayRef<OpFoldResult> operands) {
1442  return makeComposedFoldedMinMax<AffineMaxOp>(b, loc, map, operands);
1443 }
1444 
1445 // A symbol may appear as a dim in affine.apply operations. This function
1446 // canonicalizes dims that are valid symbols into actual symbols.
1447 template <class MapOrSet>
1448 static void canonicalizePromotedSymbols(MapOrSet *mapOrSet,
1449  SmallVectorImpl<Value> *operands) {
1450  if (!mapOrSet || operands->empty())
1451  return;
1452 
1453  assert(mapOrSet->getNumInputs() == operands->size() &&
1454  "map/set inputs must match number of operands");
1455 
1456  auto *context = mapOrSet->getContext();
1457  SmallVector<Value, 8> resultOperands;
1458  resultOperands.reserve(operands->size());
1459  SmallVector<Value, 8> remappedSymbols;
1460  remappedSymbols.reserve(operands->size());
1461  unsigned nextDim = 0;
1462  unsigned nextSym = 0;
1463  unsigned oldNumSyms = mapOrSet->getNumSymbols();
1464  SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
1465  for (unsigned i = 0, e = mapOrSet->getNumInputs(); i != e; ++i) {
1466  if (i < mapOrSet->getNumDims()) {
1467  if (isValidSymbol((*operands)[i])) {
1468  // This is a valid symbol that appears as a dim, canonicalize it.
1469  dimRemapping[i] = getAffineSymbolExpr(oldNumSyms + nextSym++, context);
1470  remappedSymbols.push_back((*operands)[i]);
1471  } else {
1472  dimRemapping[i] = getAffineDimExpr(nextDim++, context);
1473  resultOperands.push_back((*operands)[i]);
1474  }
1475  } else {
1476  resultOperands.push_back((*operands)[i]);
1477  }
1478  }
1479 
1480  resultOperands.append(remappedSymbols.begin(), remappedSymbols.end());
1481  *operands = resultOperands;
1482  *mapOrSet = mapOrSet->replaceDimsAndSymbols(
1483  dimRemapping, /*symReplacements=*/{}, nextDim, oldNumSyms + nextSym);
1484 
1485  assert(mapOrSet->getNumInputs() == operands->size() &&
1486  "map/set inputs must match number of operands");
1487 }
1488 
1489 /// A valid affine dimension may appear as a symbol in affine.apply operations.
1490 /// Given an application of `operands` to an affine map or integer set
1491 /// `mapOrSet`, this function canonicalizes symbols of `mapOrSet` that are valid
1492 /// dims, but not valid symbols into actual dims. Without such a legalization,
1493 /// the affine.apply will be invalid. This method is the exact inverse of
1494 /// canonicalizePromotedSymbols.
1495 template <class MapOrSet>
1496 static void legalizeDemotedDims(MapOrSet &mapOrSet,
1497  SmallVectorImpl<Value> &operands) {
1498  if (!mapOrSet || operands.empty())
1499  return;
1500 
1501  unsigned numOperands = operands.size();
1502 
1503  assert(mapOrSet.getNumInputs() == numOperands &&
1504  "map/set inputs must match number of operands");
1505 
1506  auto *context = mapOrSet.getContext();
1507  SmallVector<Value, 8> resultOperands;
1508  resultOperands.reserve(numOperands);
1509  SmallVector<Value, 8> remappedDims;
1510  remappedDims.reserve(numOperands);
1511  SmallVector<Value, 8> symOperands;
1512  symOperands.reserve(mapOrSet.getNumSymbols());
1513  unsigned nextSym = 0;
1514  unsigned nextDim = 0;
1515  unsigned oldNumDims = mapOrSet.getNumDims();
1516  SmallVector<AffineExpr, 8> symRemapping(mapOrSet.getNumSymbols());
1517  resultOperands.assign(operands.begin(), operands.begin() + oldNumDims);
1518  for (unsigned i = oldNumDims, e = mapOrSet.getNumInputs(); i != e; ++i) {
1519  if (operands[i] && isValidDim(operands[i]) && !isValidSymbol(operands[i])) {
1520  // This is a valid dim that appears as a symbol, legalize it.
1521  symRemapping[i - oldNumDims] =
1522  getAffineDimExpr(oldNumDims + nextDim++, context);
1523  remappedDims.push_back(operands[i]);
1524  } else {
1525  symRemapping[i - oldNumDims] = getAffineSymbolExpr(nextSym++, context);
1526  symOperands.push_back(operands[i]);
1527  }
1528  }
1529 
1530  append_range(resultOperands, remappedDims);
1531  append_range(resultOperands, symOperands);
1532  operands = resultOperands;
1533  mapOrSet = mapOrSet.replaceDimsAndSymbols(
1534  /*dimReplacements=*/{}, symRemapping, oldNumDims + nextDim, nextSym);
1535 
1536  assert(mapOrSet.getNumInputs() == operands.size() &&
1537  "map/set inputs must match number of operands");
1538 }
1539 
1540 // Works for either an affine map or an integer set.
1541 template <class MapOrSet>
1542 static void canonicalizeMapOrSetAndOperands(MapOrSet *mapOrSet,
1543  SmallVectorImpl<Value> *operands) {
1544  static_assert(llvm::is_one_of<MapOrSet, AffineMap, IntegerSet>::value,
1545  "Argument must be either of AffineMap or IntegerSet type");
1546 
1547  if (!mapOrSet || operands->empty())
1548  return;
1549 
1550  assert(mapOrSet->getNumInputs() == operands->size() &&
1551  "map/set inputs must match number of operands");
1552 
1553  canonicalizePromotedSymbols<MapOrSet>(mapOrSet, operands);
1554  legalizeDemotedDims<MapOrSet>(*mapOrSet, *operands);
1555 
1556  // Check to see what dims are used.
1557  llvm::SmallBitVector usedDims(mapOrSet->getNumDims());
1558  llvm::SmallBitVector usedSyms(mapOrSet->getNumSymbols());
1559  mapOrSet->walkExprs([&](AffineExpr expr) {
1560  if (auto dimExpr = dyn_cast<AffineDimExpr>(expr))
1561  usedDims[dimExpr.getPosition()] = true;
1562  else if (auto symExpr = dyn_cast<AffineSymbolExpr>(expr))
1563  usedSyms[symExpr.getPosition()] = true;
1564  });
1565 
1566  auto *context = mapOrSet->getContext();
1567 
1568  SmallVector<Value, 8> resultOperands;
1569  resultOperands.reserve(operands->size());
1570 
1571  llvm::SmallDenseMap<Value, AffineExpr, 8> seenDims;
1572  SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
1573  unsigned nextDim = 0;
1574  for (unsigned i = 0, e = mapOrSet->getNumDims(); i != e; ++i) {
1575  if (usedDims[i]) {
1576  // Remap dim positions for duplicate operands.
1577  auto it = seenDims.find((*operands)[i]);
1578  if (it == seenDims.end()) {
1579  dimRemapping[i] = getAffineDimExpr(nextDim++, context);
1580  resultOperands.push_back((*operands)[i]);
1581  seenDims.insert(std::make_pair((*operands)[i], dimRemapping[i]));
1582  } else {
1583  dimRemapping[i] = it->second;
1584  }
1585  }
1586  }
1587  llvm::SmallDenseMap<Value, AffineExpr, 8> seenSymbols;
1588  SmallVector<AffineExpr, 8> symRemapping(mapOrSet->getNumSymbols());
1589  unsigned nextSym = 0;
1590  for (unsigned i = 0, e = mapOrSet->getNumSymbols(); i != e; ++i) {
1591  if (!usedSyms[i])
1592  continue;
1593  // Handle constant operands (only needed for symbolic operands since
1594  // constant operands in dimensional positions would have already been
1595  // promoted to symbolic positions above).
1596  IntegerAttr operandCst;
1597  if (matchPattern((*operands)[i + mapOrSet->getNumDims()],
1598  m_Constant(&operandCst))) {
1599  symRemapping[i] =
1600  getAffineConstantExpr(operandCst.getValue().getSExtValue(), context);
1601  continue;
1602  }
1603  // Remap symbol positions for duplicate operands.
1604  auto it = seenSymbols.find((*operands)[i + mapOrSet->getNumDims()]);
1605  if (it == seenSymbols.end()) {
1606  symRemapping[i] = getAffineSymbolExpr(nextSym++, context);
1607  resultOperands.push_back((*operands)[i + mapOrSet->getNumDims()]);
1608  seenSymbols.insert(std::make_pair((*operands)[i + mapOrSet->getNumDims()],
1609  symRemapping[i]));
1610  } else {
1611  symRemapping[i] = it->second;
1612  }
1613  }
1614  *mapOrSet = mapOrSet->replaceDimsAndSymbols(dimRemapping, symRemapping,
1615  nextDim, nextSym);
1616  *operands = resultOperands;
1617 }
1618 
1620  AffineMap *map, SmallVectorImpl<Value> *operands) {
1621  canonicalizeMapOrSetAndOperands<AffineMap>(map, operands);
1622 }
1623 
1625  IntegerSet *set, SmallVectorImpl<Value> *operands) {
1626  canonicalizeMapOrSetAndOperands<IntegerSet>(set, operands);
1627 }
1628 
1629 namespace {
1630 /// Simplify AffineApply, AffineLoad, and AffineStore operations by composing
1631 /// maps that supply results into them.
1632 ///
1633 template <typename AffineOpTy>
1634 struct SimplifyAffineOp : public OpRewritePattern<AffineOpTy> {
1636 
1637  /// Replace the affine op with another instance of it with the supplied
1638  /// map and mapOperands.
1639  void replaceAffineOp(PatternRewriter &rewriter, AffineOpTy affineOp,
1640  AffineMap map, ArrayRef<Value> mapOperands) const;
1641 
1642  LogicalResult matchAndRewrite(AffineOpTy affineOp,
1643  PatternRewriter &rewriter) const override {
1644  static_assert(
1645  llvm::is_one_of<AffineOpTy, AffineLoadOp, AffinePrefetchOp,
1646  AffineStoreOp, AffineApplyOp, AffineMinOp, AffineMaxOp,
1647  AffineVectorStoreOp, AffineVectorLoadOp>::value,
1648  "affine load/store/vectorstore/vectorload/apply/prefetch/min/max op "
1649  "expected");
1650  auto map = affineOp.getAffineMap();
1651  AffineMap oldMap = map;
1652  auto oldOperands = affineOp.getMapOperands();
1653  SmallVector<Value, 8> resultOperands(oldOperands);
1654  composeAffineMapAndOperands(&map, &resultOperands);
1655  canonicalizeMapAndOperands(&map, &resultOperands);
1656  simplifyMapWithOperands(map, resultOperands);
1657  if (map == oldMap && std::equal(oldOperands.begin(), oldOperands.end(),
1658  resultOperands.begin()))
1659  return failure();
1660 
1661  replaceAffineOp(rewriter, affineOp, map, resultOperands);
1662  return success();
1663  }
1664 };
1665 
1666 // Specialize the template to account for the different build signatures for
1667 // affine load, store, and apply ops.
1668 template <>
1669 void SimplifyAffineOp<AffineLoadOp>::replaceAffineOp(
1670  PatternRewriter &rewriter, AffineLoadOp load, AffineMap map,
1671  ArrayRef<Value> mapOperands) const {
1672  rewriter.replaceOpWithNewOp<AffineLoadOp>(load, load.getMemRef(), map,
1673  mapOperands);
1674 }
1675 template <>
1676 void SimplifyAffineOp<AffinePrefetchOp>::replaceAffineOp(
1677  PatternRewriter &rewriter, AffinePrefetchOp prefetch, AffineMap map,
1678  ArrayRef<Value> mapOperands) const {
1679  rewriter.replaceOpWithNewOp<AffinePrefetchOp>(
1680  prefetch, prefetch.getMemref(), map, mapOperands, prefetch.getIsWrite(),
1681  prefetch.getLocalityHint(), prefetch.getIsDataCache());
1682 }
1683 template <>
1684 void SimplifyAffineOp<AffineStoreOp>::replaceAffineOp(
1685  PatternRewriter &rewriter, AffineStoreOp store, AffineMap map,
1686  ArrayRef<Value> mapOperands) const {
1687  rewriter.replaceOpWithNewOp<AffineStoreOp>(
1688  store, store.getValueToStore(), store.getMemRef(), map, mapOperands);
1689 }
1690 template <>
1691 void SimplifyAffineOp<AffineVectorLoadOp>::replaceAffineOp(
1692  PatternRewriter &rewriter, AffineVectorLoadOp vectorload, AffineMap map,
1693  ArrayRef<Value> mapOperands) const {
1694  rewriter.replaceOpWithNewOp<AffineVectorLoadOp>(
1695  vectorload, vectorload.getVectorType(), vectorload.getMemRef(), map,
1696  mapOperands);
1697 }
1698 template <>
1699 void SimplifyAffineOp<AffineVectorStoreOp>::replaceAffineOp(
1700  PatternRewriter &rewriter, AffineVectorStoreOp vectorstore, AffineMap map,
1701  ArrayRef<Value> mapOperands) const {
1702  rewriter.replaceOpWithNewOp<AffineVectorStoreOp>(
1703  vectorstore, vectorstore.getValueToStore(), vectorstore.getMemRef(), map,
1704  mapOperands);
1705 }
1706 
1707 // Generic version for ops that don't have extra operands.
1708 template <typename AffineOpTy>
1709 void SimplifyAffineOp<AffineOpTy>::replaceAffineOp(
1710  PatternRewriter &rewriter, AffineOpTy op, AffineMap map,
1711  ArrayRef<Value> mapOperands) const {
1712  rewriter.replaceOpWithNewOp<AffineOpTy>(op, map, mapOperands);
1713 }
1714 } // namespace
1715 
1716 void AffineApplyOp::getCanonicalizationPatterns(RewritePatternSet &results,
1717  MLIRContext *context) {
1718  results.add<SimplifyAffineOp<AffineApplyOp>>(context);
1719 }
1720 
1721 //===----------------------------------------------------------------------===//
1722 // AffineDmaStartOp
1723 //===----------------------------------------------------------------------===//
1724 
1725 // TODO: Check that map operands are loop IVs or symbols.
1726 void AffineDmaStartOp::build(OpBuilder &builder, OperationState &result,
1727  Value srcMemRef, AffineMap srcMap,
1728  ValueRange srcIndices, Value destMemRef,
1729  AffineMap dstMap, ValueRange destIndices,
1730  Value tagMemRef, AffineMap tagMap,
1731  ValueRange tagIndices, Value numElements,
1732  Value stride, Value elementsPerStride) {
1733  result.addOperands(srcMemRef);
1734  result.addAttribute(getSrcMapAttrStrName(), AffineMapAttr::get(srcMap));
1735  result.addOperands(srcIndices);
1736  result.addOperands(destMemRef);
1737  result.addAttribute(getDstMapAttrStrName(), AffineMapAttr::get(dstMap));
1738  result.addOperands(destIndices);
1739  result.addOperands(tagMemRef);
1740  result.addAttribute(getTagMapAttrStrName(), AffineMapAttr::get(tagMap));
1741  result.addOperands(tagIndices);
1742  result.addOperands(numElements);
1743  if (stride) {
1744  result.addOperands({stride, elementsPerStride});
1745  }
1746 }
1747 
1748 AffineDmaStartOp AffineDmaStartOp::create(
1749  OpBuilder &builder, Location location, Value srcMemRef, AffineMap srcMap,
1750  ValueRange srcIndices, Value destMemRef, AffineMap dstMap,
1751  ValueRange destIndices, Value tagMemRef, AffineMap tagMap,
1752  ValueRange tagIndices, Value numElements, Value stride,
1753  Value elementsPerStride) {
1754  mlir::OperationState state(location, getOperationName());
1755  build(builder, state, srcMemRef, srcMap, srcIndices, destMemRef, dstMap,
1756  destIndices, tagMemRef, tagMap, tagIndices, numElements, stride,
1757  elementsPerStride);
1758  auto result = dyn_cast<AffineDmaStartOp>(builder.create(state));
1759  assert(result && "builder didn't return the right type");
1760  return result;
1761 }
1762 
1763 AffineDmaStartOp AffineDmaStartOp::create(
1764  ImplicitLocOpBuilder &builder, Value srcMemRef, AffineMap srcMap,
1765  ValueRange srcIndices, Value destMemRef, AffineMap dstMap,
1766  ValueRange destIndices, Value tagMemRef, AffineMap tagMap,
1767  ValueRange tagIndices, Value numElements, Value stride,
1768  Value elementsPerStride) {
1769  return create(builder, builder.getLoc(), srcMemRef, srcMap, srcIndices,
1770  destMemRef, dstMap, destIndices, tagMemRef, tagMap, tagIndices,
1771  numElements, stride, elementsPerStride);
1772 }
1773 
1775  p << " " << getSrcMemRef() << '[';
1776  p.printAffineMapOfSSAIds(getSrcMapAttr(), getSrcIndices());
1777  p << "], " << getDstMemRef() << '[';
1778  p.printAffineMapOfSSAIds(getDstMapAttr(), getDstIndices());
1779  p << "], " << getTagMemRef() << '[';
1780  p.printAffineMapOfSSAIds(getTagMapAttr(), getTagIndices());
1781  p << "], " << getNumElements();
1782  if (isStrided()) {
1783  p << ", " << getStride();
1784  p << ", " << getNumElementsPerStride();
1785  }
1786  p << " : " << getSrcMemRefType() << ", " << getDstMemRefType() << ", "
1787  << getTagMemRefType();
1788 }
1789 
1790 // Parse AffineDmaStartOp.
1791 // Ex:
1792 // affine.dma_start %src[%i, %j], %dst[%k, %l], %tag[%index], %size,
1793 // %stride, %num_elt_per_stride
1794 // : memref<3076 x f32, 0>, memref<1024 x f32, 2>, memref<1 x i32>
1795 //
1797  OperationState &result) {
1798  OpAsmParser::UnresolvedOperand srcMemRefInfo;
1799  AffineMapAttr srcMapAttr;
1801  OpAsmParser::UnresolvedOperand dstMemRefInfo;
1802  AffineMapAttr dstMapAttr;
1804  OpAsmParser::UnresolvedOperand tagMemRefInfo;
1805  AffineMapAttr tagMapAttr;
1807  OpAsmParser::UnresolvedOperand numElementsInfo;
1809 
1810  SmallVector<Type, 3> types;
1811  auto indexType = parser.getBuilder().getIndexType();
1812 
1813  // Parse and resolve the following list of operands:
1814  // *) dst memref followed by its affine maps operands (in square brackets).
1815  // *) src memref followed by its affine map operands (in square brackets).
1816  // *) tag memref followed by its affine map operands (in square brackets).
1817  // *) number of elements transferred by DMA operation.
1818  if (parser.parseOperand(srcMemRefInfo) ||
1819  parser.parseAffineMapOfSSAIds(srcMapOperands, srcMapAttr,
1820  getSrcMapAttrStrName(),
1821  result.attributes) ||
1822  parser.parseComma() || parser.parseOperand(dstMemRefInfo) ||
1823  parser.parseAffineMapOfSSAIds(dstMapOperands, dstMapAttr,
1824  getDstMapAttrStrName(),
1825  result.attributes) ||
1826  parser.parseComma() || parser.parseOperand(tagMemRefInfo) ||
1827  parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
1828  getTagMapAttrStrName(),
1829  result.attributes) ||
1830  parser.parseComma() || parser.parseOperand(numElementsInfo))
1831  return failure();
1832 
1833  // Parse optional stride and elements per stride.
1834  if (parser.parseTrailingOperandList(strideInfo))
1835  return failure();
1836 
1837  if (!strideInfo.empty() && strideInfo.size() != 2) {
1838  return parser.emitError(parser.getNameLoc(),
1839  "expected two stride related operands");
1840  }
1841  bool isStrided = strideInfo.size() == 2;
1842 
1843  if (parser.parseColonTypeList(types))
1844  return failure();
1845 
1846  if (types.size() != 3)
1847  return parser.emitError(parser.getNameLoc(), "expected three types");
1848 
1849  if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) ||
1850  parser.resolveOperands(srcMapOperands, indexType, result.operands) ||
1851  parser.resolveOperand(dstMemRefInfo, types[1], result.operands) ||
1852  parser.resolveOperands(dstMapOperands, indexType, result.operands) ||
1853  parser.resolveOperand(tagMemRefInfo, types[2], result.operands) ||
1854  parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
1855  parser.resolveOperand(numElementsInfo, indexType, result.operands))
1856  return failure();
1857 
1858  if (isStrided) {
1859  if (parser.resolveOperands(strideInfo, indexType, result.operands))
1860  return failure();
1861  }
1862 
1863  // Check that src/dst/tag operand counts match their map.numInputs.
1864  if (srcMapOperands.size() != srcMapAttr.getValue().getNumInputs() ||
1865  dstMapOperands.size() != dstMapAttr.getValue().getNumInputs() ||
1866  tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
1867  return parser.emitError(parser.getNameLoc(),
1868  "memref operand count not equal to map.numInputs");
1869  return success();
1870 }
1871 
1872 LogicalResult AffineDmaStartOp::verifyInvariantsImpl() {
1873  if (!llvm::isa<MemRefType>(getOperand(getSrcMemRefOperandIndex()).getType()))
1874  return emitOpError("expected DMA source to be of memref type");
1875  if (!llvm::isa<MemRefType>(getOperand(getDstMemRefOperandIndex()).getType()))
1876  return emitOpError("expected DMA destination to be of memref type");
1877  if (!llvm::isa<MemRefType>(getOperand(getTagMemRefOperandIndex()).getType()))
1878  return emitOpError("expected DMA tag to be of memref type");
1879 
1880  unsigned numInputsAllMaps = getSrcMap().getNumInputs() +
1881  getDstMap().getNumInputs() +
1882  getTagMap().getNumInputs();
1883  if (getNumOperands() != numInputsAllMaps + 3 + 1 &&
1884  getNumOperands() != numInputsAllMaps + 3 + 1 + 2) {
1885  return emitOpError("incorrect number of operands");
1886  }
1887 
1888  Region *scope = getAffineScope(*this);
1889  for (auto idx : getSrcIndices()) {
1890  if (!idx.getType().isIndex())
1891  return emitOpError("src index to dma_start must have 'index' type");
1892  if (!isValidAffineIndexOperand(idx, scope))
1893  return emitOpError(
1894  "src index must be a valid dimension or symbol identifier");
1895  }
1896  for (auto idx : getDstIndices()) {
1897  if (!idx.getType().isIndex())
1898  return emitOpError("dst index to dma_start must have 'index' type");
1899  if (!isValidAffineIndexOperand(idx, scope))
1900  return emitOpError(
1901  "dst index must be a valid dimension or symbol identifier");
1902  }
1903  for (auto idx : getTagIndices()) {
1904  if (!idx.getType().isIndex())
1905  return emitOpError("tag index to dma_start must have 'index' type");
1906  if (!isValidAffineIndexOperand(idx, scope))
1907  return emitOpError(
1908  "tag index must be a valid dimension or symbol identifier");
1909  }
1910  return success();
1911 }
1912 
1913 LogicalResult AffineDmaStartOp::fold(ArrayRef<Attribute> cstOperands,
1914  SmallVectorImpl<OpFoldResult> &results) {
1915  /// dma_start(memrefcast) -> dma_start
1916  return memref::foldMemRefCast(*this);
1917 }
1918 
1919 void AffineDmaStartOp::getEffects(
1921  &effects) {
1922  effects.emplace_back(MemoryEffects::Read::get(), &getSrcMemRefMutable(),
1924  effects.emplace_back(MemoryEffects::Write::get(), &getDstMemRefMutable(),
1926  effects.emplace_back(MemoryEffects::Read::get(), &getTagMemRefMutable(),
1928 }
1929 
1930 //===----------------------------------------------------------------------===//
1931 // AffineDmaWaitOp
1932 //===----------------------------------------------------------------------===//
1933 
1934 // TODO: Check that map operands are loop IVs or symbols.
1935 void AffineDmaWaitOp::build(OpBuilder &builder, OperationState &result,
1936  Value tagMemRef, AffineMap tagMap,
1937  ValueRange tagIndices, Value numElements) {
1938  result.addOperands(tagMemRef);
1939  result.addAttribute(getTagMapAttrStrName(), AffineMapAttr::get(tagMap));
1940  result.addOperands(tagIndices);
1941  result.addOperands(numElements);
1942 }
1943 
1944 AffineDmaWaitOp AffineDmaWaitOp::create(OpBuilder &builder, Location location,
1945  Value tagMemRef, AffineMap tagMap,
1946  ValueRange tagIndices,
1947  Value numElements) {
1948  mlir::OperationState state(location, getOperationName());
1949  build(builder, state, tagMemRef, tagMap, tagIndices, numElements);
1950  auto result = dyn_cast<AffineDmaWaitOp>(builder.create(state));
1951  assert(result && "builder didn't return the right type");
1952  return result;
1953 }
1954 
1955 AffineDmaWaitOp AffineDmaWaitOp::create(ImplicitLocOpBuilder &builder,
1956  Value tagMemRef, AffineMap tagMap,
1957  ValueRange tagIndices,
1958  Value numElements) {
1959  return create(builder, builder.getLoc(), tagMemRef, tagMap, tagIndices,
1960  numElements);
1961 }
1962 
1964  p << " " << getTagMemRef() << '[';
1965  SmallVector<Value, 2> operands(getTagIndices());
1966  p.printAffineMapOfSSAIds(getTagMapAttr(), operands);
1967  p << "], ";
1969  p << " : " << getTagMemRef().getType();
1970 }
1971 
1972 // Parse AffineDmaWaitOp.
1973 // Eg:
1974 // affine.dma_wait %tag[%index], %num_elements
1975 // : memref<1 x i32, (d0) -> (d0), 4>
1976 //
1978  OperationState &result) {
1979  OpAsmParser::UnresolvedOperand tagMemRefInfo;
1980  AffineMapAttr tagMapAttr;
1982  Type type;
1983  auto indexType = parser.getBuilder().getIndexType();
1984  OpAsmParser::UnresolvedOperand numElementsInfo;
1985 
1986  // Parse tag memref, its map operands, and dma size.
1987  if (parser.parseOperand(tagMemRefInfo) ||
1988  parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
1989  getTagMapAttrStrName(),
1990  result.attributes) ||
1991  parser.parseComma() || parser.parseOperand(numElementsInfo) ||
1992  parser.parseColonType(type) ||
1993  parser.resolveOperand(tagMemRefInfo, type, result.operands) ||
1994  parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
1995  parser.resolveOperand(numElementsInfo, indexType, result.operands))
1996  return failure();
1997 
1998  if (!llvm::isa<MemRefType>(type))
1999  return parser.emitError(parser.getNameLoc(),
2000  "expected tag to be of memref type");
2001 
2002  if (tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
2003  return parser.emitError(parser.getNameLoc(),
2004  "tag memref operand count != to map.numInputs");
2005  return success();
2006 }
2007 
2008 LogicalResult AffineDmaWaitOp::verifyInvariantsImpl() {
2009  if (!llvm::isa<MemRefType>(getOperand(0).getType()))
2010  return emitOpError("expected DMA tag to be of memref type");
2011  Region *scope = getAffineScope(*this);
2012  for (auto idx : getTagIndices()) {
2013  if (!idx.getType().isIndex())
2014  return emitOpError("index to dma_wait must have 'index' type");
2015  if (!isValidAffineIndexOperand(idx, scope))
2016  return emitOpError(
2017  "index must be a valid dimension or symbol identifier");
2018  }
2019  return success();
2020 }
2021 
2022 LogicalResult AffineDmaWaitOp::fold(ArrayRef<Attribute> cstOperands,
2023  SmallVectorImpl<OpFoldResult> &results) {
2024  /// dma_wait(memrefcast) -> dma_wait
2025  return memref::foldMemRefCast(*this);
2026 }
2027 
2028 void AffineDmaWaitOp::getEffects(
2030  &effects) {
2031  effects.emplace_back(MemoryEffects::Read::get(), &getTagMemRefMutable(),
2033 }
2034 
2035 //===----------------------------------------------------------------------===//
2036 // AffineForOp
2037 //===----------------------------------------------------------------------===//
2038 
2039 /// 'bodyBuilder' is used to build the body of affine.for. If iterArgs and
2040 /// bodyBuilder are empty/null, we include default terminator op.
2041 void AffineForOp::build(OpBuilder &builder, OperationState &result,
2042  ValueRange lbOperands, AffineMap lbMap,
2043  ValueRange ubOperands, AffineMap ubMap, int64_t step,
2044  ValueRange iterArgs, BodyBuilderFn bodyBuilder) {
2045  assert(((!lbMap && lbOperands.empty()) ||
2046  lbOperands.size() == lbMap.getNumInputs()) &&
2047  "lower bound operand count does not match the affine map");
2048  assert(((!ubMap && ubOperands.empty()) ||
2049  ubOperands.size() == ubMap.getNumInputs()) &&
2050  "upper bound operand count does not match the affine map");
2051  assert(step > 0 && "step has to be a positive integer constant");
2052 
2053  OpBuilder::InsertionGuard guard(builder);
2054 
2055  // Set variadic segment sizes.
2056  result.addAttribute(
2057  getOperandSegmentSizeAttr(),
2058  builder.getDenseI32ArrayAttr({static_cast<int32_t>(lbOperands.size()),
2059  static_cast<int32_t>(ubOperands.size()),
2060  static_cast<int32_t>(iterArgs.size())}));
2061 
2062  for (Value val : iterArgs)
2063  result.addTypes(val.getType());
2064 
2065  // Add an attribute for the step.
2066  result.addAttribute(getStepAttrName(result.name),
2067  builder.getIntegerAttr(builder.getIndexType(), step));
2068 
2069  // Add the lower bound.
2070  result.addAttribute(getLowerBoundMapAttrName(result.name),
2071  AffineMapAttr::get(lbMap));
2072  result.addOperands(lbOperands);
2073 
2074  // Add the upper bound.
2075  result.addAttribute(getUpperBoundMapAttrName(result.name),
2076  AffineMapAttr::get(ubMap));
2077  result.addOperands(ubOperands);
2078 
2079  result.addOperands(iterArgs);
2080  // Create a region and a block for the body. The argument of the region is
2081  // the loop induction variable.
2082  Region *bodyRegion = result.addRegion();
2083  Block *bodyBlock = builder.createBlock(bodyRegion);
2084  Value inductionVar =
2085  bodyBlock->addArgument(builder.getIndexType(), result.location);
2086  for (Value val : iterArgs)
2087  bodyBlock->addArgument(val.getType(), val.getLoc());
2088 
2089  // Create the default terminator if the builder is not provided and if the
2090  // iteration arguments are not provided. Otherwise, leave this to the caller
2091  // because we don't know which values to return from the loop.
2092  if (iterArgs.empty() && !bodyBuilder) {
2093  ensureTerminator(*bodyRegion, builder, result.location);
2094  } else if (bodyBuilder) {
2095  OpBuilder::InsertionGuard guard(builder);
2096  builder.setInsertionPointToStart(bodyBlock);
2097  bodyBuilder(builder, result.location, inductionVar,
2098  bodyBlock->getArguments().drop_front());
2099  }
2100 }
2101 
2102 void AffineForOp::build(OpBuilder &builder, OperationState &result, int64_t lb,
2103  int64_t ub, int64_t step, ValueRange iterArgs,
2104  BodyBuilderFn bodyBuilder) {
2105  auto lbMap = AffineMap::getConstantMap(lb, builder.getContext());
2106  auto ubMap = AffineMap::getConstantMap(ub, builder.getContext());
2107  return build(builder, result, {}, lbMap, {}, ubMap, step, iterArgs,
2108  bodyBuilder);
2109 }
2110 
2111 LogicalResult AffineForOp::verifyRegions() {
2112  // Check that the body defines as single block argument for the induction
2113  // variable.
2114  auto *body = getBody();
2115  if (body->getNumArguments() == 0 || !body->getArgument(0).getType().isIndex())
2116  return emitOpError("expected body to have a single index argument for the "
2117  "induction variable");
2118 
2119  // Verify that the bound operands are valid dimension/symbols.
2120  /// Lower bound.
2121  if (getLowerBoundMap().getNumInputs() > 0)
2123  getLowerBoundMap().getNumDims())))
2124  return failure();
2125  /// Upper bound.
2126  if (getUpperBoundMap().getNumInputs() > 0)
2128  getUpperBoundMap().getNumDims())))
2129  return failure();
2130  if (getLowerBoundMap().getNumResults() < 1)
2131  return emitOpError("expected lower bound map to have at least one result");
2132  if (getUpperBoundMap().getNumResults() < 1)
2133  return emitOpError("expected upper bound map to have at least one result");
2134 
2135  unsigned opNumResults = getNumResults();
2136  if (opNumResults == 0)
2137  return success();
2138 
2139  // If ForOp defines values, check that the number and types of the defined
2140  // values match ForOp initial iter operands and backedge basic block
2141  // arguments.
2142  if (getNumIterOperands() != opNumResults)
2143  return emitOpError(
2144  "mismatch between the number of loop-carried values and results");
2145  if (getNumRegionIterArgs() != opNumResults)
2146  return emitOpError(
2147  "mismatch between the number of basic block args and results");
2148 
2149  return success();
2150 }
2151 
2152 /// Parse a for operation loop bounds.
2153 static ParseResult parseBound(bool isLower, OperationState &result,
2154  OpAsmParser &p) {
2155  // 'min' / 'max' prefixes are generally syntactic sugar, but are required if
2156  // the map has multiple results.
2157  bool failedToParsedMinMax =
2158  failed(p.parseOptionalKeyword(isLower ? "max" : "min"));
2159 
2160  auto &builder = p.getBuilder();
2161  auto boundAttrStrName =
2162  isLower ? AffineForOp::getLowerBoundMapAttrName(result.name)
2163  : AffineForOp::getUpperBoundMapAttrName(result.name);
2164 
2165  // Parse ssa-id as identity map.
2167  if (p.parseOperandList(boundOpInfos))
2168  return failure();
2169 
2170  if (!boundOpInfos.empty()) {
2171  // Check that only one operand was parsed.
2172  if (boundOpInfos.size() > 1)
2173  return p.emitError(p.getNameLoc(),
2174  "expected only one loop bound operand");
2175 
2176  // TODO: improve error message when SSA value is not of index type.
2177  // Currently it is 'use of value ... expects different type than prior uses'
2178  if (p.resolveOperand(boundOpInfos.front(), builder.getIndexType(),
2179  result.operands))
2180  return failure();
2181 
2182  // Create an identity map using symbol id. This representation is optimized
2183  // for storage. Analysis passes may expand it into a multi-dimensional map
2184  // if desired.
2185  AffineMap map = builder.getSymbolIdentityMap();
2186  result.addAttribute(boundAttrStrName, AffineMapAttr::get(map));
2187  return success();
2188  }
2189 
2190  // Get the attribute location.
2191  SMLoc attrLoc = p.getCurrentLocation();
2192 
2193  Attribute boundAttr;
2194  if (p.parseAttribute(boundAttr, builder.getIndexType(), boundAttrStrName,
2195  result.attributes))
2196  return failure();
2197 
2198  // Parse full form - affine map followed by dim and symbol list.
2199  if (auto affineMapAttr = dyn_cast<AffineMapAttr>(boundAttr)) {
2200  unsigned currentNumOperands = result.operands.size();
2201  unsigned numDims;
2202  if (parseDimAndSymbolList(p, result.operands, numDims))
2203  return failure();
2204 
2205  auto map = affineMapAttr.getValue();
2206  if (map.getNumDims() != numDims)
2207  return p.emitError(
2208  p.getNameLoc(),
2209  "dim operand count and affine map dim count must match");
2210 
2211  unsigned numDimAndSymbolOperands =
2212  result.operands.size() - currentNumOperands;
2213  if (numDims + map.getNumSymbols() != numDimAndSymbolOperands)
2214  return p.emitError(
2215  p.getNameLoc(),
2216  "symbol operand count and affine map symbol count must match");
2217 
2218  // If the map has multiple results, make sure that we parsed the min/max
2219  // prefix.
2220  if (map.getNumResults() > 1 && failedToParsedMinMax) {
2221  if (isLower) {
2222  return p.emitError(attrLoc, "lower loop bound affine map with "
2223  "multiple results requires 'max' prefix");
2224  }
2225  return p.emitError(attrLoc, "upper loop bound affine map with multiple "
2226  "results requires 'min' prefix");
2227  }
2228  return success();
2229  }
2230 
2231  // Parse custom assembly form.
2232  if (auto integerAttr = dyn_cast<IntegerAttr>(boundAttr)) {
2233  result.attributes.pop_back();
2234  result.addAttribute(
2235  boundAttrStrName,
2236  AffineMapAttr::get(builder.getConstantAffineMap(integerAttr.getInt())));
2237  return success();
2238  }
2239 
2240  return p.emitError(
2241  p.getNameLoc(),
2242  "expected valid affine map representation for loop bounds");
2243 }
2244 
2245 ParseResult AffineForOp::parse(OpAsmParser &parser, OperationState &result) {
2246  auto &builder = parser.getBuilder();
2247  OpAsmParser::Argument inductionVariable;
2248  inductionVariable.type = builder.getIndexType();
2249  // Parse the induction variable followed by '='.
2250  if (parser.parseArgument(inductionVariable) || parser.parseEqual())
2251  return failure();
2252 
2253  // Parse loop bounds.
2254  int64_t numOperands = result.operands.size();
2255  if (parseBound(/*isLower=*/true, result, parser))
2256  return failure();
2257  int64_t numLbOperands = result.operands.size() - numOperands;
2258  if (parser.parseKeyword("to", " between bounds"))
2259  return failure();
2260  numOperands = result.operands.size();
2261  if (parseBound(/*isLower=*/false, result, parser))
2262  return failure();
2263  int64_t numUbOperands = result.operands.size() - numOperands;
2264 
2265  // Parse the optional loop step, we default to 1 if one is not present.
2266  if (parser.parseOptionalKeyword("step")) {
2267  result.addAttribute(
2268  getStepAttrName(result.name),
2269  builder.getIntegerAttr(builder.getIndexType(), /*value=*/1));
2270  } else {
2271  SMLoc stepLoc = parser.getCurrentLocation();
2272  IntegerAttr stepAttr;
2273  if (parser.parseAttribute(stepAttr, builder.getIndexType(),
2274  getStepAttrName(result.name).data(),
2275  result.attributes))
2276  return failure();
2277 
2278  if (stepAttr.getValue().isNegative())
2279  return parser.emitError(
2280  stepLoc,
2281  "expected step to be representable as a positive signed integer");
2282  }
2283 
2284  // Parse the optional initial iteration arguments.
2287 
2288  // Induction variable.
2289  regionArgs.push_back(inductionVariable);
2290 
2291  if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
2292  // Parse assignment list and results type list.
2293  if (parser.parseAssignmentList(regionArgs, operands) ||
2294  parser.parseArrowTypeList(result.types))
2295  return failure();
2296  // Resolve input operands.
2297  for (auto argOperandType :
2298  llvm::zip(llvm::drop_begin(regionArgs), operands, result.types)) {
2299  Type type = std::get<2>(argOperandType);
2300  std::get<0>(argOperandType).type = type;
2301  if (parser.resolveOperand(std::get<1>(argOperandType), type,
2302  result.operands))
2303  return failure();
2304  }
2305  }
2306 
2307  result.addAttribute(
2308  getOperandSegmentSizeAttr(),
2309  builder.getDenseI32ArrayAttr({static_cast<int32_t>(numLbOperands),
2310  static_cast<int32_t>(numUbOperands),
2311  static_cast<int32_t>(operands.size())}));
2312 
2313  // Parse the body region.
2314  Region *body = result.addRegion();
2315  if (regionArgs.size() != result.types.size() + 1)
2316  return parser.emitError(
2317  parser.getNameLoc(),
2318  "mismatch between the number of loop-carried values and results");
2319  if (parser.parseRegion(*body, regionArgs))
2320  return failure();
2321 
2322  AffineForOp::ensureTerminator(*body, builder, result.location);
2323 
2324  // Parse the optional attribute list.
2325  return parser.parseOptionalAttrDict(result.attributes);
2326 }
2327 
2328 static void printBound(AffineMapAttr boundMap,
2329  Operation::operand_range boundOperands,
2330  const char *prefix, OpAsmPrinter &p) {
2331  AffineMap map = boundMap.getValue();
2332 
2333  // Check if this bound should be printed using custom assembly form.
2334  // The decision to restrict printing custom assembly form to trivial cases
2335  // comes from the will to roundtrip MLIR binary -> text -> binary in a
2336  // lossless way.
2337  // Therefore, custom assembly form parsing and printing is only supported for
2338  // zero-operand constant maps and single symbol operand identity maps.
2339  if (map.getNumResults() == 1) {
2340  AffineExpr expr = map.getResult(0);
2341 
2342  // Print constant bound.
2343  if (map.getNumDims() == 0 && map.getNumSymbols() == 0) {
2344  if (auto constExpr = dyn_cast<AffineConstantExpr>(expr)) {
2345  p << constExpr.getValue();
2346  return;
2347  }
2348  }
2349 
2350  // Print bound that consists of a single SSA symbol if the map is over a
2351  // single symbol.
2352  if (map.getNumDims() == 0 && map.getNumSymbols() == 1) {
2353  if (isa<AffineSymbolExpr>(expr)) {
2354  p.printOperand(*boundOperands.begin());
2355  return;
2356  }
2357  }
2358  } else {
2359  // Map has multiple results. Print 'min' or 'max' prefix.
2360  p << prefix << ' ';
2361  }
2362 
2363  // Print the map and its operands.
2364  p << boundMap;
2365  printDimAndSymbolList(boundOperands.begin(), boundOperands.end(),
2366  map.getNumDims(), p);
2367 }
2368 
2369 unsigned AffineForOp::getNumIterOperands() {
2370  AffineMap lbMap = getLowerBoundMapAttr().getValue();
2371  AffineMap ubMap = getUpperBoundMapAttr().getValue();
2372 
2373  return getNumOperands() - lbMap.getNumInputs() - ubMap.getNumInputs();
2374 }
2375 
2376 std::optional<MutableArrayRef<OpOperand>>
2377 AffineForOp::getYieldedValuesMutable() {
2378  return cast<AffineYieldOp>(getBody()->getTerminator()).getOperandsMutable();
2379 }
2380 
2382  p << ' ';
2383  p.printRegionArgument(getBody()->getArgument(0), /*argAttrs=*/{},
2384  /*omitType=*/true);
2385  p << " = ";
2386  printBound(getLowerBoundMapAttr(), getLowerBoundOperands(), "max", p);
2387  p << " to ";
2388  printBound(getUpperBoundMapAttr(), getUpperBoundOperands(), "min", p);
2389 
2390  if (getStepAsInt() != 1)
2391  p << " step " << getStepAsInt();
2392 
2393  bool printBlockTerminators = false;
2394  if (getNumIterOperands() > 0) {
2395  p << " iter_args(";
2396  auto regionArgs = getRegionIterArgs();
2397  auto operands = getInits();
2398 
2399  llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
2400  p << std::get<0>(it) << " = " << std::get<1>(it);
2401  });
2402  p << ") -> (" << getResultTypes() << ")";
2403  printBlockTerminators = true;
2404  }
2405 
2406  p << ' ';
2407  p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
2408  printBlockTerminators);
2410  (*this)->getAttrs(),
2411  /*elidedAttrs=*/{getLowerBoundMapAttrName(getOperation()->getName()),
2412  getUpperBoundMapAttrName(getOperation()->getName()),
2413  getStepAttrName(getOperation()->getName()),
2414  getOperandSegmentSizeAttr()});
2415 }
2416 
2417 /// Fold the constant bounds of a loop.
2418 static LogicalResult foldLoopBounds(AffineForOp forOp) {
2419  auto foldLowerOrUpperBound = [&forOp](bool lower) {
2420  // Check to see if each of the operands is the result of a constant. If
2421  // so, get the value. If not, ignore it.
2422  SmallVector<Attribute, 8> operandConstants;
2423  auto boundOperands =
2424  lower ? forOp.getLowerBoundOperands() : forOp.getUpperBoundOperands();
2425  for (auto operand : boundOperands) {
2426  Attribute operandCst;
2427  matchPattern(operand, m_Constant(&operandCst));
2428  operandConstants.push_back(operandCst);
2429  }
2430 
2431  AffineMap boundMap =
2432  lower ? forOp.getLowerBoundMap() : forOp.getUpperBoundMap();
2433  assert(boundMap.getNumResults() >= 1 &&
2434  "bound maps should have at least one result");
2435  SmallVector<Attribute, 4> foldedResults;
2436  if (failed(boundMap.constantFold(operandConstants, foldedResults)))
2437  return failure();
2438 
2439  // Compute the max or min as applicable over the results.
2440  assert(!foldedResults.empty() && "bounds should have at least one result");
2441  auto maxOrMin = llvm::cast<IntegerAttr>(foldedResults[0]).getValue();
2442  for (unsigned i = 1, e = foldedResults.size(); i < e; i++) {
2443  auto foldedResult = llvm::cast<IntegerAttr>(foldedResults[i]).getValue();
2444  maxOrMin = lower ? llvm::APIntOps::smax(maxOrMin, foldedResult)
2445  : llvm::APIntOps::smin(maxOrMin, foldedResult);
2446  }
2447  lower ? forOp.setConstantLowerBound(maxOrMin.getSExtValue())
2448  : forOp.setConstantUpperBound(maxOrMin.getSExtValue());
2449  return success();
2450  };
2451 
2452  // Try to fold the lower bound.
2453  bool folded = false;
2454  if (!forOp.hasConstantLowerBound())
2455  folded |= succeeded(foldLowerOrUpperBound(/*lower=*/true));
2456 
2457  // Try to fold the upper bound.
2458  if (!forOp.hasConstantUpperBound())
2459  folded |= succeeded(foldLowerOrUpperBound(/*lower=*/false));
2460  return success(folded);
2461 }
2462 
2463 /// Canonicalize the bounds of the given loop.
2464 static LogicalResult canonicalizeLoopBounds(AffineForOp forOp) {
2465  SmallVector<Value, 4> lbOperands(forOp.getLowerBoundOperands());
2466  SmallVector<Value, 4> ubOperands(forOp.getUpperBoundOperands());
2467 
2468  auto lbMap = forOp.getLowerBoundMap();
2469  auto ubMap = forOp.getUpperBoundMap();
2470  auto prevLbMap = lbMap;
2471  auto prevUbMap = ubMap;
2472 
2473  composeAffineMapAndOperands(&lbMap, &lbOperands);
2474  canonicalizeMapAndOperands(&lbMap, &lbOperands);
2475  simplifyMinOrMaxExprWithOperands(lbMap, lbOperands, /*isMax=*/true);
2476  simplifyMinOrMaxExprWithOperands(ubMap, ubOperands, /*isMax=*/false);
2477  lbMap = removeDuplicateExprs(lbMap);
2478 
2479  composeAffineMapAndOperands(&ubMap, &ubOperands);
2480  canonicalizeMapAndOperands(&ubMap, &ubOperands);
2481  ubMap = removeDuplicateExprs(ubMap);
2482 
2483  // Any canonicalization change always leads to updated map(s).
2484  if (lbMap == prevLbMap && ubMap == prevUbMap)
2485  return failure();
2486 
2487  if (lbMap != prevLbMap)
2488  forOp.setLowerBound(lbOperands, lbMap);
2489  if (ubMap != prevUbMap)
2490  forOp.setUpperBound(ubOperands, ubMap);
2491  return success();
2492 }
2493 
2494 namespace {
2495 /// Returns constant trip count in trivial cases.
2496 static std::optional<uint64_t> getTrivialConstantTripCount(AffineForOp forOp) {
2497  int64_t step = forOp.getStepAsInt();
2498  if (!forOp.hasConstantBounds() || step <= 0)
2499  return std::nullopt;
2500  int64_t lb = forOp.getConstantLowerBound();
2501  int64_t ub = forOp.getConstantUpperBound();
2502  return ub - lb <= 0 ? 0 : (ub - lb + step - 1) / step;
2503 }
2504 
2505 /// This is a pattern to fold trivially empty loop bodies.
2506 /// TODO: This should be moved into the folding hook.
2507 struct AffineForEmptyLoopFolder : public OpRewritePattern<AffineForOp> {
2509 
2510  LogicalResult matchAndRewrite(AffineForOp forOp,
2511  PatternRewriter &rewriter) const override {
2512  // Check that the body only contains a yield.
2513  if (!llvm::hasSingleElement(*forOp.getBody()))
2514  return failure();
2515  if (forOp.getNumResults() == 0)
2516  return success();
2517  std::optional<uint64_t> tripCount = getTrivialConstantTripCount(forOp);
2518  if (tripCount == 0) {
2519  // The initial values of the iteration arguments would be the op's
2520  // results.
2521  rewriter.replaceOp(forOp, forOp.getInits());
2522  return success();
2523  }
2524  SmallVector<Value, 4> replacements;
2525  auto yieldOp = cast<AffineYieldOp>(forOp.getBody()->getTerminator());
2526  auto iterArgs = forOp.getRegionIterArgs();
2527  bool hasValDefinedOutsideLoop = false;
2528  bool iterArgsNotInOrder = false;
2529  for (unsigned i = 0, e = yieldOp->getNumOperands(); i < e; ++i) {
2530  Value val = yieldOp.getOperand(i);
2531  auto *iterArgIt = llvm::find(iterArgs, val);
2532  // TODO: It should be possible to perform a replacement by computing the
2533  // last value of the IV based on the bounds and the step.
2534  if (val == forOp.getInductionVar())
2535  return failure();
2536  if (iterArgIt == iterArgs.end()) {
2537  // `val` is defined outside of the loop.
2538  assert(forOp.isDefinedOutsideOfLoop(val) &&
2539  "must be defined outside of the loop");
2540  hasValDefinedOutsideLoop = true;
2541  replacements.push_back(val);
2542  } else {
2543  unsigned pos = std::distance(iterArgs.begin(), iterArgIt);
2544  if (pos != i)
2545  iterArgsNotInOrder = true;
2546  replacements.push_back(forOp.getInits()[pos]);
2547  }
2548  }
2549  // Bail out when the trip count is unknown and the loop returns any value
2550  // defined outside of the loop or any iterArg out of order.
2551  if (!tripCount.has_value() &&
2552  (hasValDefinedOutsideLoop || iterArgsNotInOrder))
2553  return failure();
2554  // Bail out when the loop iterates more than once and it returns any iterArg
2555  // out of order.
2556  if (tripCount.has_value() && tripCount.value() >= 2 && iterArgsNotInOrder)
2557  return failure();
2558  rewriter.replaceOp(forOp, replacements);
2559  return success();
2560  }
2561 };
2562 } // namespace
2563 
2564 void AffineForOp::getCanonicalizationPatterns(RewritePatternSet &results,
2565  MLIRContext *context) {
2566  results.add<AffineForEmptyLoopFolder>(context);
2567 }
2568 
2569 OperandRange AffineForOp::getEntrySuccessorOperands(RegionBranchPoint point) {
2570  assert((point.isParent() || point == getRegion()) && "invalid region point");
2571 
2572  // The initial operands map to the loop arguments after the induction
2573  // variable or are forwarded to the results when the trip count is zero.
2574  return getInits();
2575 }
2576 
2577 void AffineForOp::getSuccessorRegions(
2579  assert((point.isParent() || point == getRegion()) && "expected loop region");
2580  // The loop may typically branch back to its body or to the parent operation.
2581  // If the predecessor is the parent op and the trip count is known to be at
2582  // least one, branch into the body using the iterator arguments. And in cases
2583  // we know the trip count is zero, it can only branch back to its parent.
2584  std::optional<uint64_t> tripCount = getTrivialConstantTripCount(*this);
2585  if (point.isParent() && tripCount.has_value()) {
2586  if (tripCount.value() > 0) {
2587  regions.push_back(RegionSuccessor(&getRegion(), getRegionIterArgs()));
2588  return;
2589  }
2590  if (tripCount.value() == 0) {
2591  regions.push_back(RegionSuccessor(getResults()));
2592  return;
2593  }
2594  }
2595 
2596  // From the loop body, if the trip count is one, we can only branch back to
2597  // the parent.
2598  if (!point.isParent() && tripCount == 1) {
2599  regions.push_back(RegionSuccessor(getResults()));
2600  return;
2601  }
2602 
2603  // In all other cases, the loop may branch back to itself or the parent
2604  // operation.
2605  regions.push_back(RegionSuccessor(&getRegion(), getRegionIterArgs()));
2606  regions.push_back(RegionSuccessor(getResults()));
2607 }
2608 
2609 /// Returns true if the affine.for has zero iterations in trivial cases.
2610 static bool hasTrivialZeroTripCount(AffineForOp op) {
2611  return getTrivialConstantTripCount(op) == 0;
2612 }
2613 
2614 LogicalResult AffineForOp::fold(FoldAdaptor adaptor,
2615  SmallVectorImpl<OpFoldResult> &results) {
2616  bool folded = succeeded(foldLoopBounds(*this));
2617  folded |= succeeded(canonicalizeLoopBounds(*this));
2618  if (hasTrivialZeroTripCount(*this) && getNumResults() != 0) {
2619  // The initial values of the loop-carried variables (iter_args) are the
2620  // results of the op. But this must be avoided for an affine.for op that
2621  // does not return any results. Since ops that do not return results cannot
2622  // be folded away, we would enter an infinite loop of folds on the same
2623  // affine.for op.
2624  results.assign(getInits().begin(), getInits().end());
2625  folded = true;
2626  }
2627  return success(folded);
2628 }
2629 
2631  return AffineBound(*this, getLowerBoundOperands(), getLowerBoundMap());
2632 }
2633 
2635  return AffineBound(*this, getUpperBoundOperands(), getUpperBoundMap());
2636 }
2637 
2638 void AffineForOp::setLowerBound(ValueRange lbOperands, AffineMap map) {
2639  assert(lbOperands.size() == map.getNumInputs());
2640  assert(map.getNumResults() >= 1 && "bound map has at least one result");
2641  getLowerBoundOperandsMutable().assign(lbOperands);
2642  setLowerBoundMap(map);
2643 }
2644 
2645 void AffineForOp::setUpperBound(ValueRange ubOperands, AffineMap map) {
2646  assert(ubOperands.size() == map.getNumInputs());
2647  assert(map.getNumResults() >= 1 && "bound map has at least one result");
2648  getUpperBoundOperandsMutable().assign(ubOperands);
2649  setUpperBoundMap(map);
2650 }
2651 
2652 bool AffineForOp::hasConstantLowerBound() {
2653  return getLowerBoundMap().isSingleConstant();
2654 }
2655 
2656 bool AffineForOp::hasConstantUpperBound() {
2657  return getUpperBoundMap().isSingleConstant();
2658 }
2659 
2660 int64_t AffineForOp::getConstantLowerBound() {
2661  return getLowerBoundMap().getSingleConstantResult();
2662 }
2663 
2664 int64_t AffineForOp::getConstantUpperBound() {
2665  return getUpperBoundMap().getSingleConstantResult();
2666 }
2667 
2668 void AffineForOp::setConstantLowerBound(int64_t value) {
2669  setLowerBound({}, AffineMap::getConstantMap(value, getContext()));
2670 }
2671 
2672 void AffineForOp::setConstantUpperBound(int64_t value) {
2673  setUpperBound({}, AffineMap::getConstantMap(value, getContext()));
2674 }
2675 
2676 AffineForOp::operand_range AffineForOp::getControlOperands() {
2677  return {operand_begin(), operand_begin() + getLowerBoundOperands().size() +
2678  getUpperBoundOperands().size()};
2679 }
2680 
2681 bool AffineForOp::matchingBoundOperandList() {
2682  auto lbMap = getLowerBoundMap();
2683  auto ubMap = getUpperBoundMap();
2684  if (lbMap.getNumDims() != ubMap.getNumDims() ||
2685  lbMap.getNumSymbols() != ubMap.getNumSymbols())
2686  return false;
2687 
2688  unsigned numOperands = lbMap.getNumInputs();
2689  for (unsigned i = 0, e = lbMap.getNumInputs(); i < e; i++) {
2690  // Compare Value 's.
2691  if (getOperand(i) != getOperand(numOperands + i))
2692  return false;
2693  }
2694  return true;
2695 }
2696 
2697 SmallVector<Region *> AffineForOp::getLoopRegions() { return {&getRegion()}; }
2698 
2699 std::optional<SmallVector<Value>> AffineForOp::getLoopInductionVars() {
2700  return SmallVector<Value>{getInductionVar()};
2701 }
2702 
2703 std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopLowerBounds() {
2704  if (!hasConstantLowerBound())
2705  return std::nullopt;
2706  OpBuilder b(getContext());
2708  OpFoldResult(b.getI64IntegerAttr(getConstantLowerBound()))};
2709 }
2710 
2711 std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopSteps() {
2712  OpBuilder b(getContext());
2714  OpFoldResult(b.getI64IntegerAttr(getStepAsInt()))};
2715 }
2716 
2717 std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopUpperBounds() {
2718  if (!hasConstantUpperBound())
2719  return {};
2720  OpBuilder b(getContext());
2722  OpFoldResult(b.getI64IntegerAttr(getConstantUpperBound()))};
2723 }
2724 
2725 FailureOr<LoopLikeOpInterface> AffineForOp::replaceWithAdditionalYields(
2726  RewriterBase &rewriter, ValueRange newInitOperands,
2727  bool replaceInitOperandUsesInLoop,
2728  const NewYieldValuesFn &newYieldValuesFn) {
2729  // Create a new loop before the existing one, with the extra operands.
2730  OpBuilder::InsertionGuard g(rewriter);
2731  rewriter.setInsertionPoint(getOperation());
2732  auto inits = llvm::to_vector(getInits());
2733  inits.append(newInitOperands.begin(), newInitOperands.end());
2734  AffineForOp newLoop = AffineForOp::create(
2735  rewriter, getLoc(), getLowerBoundOperands(), getLowerBoundMap(),
2736  getUpperBoundOperands(), getUpperBoundMap(), getStepAsInt(), inits);
2737 
2738  // Generate the new yield values and append them to the scf.yield operation.
2739  auto yieldOp = cast<AffineYieldOp>(getBody()->getTerminator());
2740  ArrayRef<BlockArgument> newIterArgs =
2741  newLoop.getBody()->getArguments().take_back(newInitOperands.size());
2742  {
2743  OpBuilder::InsertionGuard g(rewriter);
2744  rewriter.setInsertionPoint(yieldOp);
2745  SmallVector<Value> newYieldedValues =
2746  newYieldValuesFn(rewriter, getLoc(), newIterArgs);
2747  assert(newInitOperands.size() == newYieldedValues.size() &&
2748  "expected as many new yield values as new iter operands");
2749  rewriter.modifyOpInPlace(yieldOp, [&]() {
2750  yieldOp.getOperandsMutable().append(newYieldedValues);
2751  });
2752  }
2753 
2754  // Move the loop body to the new op.
2755  rewriter.mergeBlocks(getBody(), newLoop.getBody(),
2756  newLoop.getBody()->getArguments().take_front(
2757  getBody()->getNumArguments()));
2758 
2759  if (replaceInitOperandUsesInLoop) {
2760  // Replace all uses of `newInitOperands` with the corresponding basic block
2761  // arguments.
2762  for (auto it : llvm::zip(newInitOperands, newIterArgs)) {
2763  rewriter.replaceUsesWithIf(std::get<0>(it), std::get<1>(it),
2764  [&](OpOperand &use) {
2765  Operation *user = use.getOwner();
2766  return newLoop->isProperAncestor(user);
2767  });
2768  }
2769  }
2770 
2771  // Replace the old loop.
2772  rewriter.replaceOp(getOperation(),
2773  newLoop->getResults().take_front(getNumResults()));
2774  return cast<LoopLikeOpInterface>(newLoop.getOperation());
2775 }
2776 
2777 Speculation::Speculatability AffineForOp::getSpeculatability() {
2778  // `affine.for (I = Start; I < End; I += 1)` terminates for all values of
2779  // Start and End.
2780  //
2781  // For Step != 1, the loop may not terminate. We can add more smarts here if
2782  // needed.
2783  return getStepAsInt() == 1 ? Speculation::RecursivelySpeculatable
2785 }
2786 
2787 /// Returns true if the provided value is the induction variable of a
2788 /// AffineForOp.
2790  return getForInductionVarOwner(val) != AffineForOp();
2791 }
2792 
2794  return getAffineParallelInductionVarOwner(val) != nullptr;
2795 }
2796 
2799 }
2800 
2802  auto ivArg = dyn_cast<BlockArgument>(val);
2803  if (!ivArg || !ivArg.getOwner() || !ivArg.getOwner()->getParent())
2804  return AffineForOp();
2805  if (auto forOp =
2806  ivArg.getOwner()->getParent()->getParentOfType<AffineForOp>())
2807  // Check to make sure `val` is the induction variable, not an iter_arg.
2808  return forOp.getInductionVar() == val ? forOp : AffineForOp();
2809  return AffineForOp();
2810 }
2811 
2813  auto ivArg = dyn_cast<BlockArgument>(val);
2814  if (!ivArg || !ivArg.getOwner())
2815  return nullptr;
2816  Operation *containingOp = ivArg.getOwner()->getParentOp();
2817  auto parallelOp = dyn_cast_if_present<AffineParallelOp>(containingOp);
2818  if (parallelOp && llvm::is_contained(parallelOp.getIVs(), val))
2819  return parallelOp;
2820  return nullptr;
2821 }
2822 
2823 /// Extracts the induction variables from a list of AffineForOps and returns
2824 /// them.
2826  SmallVectorImpl<Value> *ivs) {
2827  ivs->reserve(forInsts.size());
2828  for (auto forInst : forInsts)
2829  ivs->push_back(forInst.getInductionVar());
2830 }
2831 
2834  ivs.reserve(affineOps.size());
2835  for (Operation *op : affineOps) {
2836  // Add constraints from forOp's bounds.
2837  if (auto forOp = dyn_cast<AffineForOp>(op))
2838  ivs.push_back(forOp.getInductionVar());
2839  else if (auto parallelOp = dyn_cast<AffineParallelOp>(op))
2840  for (size_t i = 0; i < parallelOp.getBody()->getNumArguments(); i++)
2841  ivs.push_back(parallelOp.getBody()->getArgument(i));
2842  }
2843 }
2844 
2845 /// Builds an affine loop nest, using "loopCreatorFn" to create individual loop
2846 /// operations.
2847 template <typename BoundListTy, typename LoopCreatorTy>
2849  OpBuilder &builder, Location loc, BoundListTy lbs, BoundListTy ubs,
2850  ArrayRef<int64_t> steps,
2851  function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn,
2852  LoopCreatorTy &&loopCreatorFn) {
2853  assert(lbs.size() == ubs.size() && "Mismatch in number of arguments");
2854  assert(lbs.size() == steps.size() && "Mismatch in number of arguments");
2855 
2856  // If there are no loops to be constructed, construct the body anyway.
2857  OpBuilder::InsertionGuard guard(builder);
2858  if (lbs.empty()) {
2859  if (bodyBuilderFn)
2860  bodyBuilderFn(builder, loc, ValueRange());
2861  return;
2862  }
2863 
2864  // Create the loops iteratively and store the induction variables.
2866  ivs.reserve(lbs.size());
2867  for (unsigned i = 0, e = lbs.size(); i < e; ++i) {
2868  // Callback for creating the loop body, always creates the terminator.
2869  auto loopBody = [&](OpBuilder &nestedBuilder, Location nestedLoc, Value iv,
2870  ValueRange iterArgs) {
2871  ivs.push_back(iv);
2872  // In the innermost loop, call the body builder.
2873  if (i == e - 1 && bodyBuilderFn) {
2874  OpBuilder::InsertionGuard nestedGuard(nestedBuilder);
2875  bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
2876  }
2877  AffineYieldOp::create(nestedBuilder, nestedLoc);
2878  };
2879 
2880  // Delegate actual loop creation to the callback in order to dispatch
2881  // between constant- and variable-bound loops.
2882  auto loop = loopCreatorFn(builder, loc, lbs[i], ubs[i], steps[i], loopBody);
2883  builder.setInsertionPointToStart(loop.getBody());
2884  }
2885 }
2886 
2887 /// Creates an affine loop from the bounds known to be constants.
2888 static AffineForOp
2890  int64_t ub, int64_t step,
2891  AffineForOp::BodyBuilderFn bodyBuilderFn) {
2892  return AffineForOp::create(builder, loc, lb, ub, step,
2893  /*iterArgs=*/ValueRange(), bodyBuilderFn);
2894 }
2895 
2896 /// Creates an affine loop from the bounds that may or may not be constants.
2897 static AffineForOp
2899  int64_t step,
2900  AffineForOp::BodyBuilderFn bodyBuilderFn) {
2901  std::optional<int64_t> lbConst = getConstantIntValue(lb);
2902  std::optional<int64_t> ubConst = getConstantIntValue(ub);
2903  if (lbConst && ubConst)
2904  return buildAffineLoopFromConstants(builder, loc, lbConst.value(),
2905  ubConst.value(), step, bodyBuilderFn);
2906  return AffineForOp::create(builder, loc, lb, builder.getDimIdentityMap(), ub,
2907  builder.getDimIdentityMap(), step,
2908  /*iterArgs=*/ValueRange(), bodyBuilderFn);
2909 }
2910 
2912  OpBuilder &builder, Location loc, ArrayRef<int64_t> lbs,
2914  function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
2915  buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
2917 }
2918 
2920  OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
2921  ArrayRef<int64_t> steps,
2922  function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
2923  buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
2925 }
2926 
2927 //===----------------------------------------------------------------------===//
2928 // AffineIfOp
2929 //===----------------------------------------------------------------------===//
2930 
2931 namespace {
2932 /// Remove else blocks that have nothing other than a zero value yield.
2933 struct SimplifyDeadElse : public OpRewritePattern<AffineIfOp> {
2935 
2936  LogicalResult matchAndRewrite(AffineIfOp ifOp,
2937  PatternRewriter &rewriter) const override {
2938  if (ifOp.getElseRegion().empty() ||
2939  !llvm::hasSingleElement(*ifOp.getElseBlock()) || ifOp.getNumResults())
2940  return failure();
2941 
2942  rewriter.startOpModification(ifOp);
2943  rewriter.eraseBlock(ifOp.getElseBlock());
2944  rewriter.finalizeOpModification(ifOp);
2945  return success();
2946  }
2947 };
2948 
2949 /// Removes affine.if cond if the condition is always true or false in certain
2950 /// trivial cases. Promotes the then/else block in the parent operation block.
2951 struct AlwaysTrueOrFalseIf : public OpRewritePattern<AffineIfOp> {
2953 
2954  LogicalResult matchAndRewrite(AffineIfOp op,
2955  PatternRewriter &rewriter) const override {
2956 
2957  auto isTriviallyFalse = [](IntegerSet iSet) {
2958  return iSet.isEmptyIntegerSet();
2959  };
2960 
2961  auto isTriviallyTrue = [](IntegerSet iSet) {
2962  return (iSet.getNumEqualities() == 1 && iSet.getNumInequalities() == 0 &&
2963  iSet.getConstraint(0) == 0);
2964  };
2965 
2966  IntegerSet affineIfConditions = op.getIntegerSet();
2967  Block *blockToMove;
2968  if (isTriviallyFalse(affineIfConditions)) {
2969  // The absence, or equivalently, the emptiness of the else region need not
2970  // be checked when affine.if is returning results because if an affine.if
2971  // operation is returning results, it always has a non-empty else region.
2972  if (op.getNumResults() == 0 && !op.hasElse()) {
2973  // If the else region is absent, or equivalently, empty, remove the
2974  // affine.if operation (which is not returning any results).
2975  rewriter.eraseOp(op);
2976  return success();
2977  }
2978  blockToMove = op.getElseBlock();
2979  } else if (isTriviallyTrue(affineIfConditions)) {
2980  blockToMove = op.getThenBlock();
2981  } else {
2982  return failure();
2983  }
2984  Operation *blockToMoveTerminator = blockToMove->getTerminator();
2985  // Promote the "blockToMove" block to the parent operation block between the
2986  // prologue and epilogue of "op".
2987  rewriter.inlineBlockBefore(blockToMove, op);
2988  // Replace the "op" operation with the operands of the
2989  // "blockToMoveTerminator" operation. Note that "blockToMoveTerminator" is
2990  // the affine.yield operation present in the "blockToMove" block. It has no
2991  // operands when affine.if is not returning results and therefore, in that
2992  // case, replaceOp just erases "op". When affine.if is not returning
2993  // results, the affine.yield operation can be omitted. It gets inserted
2994  // implicitly.
2995  rewriter.replaceOp(op, blockToMoveTerminator->getOperands());
2996  // Erase the "blockToMoveTerminator" operation since it is now in the parent
2997  // operation block, which already has its own terminator.
2998  rewriter.eraseOp(blockToMoveTerminator);
2999  return success();
3000  }
3001 };
3002 } // namespace
3003 
3004 /// AffineIfOp has two regions -- `then` and `else`. The flow of data should be
3005 /// as follows: AffineIfOp -> `then`/`else` -> AffineIfOp
3006 void AffineIfOp::getSuccessorRegions(
3008  // If the predecessor is an AffineIfOp, then branching into both `then` and
3009  // `else` region is valid.
3010  if (point.isParent()) {
3011  regions.reserve(2);
3012  regions.push_back(
3013  RegionSuccessor(&getThenRegion(), getThenRegion().getArguments()));
3014  // If the "else" region is empty, branch bach into parent.
3015  if (getElseRegion().empty()) {
3016  regions.push_back(getResults());
3017  } else {
3018  regions.push_back(
3019  RegionSuccessor(&getElseRegion(), getElseRegion().getArguments()));
3020  }
3021  return;
3022  }
3023 
3024  // If the predecessor is the `else`/`then` region, then branching into parent
3025  // op is valid.
3026  regions.push_back(RegionSuccessor(getResults()));
3027 }
3028 
3029 LogicalResult AffineIfOp::verify() {
3030  // Verify that we have a condition attribute.
3031  // FIXME: This should be specified in the arguments list in ODS.
3032  auto conditionAttr =
3033  (*this)->getAttrOfType<IntegerSetAttr>(getConditionAttrStrName());
3034  if (!conditionAttr)
3035  return emitOpError("requires an integer set attribute named 'condition'");
3036 
3037  // Verify that there are enough operands for the condition.
3038  IntegerSet condition = conditionAttr.getValue();
3039  if (getNumOperands() != condition.getNumInputs())
3040  return emitOpError("operand count and condition integer set dimension and "
3041  "symbol count must match");
3042 
3043  // Verify that the operands are valid dimension/symbols.
3044  if (failed(verifyDimAndSymbolIdentifiers(*this, getOperands(),
3045  condition.getNumDims())))
3046  return failure();
3047 
3048  return success();
3049 }
3050 
3051 ParseResult AffineIfOp::parse(OpAsmParser &parser, OperationState &result) {
3052  // Parse the condition attribute set.
3053  IntegerSetAttr conditionAttr;
3054  unsigned numDims;
3055  if (parser.parseAttribute(conditionAttr,
3056  AffineIfOp::getConditionAttrStrName(),
3057  result.attributes) ||
3058  parseDimAndSymbolList(parser, result.operands, numDims))
3059  return failure();
3060 
3061  // Verify the condition operands.
3062  auto set = conditionAttr.getValue();
3063  if (set.getNumDims() != numDims)
3064  return parser.emitError(
3065  parser.getNameLoc(),
3066  "dim operand count and integer set dim count must match");
3067  if (numDims + set.getNumSymbols() != result.operands.size())
3068  return parser.emitError(
3069  parser.getNameLoc(),
3070  "symbol operand count and integer set symbol count must match");
3071 
3072  if (parser.parseOptionalArrowTypeList(result.types))
3073  return failure();
3074 
3075  // Create the regions for 'then' and 'else'. The latter must be created even
3076  // if it remains empty for the validity of the operation.
3077  result.regions.reserve(2);
3078  Region *thenRegion = result.addRegion();
3079  Region *elseRegion = result.addRegion();
3080 
3081  // Parse the 'then' region.
3082  if (parser.parseRegion(*thenRegion, {}, {}))
3083  return failure();
3084  AffineIfOp::ensureTerminator(*thenRegion, parser.getBuilder(),
3085  result.location);
3086 
3087  // If we find an 'else' keyword then parse the 'else' region.
3088  if (!parser.parseOptionalKeyword("else")) {
3089  if (parser.parseRegion(*elseRegion, {}, {}))
3090  return failure();
3091  AffineIfOp::ensureTerminator(*elseRegion, parser.getBuilder(),
3092  result.location);
3093  }
3094 
3095  // Parse the optional attribute list.
3096  if (parser.parseOptionalAttrDict(result.attributes))
3097  return failure();
3098 
3099  return success();
3100 }
3101 
3103  auto conditionAttr =
3104  (*this)->getAttrOfType<IntegerSetAttr>(getConditionAttrStrName());
3105  p << " " << conditionAttr;
3106  printDimAndSymbolList(operand_begin(), operand_end(),
3107  conditionAttr.getValue().getNumDims(), p);
3108  p.printOptionalArrowTypeList(getResultTypes());
3109  p << ' ';
3110  p.printRegion(getThenRegion(), /*printEntryBlockArgs=*/false,
3111  /*printBlockTerminators=*/getNumResults());
3112 
3113  // Print the 'else' regions if it has any blocks.
3114  auto &elseRegion = this->getElseRegion();
3115  if (!elseRegion.empty()) {
3116  p << " else ";
3117  p.printRegion(elseRegion,
3118  /*printEntryBlockArgs=*/false,
3119  /*printBlockTerminators=*/getNumResults());
3120  }
3121 
3122  // Print the attribute list.
3123  p.printOptionalAttrDict((*this)->getAttrs(),
3124  /*elidedAttrs=*/getConditionAttrStrName());
3125 }
3126 
3127 IntegerSet AffineIfOp::getIntegerSet() {
3128  return (*this)
3129  ->getAttrOfType<IntegerSetAttr>(getConditionAttrStrName())
3130  .getValue();
3131 }
3132 
3133 void AffineIfOp::setIntegerSet(IntegerSet newSet) {
3134  (*this)->setAttr(getConditionAttrStrName(), IntegerSetAttr::get(newSet));
3135 }
3136 
3137 void AffineIfOp::setConditional(IntegerSet set, ValueRange operands) {
3138  setIntegerSet(set);
3139  (*this)->setOperands(operands);
3140 }
3141 
3142 void AffineIfOp::build(OpBuilder &builder, OperationState &result,
3143  TypeRange resultTypes, IntegerSet set, ValueRange args,
3144  bool withElseRegion) {
3145  assert(resultTypes.empty() || withElseRegion);
3146  OpBuilder::InsertionGuard guard(builder);
3147 
3148  result.addTypes(resultTypes);
3149  result.addOperands(args);
3150  result.addAttribute(getConditionAttrStrName(), IntegerSetAttr::get(set));
3151 
3152  Region *thenRegion = result.addRegion();
3153  builder.createBlock(thenRegion);
3154  if (resultTypes.empty())
3155  AffineIfOp::ensureTerminator(*thenRegion, builder, result.location);
3156 
3157  Region *elseRegion = result.addRegion();
3158  if (withElseRegion) {
3159  builder.createBlock(elseRegion);
3160  if (resultTypes.empty())
3161  AffineIfOp::ensureTerminator(*elseRegion, builder, result.location);
3162  }
3163 }
3164 
3165 void AffineIfOp::build(OpBuilder &builder, OperationState &result,
3166  IntegerSet set, ValueRange args, bool withElseRegion) {
3167  AffineIfOp::build(builder, result, /*resultTypes=*/{}, set, args,
3168  withElseRegion);
3169 }
3170 
3171 /// Compose any affine.apply ops feeding into `operands` of the integer set
3172 /// `set` by composing the maps of such affine.apply ops with the integer
3173 /// set constraints.
3175  SmallVectorImpl<Value> &operands,
3176  bool composeAffineMin = false) {
3177  // We will simply reuse the API of the map composition by viewing the LHSs of
3178  // the equalities and inequalities of `set` as the affine exprs of an affine
3179  // map. Convert to equivalent map, compose, and convert back to set.
3180  auto map = AffineMap::get(set.getNumDims(), set.getNumSymbols(),
3181  set.getConstraints(), set.getContext());
3182  // Check if any composition is possible.
3183  if (llvm::none_of(operands,
3184  [](Value v) { return v.getDefiningOp<AffineApplyOp>(); }))
3185  return;
3186 
3187  composeAffineMapAndOperands(&map, &operands, composeAffineMin);
3188  set = IntegerSet::get(map.getNumDims(), map.getNumSymbols(), map.getResults(),
3189  set.getEqFlags());
3190 }
3191 
3192 /// Canonicalize an affine if op's conditional (integer set + operands).
3193 LogicalResult AffineIfOp::fold(FoldAdaptor, SmallVectorImpl<OpFoldResult> &) {
3194  auto set = getIntegerSet();
3195  SmallVector<Value, 4> operands(getOperands());
3196  composeSetAndOperands(set, operands);
3197  canonicalizeSetAndOperands(&set, &operands);
3198 
3199  // Check if the canonicalization or composition led to any change.
3200  if (getIntegerSet() == set && llvm::equal(operands, getOperands()))
3201  return failure();
3202 
3203  setConditional(set, operands);
3204  return success();
3205 }
3206 
3207 void AffineIfOp::getCanonicalizationPatterns(RewritePatternSet &results,
3208  MLIRContext *context) {
3209  results.add<SimplifyDeadElse, AlwaysTrueOrFalseIf>(context);
3210 }
3211 
3212 //===----------------------------------------------------------------------===//
3213 // AffineLoadOp
3214 //===----------------------------------------------------------------------===//
3215 
3216 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3217  AffineMap map, ValueRange operands) {
3218  assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
3219  result.addOperands(operands);
3220  if (map)
3221  result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3222  auto memrefType = llvm::cast<MemRefType>(operands[0].getType());
3223  result.types.push_back(memrefType.getElementType());
3224 }
3225 
3226 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3227  Value memref, AffineMap map, ValueRange mapOperands) {
3228  assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3229  result.addOperands(memref);
3230  result.addOperands(mapOperands);
3231  auto memrefType = llvm::cast<MemRefType>(memref.getType());
3232  result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3233  result.types.push_back(memrefType.getElementType());
3234 }
3235 
3236 void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3237  Value memref, ValueRange indices) {
3238  auto memrefType = llvm::cast<MemRefType>(memref.getType());
3239  int64_t rank = memrefType.getRank();
3240  // Create identity map for memrefs with at least one dimension or () -> ()
3241  // for zero-dimensional memrefs.
3242  auto map =
3243  rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3244  build(builder, result, memref, map, indices);
3245 }
3246 
3247 ParseResult AffineLoadOp::parse(OpAsmParser &parser, OperationState &result) {
3248  auto &builder = parser.getBuilder();
3249  auto indexTy = builder.getIndexType();
3250 
3251  MemRefType type;
3252  OpAsmParser::UnresolvedOperand memrefInfo;
3253  AffineMapAttr mapAttr;
3255  return failure(
3256  parser.parseOperand(memrefInfo) ||
3257  parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3258  AffineLoadOp::getMapAttrStrName(),
3259  result.attributes) ||
3260  parser.parseOptionalAttrDict(result.attributes) ||
3261  parser.parseColonType(type) ||
3262  parser.resolveOperand(memrefInfo, type, result.operands) ||
3263  parser.resolveOperands(mapOperands, indexTy, result.operands) ||
3264  parser.addTypeToList(type.getElementType(), result.types));
3265 }
3266 
3268  p << " " << getMemRef() << '[';
3269  if (AffineMapAttr mapAttr =
3270  (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()))
3271  p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3272  p << ']';
3273  p.printOptionalAttrDict((*this)->getAttrs(),
3274  /*elidedAttrs=*/{getMapAttrStrName()});
3275  p << " : " << getMemRefType();
3276 }
3277 
3278 /// Verify common indexing invariants of affine.load, affine.store,
3279 /// affine.vector_load and affine.vector_store.
3280 template <typename AffineMemOpTy>
3281 static LogicalResult
3282 verifyMemoryOpIndexing(AffineMemOpTy op, AffineMapAttr mapAttr,
3283  Operation::operand_range mapOperands,
3284  MemRefType memrefType, unsigned numIndexOperands) {
3285  AffineMap map = mapAttr.getValue();
3286  if (map.getNumResults() != memrefType.getRank())
3287  return op->emitOpError("affine map num results must equal memref rank");
3288  if (map.getNumInputs() != numIndexOperands)
3289  return op->emitOpError("expects as many subscripts as affine map inputs");
3290 
3291  for (auto idx : mapOperands) {
3292  if (!idx.getType().isIndex())
3293  return op->emitOpError("index to load must have 'index' type");
3294  }
3295  if (failed(verifyDimAndSymbolIdentifiers(op, mapOperands, map.getNumDims())))
3296  return failure();
3297 
3298  return success();
3299 }
3300 
3301 LogicalResult AffineLoadOp::verify() {
3302  auto memrefType = getMemRefType();
3303  if (getType() != memrefType.getElementType())
3304  return emitOpError("result type must match element type of memref");
3305 
3307  *this, (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()),
3308  getMapOperands(), memrefType,
3309  /*numIndexOperands=*/getNumOperands() - 1)))
3310  return failure();
3311 
3312  return success();
3313 }
3314 
3315 void AffineLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3316  MLIRContext *context) {
3317  results.add<SimplifyAffineOp<AffineLoadOp>>(context);
3318 }
3319 
3320 OpFoldResult AffineLoadOp::fold(FoldAdaptor adaptor) {
3321  /// load(memrefcast) -> load
3322  if (succeeded(memref::foldMemRefCast(*this)))
3323  return getResult();
3324 
3325  // Fold load from a global constant memref.
3326  auto getGlobalOp = getMemref().getDefiningOp<memref::GetGlobalOp>();
3327  if (!getGlobalOp)
3328  return {};
3329  // Get to the memref.global defining the symbol.
3330  auto *symbolTableOp = getGlobalOp->getParentWithTrait<OpTrait::SymbolTable>();
3331  if (!symbolTableOp)
3332  return {};
3333  auto global = dyn_cast_or_null<memref::GlobalOp>(
3334  SymbolTable::lookupSymbolIn(symbolTableOp, getGlobalOp.getNameAttr()));
3335  if (!global)
3336  return {};
3337 
3338  // Check if the global memref is a constant.
3339  auto cstAttr =
3340  dyn_cast_or_null<DenseElementsAttr>(global.getConstantInitValue());
3341  if (!cstAttr)
3342  return {};
3343  // If it's a splat constant, we can fold irrespective of indices.
3344  if (auto splatAttr = dyn_cast<SplatElementsAttr>(cstAttr))
3345  return splatAttr.getSplatValue<Attribute>();
3346  // Otherwise, we can fold only if we know the indices.
3347  if (!getAffineMap().isConstant())
3348  return {};
3349  auto indices = llvm::to_vector<4>(
3350  llvm::map_range(getAffineMap().getConstantResults(),
3351  [](int64_t v) -> uint64_t { return v; }));
3352  return cstAttr.getValues<Attribute>()[indices];
3353 }
3354 
3355 //===----------------------------------------------------------------------===//
3356 // AffineStoreOp
3357 //===----------------------------------------------------------------------===//
3358 
3359 void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
3360  Value valueToStore, Value memref, AffineMap map,
3361  ValueRange mapOperands) {
3362  assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3363  result.addOperands(valueToStore);
3364  result.addOperands(memref);
3365  result.addOperands(mapOperands);
3366  result.getOrAddProperties<Properties>().map = AffineMapAttr::get(map);
3367 }
3368 
3369 // Use identity map.
3370 void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
3371  Value valueToStore, Value memref,
3372  ValueRange indices) {
3373  auto memrefType = llvm::cast<MemRefType>(memref.getType());
3374  int64_t rank = memrefType.getRank();
3375  // Create identity map for memrefs with at least one dimension or () -> ()
3376  // for zero-dimensional memrefs.
3377  auto map =
3378  rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3379  build(builder, result, valueToStore, memref, map, indices);
3380 }
3381 
3382 ParseResult AffineStoreOp::parse(OpAsmParser &parser, OperationState &result) {
3383  auto indexTy = parser.getBuilder().getIndexType();
3384 
3385  MemRefType type;
3386  OpAsmParser::UnresolvedOperand storeValueInfo;
3387  OpAsmParser::UnresolvedOperand memrefInfo;
3388  AffineMapAttr mapAttr;
3390  return failure(parser.parseOperand(storeValueInfo) || parser.parseComma() ||
3391  parser.parseOperand(memrefInfo) ||
3392  parser.parseAffineMapOfSSAIds(
3393  mapOperands, mapAttr, AffineStoreOp::getMapAttrStrName(),
3394  result.attributes) ||
3395  parser.parseOptionalAttrDict(result.attributes) ||
3396  parser.parseColonType(type) ||
3397  parser.resolveOperand(storeValueInfo, type.getElementType(),
3398  result.operands) ||
3399  parser.resolveOperand(memrefInfo, type, result.operands) ||
3400  parser.resolveOperands(mapOperands, indexTy, result.operands));
3401 }
3402 
3404  p << " " << getValueToStore();
3405  p << ", " << getMemRef() << '[';
3406  if (AffineMapAttr mapAttr =
3407  (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()))
3408  p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3409  p << ']';
3410  p.printOptionalAttrDict((*this)->getAttrs(),
3411  /*elidedAttrs=*/{getMapAttrStrName()});
3412  p << " : " << getMemRefType();
3413 }
3414 
3415 LogicalResult AffineStoreOp::verify() {
3416  // The value to store must have the same type as memref element type.
3417  auto memrefType = getMemRefType();
3418  if (getValueToStore().getType() != memrefType.getElementType())
3419  return emitOpError(
3420  "value to store must have the same type as memref element type");
3421 
3423  *this, (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()),
3424  getMapOperands(), memrefType,
3425  /*numIndexOperands=*/getNumOperands() - 2)))
3426  return failure();
3427 
3428  return success();
3429 }
3430 
3431 void AffineStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3432  MLIRContext *context) {
3433  results.add<SimplifyAffineOp<AffineStoreOp>>(context);
3434 }
3435 
3436 LogicalResult AffineStoreOp::fold(FoldAdaptor adaptor,
3437  SmallVectorImpl<OpFoldResult> &results) {
3438  /// store(memrefcast) -> store
3439  return memref::foldMemRefCast(*this, getValueToStore());
3440 }
3441 
3442 //===----------------------------------------------------------------------===//
3443 // AffineMinMaxOpBase
3444 //===----------------------------------------------------------------------===//
3445 
3446 template <typename T>
3447 static LogicalResult verifyAffineMinMaxOp(T op) {
3448  // Verify that operand count matches affine map dimension and symbol count.
3449  if (op.getNumOperands() !=
3450  op.getMap().getNumDims() + op.getMap().getNumSymbols())
3451  return op.emitOpError(
3452  "operand count and affine map dimension and symbol count must match");
3453 
3454  if (op.getMap().getNumResults() == 0)
3455  return op.emitOpError("affine map expect at least one result");
3456  return success();
3457 }
3458 
3459 template <typename T>
3460 static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
3461  p << ' ' << op->getAttr(T::getMapAttrStrName());
3462  auto operands = op.getOperands();
3463  unsigned numDims = op.getMap().getNumDims();
3464  p << '(' << operands.take_front(numDims) << ')';
3465 
3466  if (operands.size() != numDims)
3467  p << '[' << operands.drop_front(numDims) << ']';
3468  p.printOptionalAttrDict(op->getAttrs(),
3469  /*elidedAttrs=*/{T::getMapAttrStrName()});
3470 }
3471 
3472 template <typename T>
3473 static ParseResult parseAffineMinMaxOp(OpAsmParser &parser,
3474  OperationState &result) {
3475  auto &builder = parser.getBuilder();
3476  auto indexType = builder.getIndexType();
3479  AffineMapAttr mapAttr;
3480  return failure(
3481  parser.parseAttribute(mapAttr, T::getMapAttrStrName(),
3482  result.attributes) ||
3483  parser.parseOperandList(dimInfos, OpAsmParser::Delimiter::Paren) ||
3484  parser.parseOperandList(symInfos,
3486  parser.parseOptionalAttrDict(result.attributes) ||
3487  parser.resolveOperands(dimInfos, indexType, result.operands) ||
3488  parser.resolveOperands(symInfos, indexType, result.operands) ||
3489  parser.addTypeToList(indexType, result.types));
3490 }
3491 
3492 /// Fold an affine min or max operation with the given operands. The operand
3493 /// list may contain nulls, which are interpreted as the operand not being a
3494 /// constant.
3495 template <typename T>
3497  static_assert(llvm::is_one_of<T, AffineMinOp, AffineMaxOp>::value,
3498  "expected affine min or max op");
3499 
3500  // Fold the affine map.
3501  // TODO: Fold more cases:
3502  // min(some_affine, some_affine + constant, ...), etc.
3503  SmallVector<int64_t, 2> results;
3504  auto foldedMap = op.getMap().partialConstantFold(operands, &results);
3505 
3506  if (foldedMap.getNumSymbols() == 1 && foldedMap.isSymbolIdentity())
3507  return op.getOperand(0);
3508 
3509  // If some of the map results are not constant, try changing the map in-place.
3510  if (results.empty()) {
3511  // If the map is the same, report that folding did not happen.
3512  if (foldedMap == op.getMap())
3513  return {};
3514  op->setAttr("map", AffineMapAttr::get(foldedMap));
3515  return op.getResult();
3516  }
3517 
3518  // Otherwise, completely fold the op into a constant.
3519  auto resultIt = std::is_same<T, AffineMinOp>::value
3520  ? llvm::min_element(results)
3521  : llvm::max_element(results);
3522  if (resultIt == results.end())
3523  return {};
3524  return IntegerAttr::get(IndexType::get(op.getContext()), *resultIt);
3525 }
3526 
3527 /// Remove duplicated expressions in affine min/max ops.
3528 template <typename T>
3531 
3532  LogicalResult matchAndRewrite(T affineOp,
3533  PatternRewriter &rewriter) const override {
3534  AffineMap oldMap = affineOp.getAffineMap();
3535 
3536  SmallVector<AffineExpr, 4> newExprs;
3537  for (AffineExpr expr : oldMap.getResults()) {
3538  // This is a linear scan over newExprs, but it should be fine given that
3539  // we typically just have a few expressions per op.
3540  if (!llvm::is_contained(newExprs, expr))
3541  newExprs.push_back(expr);
3542  }
3543 
3544  if (newExprs.size() == oldMap.getNumResults())
3545  return failure();
3546 
3547  auto newMap = AffineMap::get(oldMap.getNumDims(), oldMap.getNumSymbols(),
3548  newExprs, rewriter.getContext());
3549  rewriter.replaceOpWithNewOp<T>(affineOp, newMap, affineOp.getMapOperands());
3550 
3551  return success();
3552  }
3553 };
3554 
3555 /// Merge an affine min/max op to its consumers if its consumer is also an
3556 /// affine min/max op.
3557 ///
3558 /// This pattern requires the producer affine min/max op is bound to a
3559 /// dimension/symbol that is used as a standalone expression in the consumer
3560 /// affine op's map.
3561 ///
3562 /// For example, a pattern like the following:
3563 ///
3564 /// %0 = affine.min affine_map<()[s0] -> (s0 + 16, s0 * 8)> ()[%sym1]
3565 /// %1 = affine.min affine_map<(d0)[s0] -> (s0 + 4, d0)> (%0)[%sym2]
3566 ///
3567 /// Can be turned into:
3568 ///
3569 /// %1 = affine.min affine_map<
3570 /// ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1]
3571 template <typename T>
3574 
3575  LogicalResult matchAndRewrite(T affineOp,
3576  PatternRewriter &rewriter) const override {
3577  AffineMap oldMap = affineOp.getAffineMap();
3578  ValueRange dimOperands =
3579  affineOp.getMapOperands().take_front(oldMap.getNumDims());
3580  ValueRange symOperands =
3581  affineOp.getMapOperands().take_back(oldMap.getNumSymbols());
3582 
3583  auto newDimOperands = llvm::to_vector<8>(dimOperands);
3584  auto newSymOperands = llvm::to_vector<8>(symOperands);
3585  SmallVector<AffineExpr, 4> newExprs;
3586  SmallVector<T, 4> producerOps;
3587 
3588  // Go over each expression to see whether it's a single dimension/symbol
3589  // with the corresponding operand which is the result of another affine
3590  // min/max op. If So it can be merged into this affine op.
3591  for (AffineExpr expr : oldMap.getResults()) {
3592  if (auto symExpr = dyn_cast<AffineSymbolExpr>(expr)) {
3593  Value symValue = symOperands[symExpr.getPosition()];
3594  if (auto producerOp = symValue.getDefiningOp<T>()) {
3595  producerOps.push_back(producerOp);
3596  continue;
3597  }
3598  } else if (auto dimExpr = dyn_cast<AffineDimExpr>(expr)) {
3599  Value dimValue = dimOperands[dimExpr.getPosition()];
3600  if (auto producerOp = dimValue.getDefiningOp<T>()) {
3601  producerOps.push_back(producerOp);
3602  continue;
3603  }
3604  }
3605  // For the above cases we will remove the expression by merging the
3606  // producer affine min/max's affine expressions. Otherwise we need to
3607  // keep the existing expression.
3608  newExprs.push_back(expr);
3609  }
3610 
3611  if (producerOps.empty())
3612  return failure();
3613 
3614  unsigned numUsedDims = oldMap.getNumDims();
3615  unsigned numUsedSyms = oldMap.getNumSymbols();
3616 
3617  // Now go over all producer affine ops and merge their expressions.
3618  for (T producerOp : producerOps) {
3619  AffineMap producerMap = producerOp.getAffineMap();
3620  unsigned numProducerDims = producerMap.getNumDims();
3621  unsigned numProducerSyms = producerMap.getNumSymbols();
3622 
3623  // Collect all dimension/symbol values.
3624  ValueRange dimValues =
3625  producerOp.getMapOperands().take_front(numProducerDims);
3626  ValueRange symValues =
3627  producerOp.getMapOperands().take_back(numProducerSyms);
3628  newDimOperands.append(dimValues.begin(), dimValues.end());
3629  newSymOperands.append(symValues.begin(), symValues.end());
3630 
3631  // For expressions we need to shift to avoid overlap.
3632  for (AffineExpr expr : producerMap.getResults()) {
3633  newExprs.push_back(expr.shiftDims(numProducerDims, numUsedDims)
3634  .shiftSymbols(numProducerSyms, numUsedSyms));
3635  }
3636 
3637  numUsedDims += numProducerDims;
3638  numUsedSyms += numProducerSyms;
3639  }
3640 
3641  auto newMap = AffineMap::get(numUsedDims, numUsedSyms, newExprs,
3642  rewriter.getContext());
3643  auto newOperands =
3644  llvm::to_vector<8>(llvm::concat<Value>(newDimOperands, newSymOperands));
3645  rewriter.replaceOpWithNewOp<T>(affineOp, newMap, newOperands);
3646 
3647  return success();
3648  }
3649 };
3650 
3651 /// Canonicalize the result expression order of an affine map and return success
3652 /// if the order changed.
3653 ///
3654 /// The function flattens the map's affine expressions to coefficient arrays and
3655 /// sorts them in lexicographic order. A coefficient array contains a multiplier
3656 /// for every dimension/symbol and a constant term. The canonicalization fails
3657 /// if a result expression is not pure or if the flattening requires local
3658 /// variables that, unlike dimensions and symbols, have no global order.
3659 static LogicalResult canonicalizeMapExprAndTermOrder(AffineMap &map) {
3660  SmallVector<SmallVector<int64_t>> flattenedExprs;
3661  for (const AffineExpr &resultExpr : map.getResults()) {
3662  // Fail if the expression is not pure.
3663  if (!resultExpr.isPureAffine())
3664  return failure();
3665 
3666  SimpleAffineExprFlattener flattener(map.getNumDims(), map.getNumSymbols());
3667  auto flattenResult = flattener.walkPostOrder(resultExpr);
3668  if (failed(flattenResult))
3669  return failure();
3670 
3671  // Fail if the flattened expression has local variables.
3672  if (flattener.operandExprStack.back().size() !=
3673  map.getNumDims() + map.getNumSymbols() + 1)
3674  return failure();
3675 
3676  flattenedExprs.emplace_back(flattener.operandExprStack.back().begin(),
3677  flattener.operandExprStack.back().end());
3678  }
3679 
3680  // Fail if sorting is not necessary.
3681  if (llvm::is_sorted(flattenedExprs))
3682  return failure();
3683 
3684  // Reorder the result expressions according to their flattened form.
3685  SmallVector<unsigned> resultPermutation =
3686  llvm::to_vector(llvm::seq<unsigned>(0, map.getNumResults()));
3687  llvm::sort(resultPermutation, [&](unsigned lhs, unsigned rhs) {
3688  return flattenedExprs[lhs] < flattenedExprs[rhs];
3689  });
3690  SmallVector<AffineExpr> newExprs;
3691  for (unsigned idx : resultPermutation)
3692  newExprs.push_back(map.getResult(idx));
3693 
3694  map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), newExprs,
3695  map.getContext());
3696  return success();
3697 }
3698 
3699 /// Canonicalize the affine map result expression order of an affine min/max
3700 /// operation.
3701 ///
3702 /// The pattern calls `canonicalizeMapExprAndTermOrder` to order the result
3703 /// expressions and replaces the operation if the order changed.
3704 ///
3705 /// For example, the following operation:
3706 ///
3707 /// %0 = affine.min affine_map<(d0, d1) -> (d0 + d1, d1 + 16, 32)> (%i0, %i1)
3708 ///
3709 /// Turns into:
3710 ///
3711 /// %0 = affine.min affine_map<(d0, d1) -> (32, d1 + 16, d0 + d1)> (%i0, %i1)
3712 template <typename T>
3715 
3716  LogicalResult matchAndRewrite(T affineOp,
3717  PatternRewriter &rewriter) const override {
3718  AffineMap map = affineOp.getAffineMap();
3720  return failure();
3721  rewriter.replaceOpWithNewOp<T>(affineOp, map, affineOp.getMapOperands());
3722  return success();
3723  }
3724 };
3725 
3726 template <typename T>
3729 
3730  LogicalResult matchAndRewrite(T affineOp,
3731  PatternRewriter &rewriter) const override {
3732  if (affineOp.getMap().getNumResults() != 1)
3733  return failure();
3734  rewriter.replaceOpWithNewOp<AffineApplyOp>(affineOp, affineOp.getMap(),
3735  affineOp.getOperands());
3736  return success();
3737  }
3738 };
3739 
3740 //===----------------------------------------------------------------------===//
3741 // AffineMinOp
3742 //===----------------------------------------------------------------------===//
3743 //
3744 // %0 = affine.min (d0) -> (1000, d0 + 512) (%i0)
3745 //
3746 
3747 OpFoldResult AffineMinOp::fold(FoldAdaptor adaptor) {
3748  return foldMinMaxOp(*this, adaptor.getOperands());
3749 }
3750 
3751 void AffineMinOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3752  MLIRContext *context) {
3755  MergeAffineMinMaxOp<AffineMinOp>, SimplifyAffineOp<AffineMinOp>,
3757  context);
3758 }
3759 
3760 LogicalResult AffineMinOp::verify() { return verifyAffineMinMaxOp(*this); }
3761 
3762 ParseResult AffineMinOp::parse(OpAsmParser &parser, OperationState &result) {
3763  return parseAffineMinMaxOp<AffineMinOp>(parser, result);
3764 }
3765 
3766 void AffineMinOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
3767 
3768 //===----------------------------------------------------------------------===//
3769 // AffineMaxOp
3770 //===----------------------------------------------------------------------===//
3771 //
3772 // %0 = affine.max (d0) -> (1000, d0 + 512) (%i0)
3773 //
3774 
3775 OpFoldResult AffineMaxOp::fold(FoldAdaptor adaptor) {
3776  return foldMinMaxOp(*this, adaptor.getOperands());
3777 }
3778 
3779 void AffineMaxOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3780  MLIRContext *context) {
3783  MergeAffineMinMaxOp<AffineMaxOp>, SimplifyAffineOp<AffineMaxOp>,
3785  context);
3786 }
3787 
3788 LogicalResult AffineMaxOp::verify() { return verifyAffineMinMaxOp(*this); }
3789 
3790 ParseResult AffineMaxOp::parse(OpAsmParser &parser, OperationState &result) {
3791  return parseAffineMinMaxOp<AffineMaxOp>(parser, result);
3792 }
3793 
3794 void AffineMaxOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
3795 
3796 //===----------------------------------------------------------------------===//
3797 // AffinePrefetchOp
3798 //===----------------------------------------------------------------------===//
3799 
3800 //
3801 // affine.prefetch %0[%i, %j + 5], read, locality<3>, data : memref<400x400xi32>
3802 //
3803 ParseResult AffinePrefetchOp::parse(OpAsmParser &parser,
3804  OperationState &result) {
3805  auto &builder = parser.getBuilder();
3806  auto indexTy = builder.getIndexType();
3807 
3808  MemRefType type;
3809  OpAsmParser::UnresolvedOperand memrefInfo;
3810  IntegerAttr hintInfo;
3811  auto i32Type = parser.getBuilder().getIntegerType(32);
3812  StringRef readOrWrite, cacheType;
3813 
3814  AffineMapAttr mapAttr;
3816  if (parser.parseOperand(memrefInfo) ||
3817  parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3818  AffinePrefetchOp::getMapAttrStrName(),
3819  result.attributes) ||
3820  parser.parseComma() || parser.parseKeyword(&readOrWrite) ||
3821  parser.parseComma() || parser.parseKeyword("locality") ||
3822  parser.parseLess() ||
3823  parser.parseAttribute(hintInfo, i32Type,
3824  AffinePrefetchOp::getLocalityHintAttrStrName(),
3825  result.attributes) ||
3826  parser.parseGreater() || parser.parseComma() ||
3827  parser.parseKeyword(&cacheType) ||
3828  parser.parseOptionalAttrDict(result.attributes) ||
3829  parser.parseColonType(type) ||
3830  parser.resolveOperand(memrefInfo, type, result.operands) ||
3831  parser.resolveOperands(mapOperands, indexTy, result.operands))
3832  return failure();
3833 
3834  if (readOrWrite != "read" && readOrWrite != "write")
3835  return parser.emitError(parser.getNameLoc(),
3836  "rw specifier has to be 'read' or 'write'");
3837  result.addAttribute(AffinePrefetchOp::getIsWriteAttrStrName(),
3838  parser.getBuilder().getBoolAttr(readOrWrite == "write"));
3839 
3840  if (cacheType != "data" && cacheType != "instr")
3841  return parser.emitError(parser.getNameLoc(),
3842  "cache type has to be 'data' or 'instr'");
3843 
3844  result.addAttribute(AffinePrefetchOp::getIsDataCacheAttrStrName(),
3845  parser.getBuilder().getBoolAttr(cacheType == "data"));
3846 
3847  return success();
3848 }
3849 
3851  p << " " << getMemref() << '[';
3852  AffineMapAttr mapAttr =
3853  (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName());
3854  if (mapAttr)
3855  p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3856  p << ']' << ", " << (getIsWrite() ? "write" : "read") << ", "
3857  << "locality<" << getLocalityHint() << ">, "
3858  << (getIsDataCache() ? "data" : "instr");
3860  (*this)->getAttrs(),
3861  /*elidedAttrs=*/{getMapAttrStrName(), getLocalityHintAttrStrName(),
3862  getIsDataCacheAttrStrName(), getIsWriteAttrStrName()});
3863  p << " : " << getMemRefType();
3864 }
3865 
3866 LogicalResult AffinePrefetchOp::verify() {
3867  auto mapAttr = (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName());
3868  if (mapAttr) {
3869  AffineMap map = mapAttr.getValue();
3870  if (map.getNumResults() != getMemRefType().getRank())
3871  return emitOpError("affine.prefetch affine map num results must equal"
3872  " memref rank");
3873  if (map.getNumInputs() + 1 != getNumOperands())
3874  return emitOpError("too few operands");
3875  } else {
3876  if (getNumOperands() != 1)
3877  return emitOpError("too few operands");
3878  }
3879 
3880  Region *scope = getAffineScope(*this);
3881  for (auto idx : getMapOperands()) {
3882  if (!isValidAffineIndexOperand(idx, scope))
3883  return emitOpError(
3884  "index must be a valid dimension or symbol identifier");
3885  }
3886  return success();
3887 }
3888 
3889 void AffinePrefetchOp::getCanonicalizationPatterns(RewritePatternSet &results,
3890  MLIRContext *context) {
3891  // prefetch(memrefcast) -> prefetch
3892  results.add<SimplifyAffineOp<AffinePrefetchOp>>(context);
3893 }
3894 
3895 LogicalResult AffinePrefetchOp::fold(FoldAdaptor adaptor,
3896  SmallVectorImpl<OpFoldResult> &results) {
3897  /// prefetch(memrefcast) -> prefetch
3898  return memref::foldMemRefCast(*this);
3899 }
3900 
3901 //===----------------------------------------------------------------------===//
3902 // AffineParallelOp
3903 //===----------------------------------------------------------------------===//
3904 
3905 void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
3906  TypeRange resultTypes,
3907  ArrayRef<arith::AtomicRMWKind> reductions,
3908  ArrayRef<int64_t> ranges) {
3909  SmallVector<AffineMap> lbs(ranges.size(), builder.getConstantAffineMap(0));
3910  auto ubs = llvm::to_vector<4>(llvm::map_range(ranges, [&](int64_t value) {
3911  return builder.getConstantAffineMap(value);
3912  }));
3913  SmallVector<int64_t> steps(ranges.size(), 1);
3914  build(builder, result, resultTypes, reductions, lbs, /*lbArgs=*/{}, ubs,
3915  /*ubArgs=*/{}, steps);
3916 }
3917 
3918 void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
3919  TypeRange resultTypes,
3920  ArrayRef<arith::AtomicRMWKind> reductions,
3921  ArrayRef<AffineMap> lbMaps, ValueRange lbArgs,
3922  ArrayRef<AffineMap> ubMaps, ValueRange ubArgs,
3923  ArrayRef<int64_t> steps) {
3924  assert(llvm::all_of(lbMaps,
3925  [lbMaps](AffineMap m) {
3926  return m.getNumDims() == lbMaps[0].getNumDims() &&
3927  m.getNumSymbols() == lbMaps[0].getNumSymbols();
3928  }) &&
3929  "expected all lower bounds maps to have the same number of dimensions "
3930  "and symbols");
3931  assert(llvm::all_of(ubMaps,
3932  [ubMaps](AffineMap m) {
3933  return m.getNumDims() == ubMaps[0].getNumDims() &&
3934  m.getNumSymbols() == ubMaps[0].getNumSymbols();
3935  }) &&
3936  "expected all upper bounds maps to have the same number of dimensions "
3937  "and symbols");
3938  assert((lbMaps.empty() || lbMaps[0].getNumInputs() == lbArgs.size()) &&
3939  "expected lower bound maps to have as many inputs as lower bound "
3940  "operands");
3941  assert((ubMaps.empty() || ubMaps[0].getNumInputs() == ubArgs.size()) &&
3942  "expected upper bound maps to have as many inputs as upper bound "
3943  "operands");
3944 
3945  OpBuilder::InsertionGuard guard(builder);
3946  result.addTypes(resultTypes);
3947 
3948  // Convert the reductions to integer attributes.
3949  SmallVector<Attribute, 4> reductionAttrs;
3950  for (arith::AtomicRMWKind reduction : reductions)
3951  reductionAttrs.push_back(
3952  builder.getI64IntegerAttr(static_cast<int64_t>(reduction)));
3953  result.addAttribute(getReductionsAttrStrName(),
3954  builder.getArrayAttr(reductionAttrs));
3955 
3956  // Concatenates maps defined in the same input space (same dimensions and
3957  // symbols), assumes there is at least one map.
3958  auto concatMapsSameInput = [&builder](ArrayRef<AffineMap> maps,
3959  SmallVectorImpl<int32_t> &groups) {
3960  if (maps.empty())
3961  return AffineMap::get(builder.getContext());
3963  groups.reserve(groups.size() + maps.size());
3964  exprs.reserve(maps.size());
3965  for (AffineMap m : maps) {
3966  llvm::append_range(exprs, m.getResults());
3967  groups.push_back(m.getNumResults());
3968  }
3969  return AffineMap::get(maps[0].getNumDims(), maps[0].getNumSymbols(), exprs,
3970  maps[0].getContext());
3971  };
3972 
3973  // Set up the bounds.
3974  SmallVector<int32_t> lbGroups, ubGroups;
3975  AffineMap lbMap = concatMapsSameInput(lbMaps, lbGroups);
3976  AffineMap ubMap = concatMapsSameInput(ubMaps, ubGroups);
3977  result.addAttribute(getLowerBoundsMapAttrStrName(),
3978  AffineMapAttr::get(lbMap));
3979  result.addAttribute(getLowerBoundsGroupsAttrStrName(),
3980  builder.getI32TensorAttr(lbGroups));
3981  result.addAttribute(getUpperBoundsMapAttrStrName(),
3982  AffineMapAttr::get(ubMap));
3983  result.addAttribute(getUpperBoundsGroupsAttrStrName(),
3984  builder.getI32TensorAttr(ubGroups));
3985  result.addAttribute(getStepsAttrStrName(), builder.getI64ArrayAttr(steps));
3986  result.addOperands(lbArgs);
3987  result.addOperands(ubArgs);
3988 
3989  // Create a region and a block for the body.
3990  auto *bodyRegion = result.addRegion();
3991  Block *body = builder.createBlock(bodyRegion);
3992 
3993  // Add all the block arguments.
3994  for (unsigned i = 0, e = steps.size(); i < e; ++i)
3995  body->addArgument(IndexType::get(builder.getContext()), result.location);
3996  if (resultTypes.empty())
3997  ensureTerminator(*bodyRegion, builder, result.location);
3998 }
3999 
4000 SmallVector<Region *> AffineParallelOp::getLoopRegions() {
4001  return {&getRegion()};
4002 }
4003 
4004 unsigned AffineParallelOp::getNumDims() { return getSteps().size(); }
4005 
4006 AffineParallelOp::operand_range AffineParallelOp::getLowerBoundsOperands() {
4007  return getOperands().take_front(getLowerBoundsMap().getNumInputs());
4008 }
4009 
4010 AffineParallelOp::operand_range AffineParallelOp::getUpperBoundsOperands() {
4011  return getOperands().drop_front(getLowerBoundsMap().getNumInputs());
4012 }
4013 
4014 AffineMap AffineParallelOp::getLowerBoundMap(unsigned pos) {
4015  auto values = getLowerBoundsGroups().getValues<int32_t>();
4016  unsigned start = 0;
4017  for (unsigned i = 0; i < pos; ++i)
4018  start += values[i];
4019  return getLowerBoundsMap().getSliceMap(start, values[pos]);
4020 }
4021 
4022 AffineMap AffineParallelOp::getUpperBoundMap(unsigned pos) {
4023  auto values = getUpperBoundsGroups().getValues<int32_t>();
4024  unsigned start = 0;
4025  for (unsigned i = 0; i < pos; ++i)
4026  start += values[i];
4027  return getUpperBoundsMap().getSliceMap(start, values[pos]);
4028 }
4029 
4030 AffineValueMap AffineParallelOp::getLowerBoundsValueMap() {
4031  return AffineValueMap(getLowerBoundsMap(), getLowerBoundsOperands());
4032 }
4033 
4034 AffineValueMap AffineParallelOp::getUpperBoundsValueMap() {
4035  return AffineValueMap(getUpperBoundsMap(), getUpperBoundsOperands());
4036 }
4037 
4038 std::optional<SmallVector<int64_t, 8>> AffineParallelOp::getConstantRanges() {
4039  if (hasMinMaxBounds())
4040  return std::nullopt;
4041 
4042  // Try to convert all the ranges to constant expressions.
4044  AffineValueMap rangesValueMap;
4045  AffineValueMap::difference(getUpperBoundsValueMap(), getLowerBoundsValueMap(),
4046  &rangesValueMap);
4047  out.reserve(rangesValueMap.getNumResults());
4048  for (unsigned i = 0, e = rangesValueMap.getNumResults(); i < e; ++i) {
4049  auto expr = rangesValueMap.getResult(i);
4050  auto cst = dyn_cast<AffineConstantExpr>(expr);
4051  if (!cst)
4052  return std::nullopt;
4053  out.push_back(cst.getValue());
4054  }
4055  return out;
4056 }
4057 
4058 Block *AffineParallelOp::getBody() { return &getRegion().front(); }
4059 
4060 OpBuilder AffineParallelOp::getBodyBuilder() {
4061  return OpBuilder(getBody(), std::prev(getBody()->end()));
4062 }
4063 
4064 void AffineParallelOp::setLowerBounds(ValueRange lbOperands, AffineMap map) {
4065  assert(lbOperands.size() == map.getNumInputs() &&
4066  "operands to map must match number of inputs");
4067 
4068  auto ubOperands = getUpperBoundsOperands();
4069 
4070  SmallVector<Value, 4> newOperands(lbOperands);
4071  newOperands.append(ubOperands.begin(), ubOperands.end());
4072  (*this)->setOperands(newOperands);
4073 
4074  setLowerBoundsMapAttr(AffineMapAttr::get(map));
4075 }
4076 
4077 void AffineParallelOp::setUpperBounds(ValueRange ubOperands, AffineMap map) {
4078  assert(ubOperands.size() == map.getNumInputs() &&
4079  "operands to map must match number of inputs");
4080 
4081  SmallVector<Value, 4> newOperands(getLowerBoundsOperands());
4082  newOperands.append(ubOperands.begin(), ubOperands.end());
4083  (*this)->setOperands(newOperands);
4084 
4085  setUpperBoundsMapAttr(AffineMapAttr::get(map));
4086 }
4087 
4088 void AffineParallelOp::setSteps(ArrayRef<int64_t> newSteps) {
4089  setStepsAttr(getBodyBuilder().getI64ArrayAttr(newSteps));
4090 }
4091 
4092 // check whether resultType match op or not in affine.parallel
4093 static bool isResultTypeMatchAtomicRMWKind(Type resultType,
4094  arith::AtomicRMWKind op) {
4095  switch (op) {
4096  case arith::AtomicRMWKind::addf:
4097  return isa<FloatType>(resultType);
4098  case arith::AtomicRMWKind::addi:
4099  return isa<IntegerType>(resultType);
4100  case arith::AtomicRMWKind::assign:
4101  return true;
4102  case arith::AtomicRMWKind::mulf:
4103  return isa<FloatType>(resultType);
4104  case arith::AtomicRMWKind::muli:
4105  return isa<IntegerType>(resultType);
4106  case arith::AtomicRMWKind::maximumf:
4107  return isa<FloatType>(resultType);
4108  case arith::AtomicRMWKind::minimumf:
4109  return isa<FloatType>(resultType);
4110  case arith::AtomicRMWKind::maxs: {
4111  auto intType = dyn_cast<IntegerType>(resultType);
4112  return intType && intType.isSigned();
4113  }
4114  case arith::AtomicRMWKind::mins: {
4115  auto intType = dyn_cast<IntegerType>(resultType);
4116  return intType && intType.isSigned();
4117  }
4118  case arith::AtomicRMWKind::maxu: {
4119  auto intType = dyn_cast<IntegerType>(resultType);
4120  return intType && intType.isUnsigned();
4121  }
4122  case arith::AtomicRMWKind::minu: {
4123  auto intType = dyn_cast<IntegerType>(resultType);
4124  return intType && intType.isUnsigned();
4125  }
4126  case arith::AtomicRMWKind::ori:
4127  return isa<IntegerType>(resultType);
4128  case arith::AtomicRMWKind::andi:
4129  return isa<IntegerType>(resultType);
4130  default:
4131  return false;
4132  }
4133 }
4134 
4135 LogicalResult AffineParallelOp::verify() {
4136  auto numDims = getNumDims();
4137  if (getLowerBoundsGroups().getNumElements() != numDims ||
4138  getUpperBoundsGroups().getNumElements() != numDims ||
4139  getSteps().size() != numDims || getBody()->getNumArguments() != numDims) {
4140  return emitOpError() << "the number of region arguments ("
4141  << getBody()->getNumArguments()
4142  << ") and the number of map groups for lower ("
4143  << getLowerBoundsGroups().getNumElements()
4144  << ") and upper bound ("
4145  << getUpperBoundsGroups().getNumElements()
4146  << "), and the number of steps (" << getSteps().size()
4147  << ") must all match";
4148  }
4149 
4150  unsigned expectedNumLBResults = 0;
4151  for (APInt v : getLowerBoundsGroups()) {
4152  unsigned results = v.getZExtValue();
4153  if (results == 0)
4154  return emitOpError()
4155  << "expected lower bound map to have at least one result";
4156  expectedNumLBResults += results;
4157  }
4158  if (expectedNumLBResults != getLowerBoundsMap().getNumResults())
4159  return emitOpError() << "expected lower bounds map to have "
4160  << expectedNumLBResults << " results";
4161  unsigned expectedNumUBResults = 0;
4162  for (APInt v : getUpperBoundsGroups()) {
4163  unsigned results = v.getZExtValue();
4164  if (results == 0)
4165  return emitOpError()
4166  << "expected upper bound map to have at least one result";
4167  expectedNumUBResults += results;
4168  }
4169  if (expectedNumUBResults != getUpperBoundsMap().getNumResults())
4170  return emitOpError() << "expected upper bounds map to have "
4171  << expectedNumUBResults << " results";
4172 
4173  if (getReductions().size() != getNumResults())
4174  return emitOpError("a reduction must be specified for each output");
4175 
4176  // Verify reduction ops are all valid and each result type matches reduction
4177  // ops
4178  for (auto it : llvm::enumerate((getReductions()))) {
4179  Attribute attr = it.value();
4180  auto intAttr = dyn_cast<IntegerAttr>(attr);
4181  if (!intAttr || !arith::symbolizeAtomicRMWKind(intAttr.getInt()))
4182  return emitOpError("invalid reduction attribute");
4183  auto kind = arith::symbolizeAtomicRMWKind(intAttr.getInt()).value();
4184  if (!isResultTypeMatchAtomicRMWKind(getResult(it.index()).getType(), kind))
4185  return emitOpError("result type cannot match reduction attribute");
4186  }
4187 
4188  // Verify that the bound operands are valid dimension/symbols.
4189  /// Lower bounds.
4190  if (failed(verifyDimAndSymbolIdentifiers(*this, getLowerBoundsOperands(),
4191  getLowerBoundsMap().getNumDims())))
4192  return failure();
4193  /// Upper bounds.
4194  if (failed(verifyDimAndSymbolIdentifiers(*this, getUpperBoundsOperands(),
4195  getUpperBoundsMap().getNumDims())))
4196  return failure();
4197  return success();
4198 }
4199 
4200 LogicalResult AffineValueMap::canonicalize() {
4201  SmallVector<Value, 4> newOperands{operands};
4202  auto newMap = getAffineMap();
4203  composeAffineMapAndOperands(&newMap, &newOperands);
4204  if (newMap == getAffineMap() && newOperands == operands)
4205  return failure();
4206  reset(newMap, newOperands);
4207  return success();
4208 }
4209 
4210 /// Canonicalize the bounds of the given loop.
4211 static LogicalResult canonicalizeLoopBounds(AffineParallelOp op) {
4212  AffineValueMap lb = op.getLowerBoundsValueMap();
4213  bool lbCanonicalized = succeeded(lb.canonicalize());
4214 
4215  AffineValueMap ub = op.getUpperBoundsValueMap();
4216  bool ubCanonicalized = succeeded(ub.canonicalize());
4217 
4218  // Any canonicalization change always leads to updated map(s).
4219  if (!lbCanonicalized && !ubCanonicalized)
4220  return failure();
4221 
4222  if (lbCanonicalized)
4223  op.setLowerBounds(lb.getOperands(), lb.getAffineMap());
4224  if (ubCanonicalized)
4225  op.setUpperBounds(ub.getOperands(), ub.getAffineMap());
4226 
4227  return success();
4228 }
4229 
4230 LogicalResult AffineParallelOp::fold(FoldAdaptor adaptor,
4231  SmallVectorImpl<OpFoldResult> &results) {
4232  return canonicalizeLoopBounds(*this);
4233 }
4234 
4235 /// Prints a lower(upper) bound of an affine parallel loop with max(min)
4236 /// conditions in it. `mapAttr` is a flat list of affine expressions and `group`
4237 /// identifies which of the those expressions form max/min groups. `operands`
4238 /// are the SSA values of dimensions and symbols and `keyword` is either "min"
4239 /// or "max".
4240 static void printMinMaxBound(OpAsmPrinter &p, AffineMapAttr mapAttr,
4241  DenseIntElementsAttr group, ValueRange operands,
4242  StringRef keyword) {
4243  AffineMap map = mapAttr.getValue();
4244  unsigned numDims = map.getNumDims();
4245  ValueRange dimOperands = operands.take_front(numDims);
4246  ValueRange symOperands = operands.drop_front(numDims);
4247  unsigned start = 0;
4248  for (llvm::APInt groupSize : group) {
4249  if (start != 0)
4250  p << ", ";
4251 
4252  unsigned size = groupSize.getZExtValue();
4253  if (size == 1) {
4254  p.printAffineExprOfSSAIds(map.getResult(start), dimOperands, symOperands);
4255  ++start;
4256  } else {
4257  p << keyword << '(';
4258  AffineMap submap = map.getSliceMap(start, size);
4259  p.printAffineMapOfSSAIds(AffineMapAttr::get(submap), operands);
4260  p << ')';
4261  start += size;
4262  }
4263  }
4264 }
4265 
4267  p << " (" << getBody()->getArguments() << ") = (";
4268  printMinMaxBound(p, getLowerBoundsMapAttr(), getLowerBoundsGroupsAttr(),
4269  getLowerBoundsOperands(), "max");
4270  p << ") to (";
4271  printMinMaxBound(p, getUpperBoundsMapAttr(), getUpperBoundsGroupsAttr(),
4272  getUpperBoundsOperands(), "min");
4273  p << ')';
4274  SmallVector<int64_t, 8> steps = getSteps();
4275  bool elideSteps = llvm::all_of(steps, [](int64_t step) { return step == 1; });
4276  if (!elideSteps) {
4277  p << " step (";
4278  llvm::interleaveComma(steps, p);
4279  p << ')';
4280  }
4281  if (getNumResults()) {
4282  p << " reduce (";
4283  llvm::interleaveComma(getReductions(), p, [&](auto &attr) {
4284  arith::AtomicRMWKind sym = *arith::symbolizeAtomicRMWKind(
4285  llvm::cast<IntegerAttr>(attr).getInt());
4286  p << "\"" << arith::stringifyAtomicRMWKind(sym) << "\"";
4287  });
4288  p << ") -> (" << getResultTypes() << ")";
4289  }
4290 
4291  p << ' ';
4292  p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
4293  /*printBlockTerminators=*/getNumResults());
4295  (*this)->getAttrs(),
4296  /*elidedAttrs=*/{AffineParallelOp::getReductionsAttrStrName(),
4297  AffineParallelOp::getLowerBoundsMapAttrStrName(),
4298  AffineParallelOp::getLowerBoundsGroupsAttrStrName(),
4299  AffineParallelOp::getUpperBoundsMapAttrStrName(),
4300  AffineParallelOp::getUpperBoundsGroupsAttrStrName(),
4301  AffineParallelOp::getStepsAttrStrName()});
4302 }
4303 
4304 /// Given a list of lists of parsed operands, populates `uniqueOperands` with
4305 /// unique operands. Also populates `replacements with affine expressions of
4306 /// `kind` that can be used to update affine maps previously accepting a
4307 /// `operands` to accept `uniqueOperands` instead.
4309  OpAsmParser &parser,
4311  SmallVectorImpl<Value> &uniqueOperands,
4314  "expected operands to be dim or symbol expression");
4315 
4316  Type indexType = parser.getBuilder().getIndexType();
4317  for (const auto &list : operands) {
4318  SmallVector<Value> valueOperands;
4319  if (parser.resolveOperands(list, indexType, valueOperands))
4320  return failure();
4321  for (Value operand : valueOperands) {
4322  unsigned pos = std::distance(uniqueOperands.begin(),
4323  llvm::find(uniqueOperands, operand));
4324  if (pos == uniqueOperands.size())
4325  uniqueOperands.push_back(operand);
4326  replacements.push_back(
4328  ? getAffineDimExpr(pos, parser.getContext())
4329  : getAffineSymbolExpr(pos, parser.getContext()));
4330  }
4331  }
4332  return success();
4333 }
4334 
4335 namespace {
4336 enum class MinMaxKind { Min, Max };
4337 } // namespace
4338 
4339 /// Parses an affine map that can contain a min/max for groups of its results,
4340 /// e.g., max(expr-1, expr-2), expr-3, max(expr-4, expr-5, expr-6). Populates
4341 /// `result` attributes with the map (flat list of expressions) and the grouping
4342 /// (list of integers that specify how many expressions to put into each
4343 /// min/max) attributes. Deduplicates repeated operands.
4344 ///
4345 /// parallel-bound ::= `(` parallel-group-list `)`
4346 /// parallel-group-list ::= parallel-group (`,` parallel-group-list)?
4347 /// parallel-group ::= simple-group | min-max-group
4348 /// simple-group ::= expr-of-ssa-ids
4349 /// min-max-group ::= ( `min` | `max` ) `(` expr-of-ssa-ids-list `)`
4350 /// expr-of-ssa-ids-list ::= expr-of-ssa-ids (`,` expr-of-ssa-id-list)?
4351 ///
4352 /// Examples:
4353 /// (%0, min(%1 + %2, %3), %4, min(%5 floordiv 32, %6))
4354 /// (%0, max(%1 - 2 * %2))
4355 static ParseResult parseAffineMapWithMinMax(OpAsmParser &parser,
4356  OperationState &result,
4357  MinMaxKind kind) {
4358  // Using `const` not `constexpr` below to workaround a MSVC optimizer bug,
4359  // see: https://reviews.llvm.org/D134227#3821753
4360  const llvm::StringLiteral tmpAttrStrName = "__pseudo_bound_map";
4361 
4362  StringRef mapName = kind == MinMaxKind::Min
4363  ? AffineParallelOp::getUpperBoundsMapAttrStrName()
4364  : AffineParallelOp::getLowerBoundsMapAttrStrName();
4365  StringRef groupsName =
4366  kind == MinMaxKind::Min
4367  ? AffineParallelOp::getUpperBoundsGroupsAttrStrName()
4368  : AffineParallelOp::getLowerBoundsGroupsAttrStrName();
4369 
4370  if (failed(parser.parseLParen()))
4371  return failure();
4372 
4373  if (succeeded(parser.parseOptionalRParen())) {
4374  result.addAttribute(
4375  mapName, AffineMapAttr::get(parser.getBuilder().getEmptyAffineMap()));
4376  result.addAttribute(groupsName, parser.getBuilder().getI32TensorAttr({}));
4377  return success();
4378  }
4379 
4380  SmallVector<AffineExpr> flatExprs;
4383  SmallVector<int32_t> numMapsPerGroup;
4385  auto parseOperands = [&]() {
4386  if (succeeded(parser.parseOptionalKeyword(
4387  kind == MinMaxKind::Min ? "min" : "max"))) {
4388  mapOperands.clear();
4389  AffineMapAttr map;
4390  if (failed(parser.parseAffineMapOfSSAIds(mapOperands, map, tmpAttrStrName,
4391  result.attributes,
4393  return failure();
4394  result.attributes.erase(tmpAttrStrName);
4395  llvm::append_range(flatExprs, map.getValue().getResults());
4396  auto operandsRef = llvm::ArrayRef(mapOperands);
4397  auto dimsRef = operandsRef.take_front(map.getValue().getNumDims());
4399  auto symsRef = operandsRef.drop_front(map.getValue().getNumDims());
4401  flatDimOperands.append(map.getValue().getNumResults(), dims);
4402  flatSymOperands.append(map.getValue().getNumResults(), syms);
4403  numMapsPerGroup.push_back(map.getValue().getNumResults());
4404  } else {
4405  if (failed(parser.parseAffineExprOfSSAIds(flatDimOperands.emplace_back(),
4406  flatSymOperands.emplace_back(),
4407  flatExprs.emplace_back())))
4408  return failure();
4409  numMapsPerGroup.push_back(1);
4410  }
4411  return success();
4412  };
4413  if (parser.parseCommaSeparatedList(parseOperands) || parser.parseRParen())
4414  return failure();
4415 
4416  unsigned totalNumDims = 0;
4417  unsigned totalNumSyms = 0;
4418  for (unsigned i = 0, e = flatExprs.size(); i < e; ++i) {
4419  unsigned numDims = flatDimOperands[i].size();
4420  unsigned numSyms = flatSymOperands[i].size();
4421  flatExprs[i] = flatExprs[i]
4422  .shiftDims(numDims, totalNumDims)
4423  .shiftSymbols(numSyms, totalNumSyms);
4424  totalNumDims += numDims;
4425  totalNumSyms += numSyms;
4426  }
4427 
4428  // Deduplicate map operands.
4429  SmallVector<Value> dimOperands, symOperands;
4430  SmallVector<AffineExpr> dimRplacements, symRepacements;
4431  if (deduplicateAndResolveOperands(parser, flatDimOperands, dimOperands,
4432  dimRplacements, AffineExprKind::DimId) ||
4433  deduplicateAndResolveOperands(parser, flatSymOperands, symOperands,
4434  symRepacements, AffineExprKind::SymbolId))
4435  return failure();
4436 
4437  result.operands.append(dimOperands.begin(), dimOperands.end());
4438  result.operands.append(symOperands.begin(), symOperands.end());
4439 
4440  Builder &builder = parser.getBuilder();
4441  auto flatMap = AffineMap::get(totalNumDims, totalNumSyms, flatExprs,
4442  parser.getContext());
4443  flatMap = flatMap.replaceDimsAndSymbols(
4444  dimRplacements, symRepacements, dimOperands.size(), symOperands.size());
4445 
4446  result.addAttribute(mapName, AffineMapAttr::get(flatMap));
4447  result.addAttribute(groupsName, builder.getI32TensorAttr(numMapsPerGroup));
4448  return success();
4449 }
4450 
4451 //
4452 // operation ::= `affine.parallel` `(` ssa-ids `)` `=` parallel-bound
4453 // `to` parallel-bound steps? region attr-dict?
4454 // steps ::= `steps` `(` integer-literals `)`
4455 //
4456 ParseResult AffineParallelOp::parse(OpAsmParser &parser,
4457  OperationState &result) {
4458  auto &builder = parser.getBuilder();
4459  auto indexType = builder.getIndexType();
4462  parser.parseEqual() ||
4463  parseAffineMapWithMinMax(parser, result, MinMaxKind::Max) ||
4464  parser.parseKeyword("to") ||
4465  parseAffineMapWithMinMax(parser, result, MinMaxKind::Min))
4466  return failure();
4467 
4468  AffineMapAttr stepsMapAttr;
4469  NamedAttrList stepsAttrs;
4471  if (failed(parser.parseOptionalKeyword("step"))) {
4472  SmallVector<int64_t, 4> steps(ivs.size(), 1);
4473  result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4474  builder.getI64ArrayAttr(steps));
4475  } else {
4476  if (parser.parseAffineMapOfSSAIds(stepsMapOperands, stepsMapAttr,
4477  AffineParallelOp::getStepsAttrStrName(),
4478  stepsAttrs,
4480  return failure();
4481 
4482  // Convert steps from an AffineMap into an I64ArrayAttr.
4484  auto stepsMap = stepsMapAttr.getValue();
4485  for (const auto &result : stepsMap.getResults()) {
4486  auto constExpr = dyn_cast<AffineConstantExpr>(result);
4487  if (!constExpr)
4488  return parser.emitError(parser.getNameLoc(),
4489  "steps must be constant integers");
4490  steps.push_back(constExpr.getValue());
4491  }
4492  result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4493  builder.getI64ArrayAttr(steps));
4494  }
4495 
4496  // Parse optional clause of the form: `reduce ("addf", "maxf")`, where the
4497  // quoted strings are a member of the enum AtomicRMWKind.
4498  SmallVector<Attribute, 4> reductions;
4499  if (succeeded(parser.parseOptionalKeyword("reduce"))) {
4500  if (parser.parseLParen())
4501  return failure();
4502  auto parseAttributes = [&]() -> ParseResult {
4503  // Parse a single quoted string via the attribute parsing, and then
4504  // verify it is a member of the enum and convert to it's integer
4505  // representation.
4506  StringAttr attrVal;
4507  NamedAttrList attrStorage;
4508  auto loc = parser.getCurrentLocation();
4509  if (parser.parseAttribute(attrVal, builder.getNoneType(), "reduce",
4510  attrStorage))
4511  return failure();
4512  std::optional<arith::AtomicRMWKind> reduction =
4513  arith::symbolizeAtomicRMWKind(attrVal.getValue());
4514  if (!reduction)
4515  return parser.emitError(loc, "invalid reduction value: ") << attrVal;
4516  reductions.push_back(
4517  builder.getI64IntegerAttr(static_cast<int64_t>(reduction.value())));
4518  // While we keep getting commas, keep parsing.
4519  return success();
4520  };
4521  if (parser.parseCommaSeparatedList(parseAttributes) || parser.parseRParen())
4522  return failure();
4523  }
4524  result.addAttribute(AffineParallelOp::getReductionsAttrStrName(),
4525  builder.getArrayAttr(reductions));
4526 
4527  // Parse return types of reductions (if any)
4528  if (parser.parseOptionalArrowTypeList(result.types))
4529  return failure();
4530 
4531  // Now parse the body.
4532  Region *body = result.addRegion();
4533  for (auto &iv : ivs)
4534  iv.type = indexType;
4535  if (parser.parseRegion(*body, ivs) ||
4536  parser.parseOptionalAttrDict(result.attributes))
4537  return failure();
4538 
4539  // Add a terminator if none was parsed.
4540  AffineParallelOp::ensureTerminator(*body, builder, result.location);
4541  return success();
4542 }
4543 
4544 //===----------------------------------------------------------------------===//
4545 // AffineYieldOp
4546 //===----------------------------------------------------------------------===//
4547 
4548 LogicalResult AffineYieldOp::verify() {
4549  auto *parentOp = (*this)->getParentOp();
4550  auto results = parentOp->getResults();
4551  auto operands = getOperands();
4552 
4553  if (!isa<AffineParallelOp, AffineIfOp, AffineForOp>(parentOp))
4554  return emitOpError() << "only terminates affine.if/for/parallel regions";
4555  if (parentOp->getNumResults() != getNumOperands())
4556  return emitOpError() << "parent of yield must have same number of "
4557  "results as the yield operands";
4558  for (auto it : llvm::zip(results, operands)) {
4559  if (std::get<0>(it).getType() != std::get<1>(it).getType())
4560  return emitOpError() << "types mismatch between yield op and its parent";
4561  }
4562 
4563  return success();
4564 }
4565 
4566 //===----------------------------------------------------------------------===//
4567 // AffineVectorLoadOp
4568 //===----------------------------------------------------------------------===//
4569 
4570 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4571  VectorType resultType, AffineMap map,
4572  ValueRange operands) {
4573  assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
4574  result.addOperands(operands);
4575  if (map)
4576  result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4577  result.types.push_back(resultType);
4578 }
4579 
4580 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4581  VectorType resultType, Value memref,
4582  AffineMap map, ValueRange mapOperands) {
4583  assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
4584  result.addOperands(memref);
4585  result.addOperands(mapOperands);
4586  result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4587  result.types.push_back(resultType);
4588 }
4589 
4590 void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4591  VectorType resultType, Value memref,
4592  ValueRange indices) {
4593  auto memrefType = llvm::cast<MemRefType>(memref.getType());
4594  int64_t rank = memrefType.getRank();
4595  // Create identity map for memrefs with at least one dimension or () -> ()
4596  // for zero-dimensional memrefs.
4597  auto map =
4598  rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
4599  build(builder, result, resultType, memref, map, indices);
4600 }
4601 
4602 void AffineVectorLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
4603  MLIRContext *context) {
4604  results.add<SimplifyAffineOp<AffineVectorLoadOp>>(context);
4605 }
4606 
4607 ParseResult AffineVectorLoadOp::parse(OpAsmParser &parser,
4608  OperationState &result) {
4609  auto &builder = parser.getBuilder();
4610  auto indexTy = builder.getIndexType();
4611 
4612  MemRefType memrefType;
4613  VectorType resultType;
4614  OpAsmParser::UnresolvedOperand memrefInfo;
4615  AffineMapAttr mapAttr;
4617  return failure(
4618  parser.parseOperand(memrefInfo) ||
4619  parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
4620  AffineVectorLoadOp::getMapAttrStrName(),
4621  result.attributes) ||
4622  parser.parseOptionalAttrDict(result.attributes) ||
4623  parser.parseColonType(memrefType) || parser.parseComma() ||
4624  parser.parseType(resultType) ||
4625  parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
4626  parser.resolveOperands(mapOperands, indexTy, result.operands) ||
4627  parser.addTypeToList(resultType, result.types));
4628 }
4629 
4631  p << " " << getMemRef() << '[';
4632  if (AffineMapAttr mapAttr =
4633  (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()))
4634  p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
4635  p << ']';
4636  p.printOptionalAttrDict((*this)->getAttrs(),
4637  /*elidedAttrs=*/{getMapAttrStrName()});
4638  p << " : " << getMemRefType() << ", " << getType();
4639 }
4640 
4641 /// Verify common invariants of affine.vector_load and affine.vector_store.
4642 static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType,
4643  VectorType vectorType) {
4644  // Check that memref and vector element types match.
4645  if (memrefType.getElementType() != vectorType.getElementType())
4646  return op->emitOpError(
4647  "requires memref and vector types of the same elemental type");
4648  return success();
4649 }
4650 
4651 LogicalResult AffineVectorLoadOp::verify() {
4652  MemRefType memrefType = getMemRefType();
4654  *this, (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()),
4655  getMapOperands(), memrefType,
4656  /*numIndexOperands=*/getNumOperands() - 1)))
4657  return failure();
4658 
4659  if (failed(verifyVectorMemoryOp(getOperation(), memrefType, getVectorType())))
4660  return failure();
4661 
4662  return success();
4663 }
4664 
4665 //===----------------------------------------------------------------------===//
4666 // AffineVectorStoreOp
4667 //===----------------------------------------------------------------------===//
4668 
4669 void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &result,
4670  Value valueToStore, Value memref, AffineMap map,
4671  ValueRange mapOperands) {
4672  assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
4673  result.addOperands(valueToStore);
4674  result.addOperands(memref);
4675  result.addOperands(mapOperands);
4676  result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4677 }
4678 
4679 // Use identity map.
4680 void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &result,
4681  Value valueToStore, Value memref,
4682  ValueRange indices) {
4683  auto memrefType = llvm::cast<MemRefType>(memref.getType());
4684  int64_t rank = memrefType.getRank();
4685  // Create identity map for memrefs with at least one dimension or () -> ()
4686  // for zero-dimensional memrefs.
4687  auto map =
4688  rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
4689  build(builder, result, valueToStore, memref, map, indices);
4690 }
4691 void AffineVectorStoreOp::getCanonicalizationPatterns(
4692  RewritePatternSet &results, MLIRContext *context) {
4693  results.add<SimplifyAffineOp<AffineVectorStoreOp>>(context);
4694 }
4695 
4696 ParseResult AffineVectorStoreOp::parse(OpAsmParser &parser,
4697  OperationState &result) {
4698  auto indexTy = parser.getBuilder().getIndexType();
4699 
4700  MemRefType memrefType;
4701  VectorType resultType;
4702  OpAsmParser::UnresolvedOperand storeValueInfo;
4703  OpAsmParser::UnresolvedOperand memrefInfo;
4704  AffineMapAttr mapAttr;
4706  return failure(
4707  parser.parseOperand(storeValueInfo) || parser.parseComma() ||
4708  parser.parseOperand(memrefInfo) ||
4709  parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
4710  AffineVectorStoreOp::getMapAttrStrName(),
4711  result.attributes) ||
4712  parser.parseOptionalAttrDict(result.attributes) ||
4713  parser.parseColonType(memrefType) || parser.parseComma() ||
4714  parser.parseType(resultType) ||
4715  parser.resolveOperand(storeValueInfo, resultType, result.operands) ||
4716  parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
4717  parser.resolveOperands(mapOperands, indexTy, result.operands));
4718 }
4719 
4721  p << " " << getValueToStore();
4722  p << ", " << getMemRef() << '[';
4723  if (AffineMapAttr mapAttr =
4724  (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()))
4725  p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
4726  p << ']';
4727  p.printOptionalAttrDict((*this)->getAttrs(),
4728  /*elidedAttrs=*/{getMapAttrStrName()});
4729  p << " : " << getMemRefType() << ", " << getValueToStore().getType();
4730 }
4731 
4732 LogicalResult AffineVectorStoreOp::verify() {
4733  MemRefType memrefType = getMemRefType();
4735  *this, (*this)->getAttrOfType<AffineMapAttr>(getMapAttrStrName()),
4736  getMapOperands(), memrefType,
4737  /*numIndexOperands=*/getNumOperands() - 2)))
4738  return failure();
4739 
4740  if (failed(verifyVectorMemoryOp(*this, memrefType, getVectorType())))
4741  return failure();
4742 
4743  return success();
4744 }
4745 
4746 //===----------------------------------------------------------------------===//
4747 // DelinearizeIndexOp
4748 //===----------------------------------------------------------------------===//
4749 
4750 void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4751  OperationState &odsState,
4752  Value linearIndex, ValueRange dynamicBasis,
4753  ArrayRef<int64_t> staticBasis,
4754  bool hasOuterBound) {
4755  SmallVector<Type> returnTypes(hasOuterBound ? staticBasis.size()
4756  : staticBasis.size() + 1,
4757  linearIndex.getType());
4758  build(odsBuilder, odsState, returnTypes, linearIndex, dynamicBasis,
4759  staticBasis);
4760 }
4761 
4762 void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4763  OperationState &odsState,
4764  Value linearIndex, ValueRange basis,
4765  bool hasOuterBound) {
4766  if (hasOuterBound && !basis.empty() && basis.front() == nullptr) {
4767  hasOuterBound = false;
4768  basis = basis.drop_front();
4769  }
4770  SmallVector<Value> dynamicBasis;
4771  SmallVector<int64_t> staticBasis;
4772  dispatchIndexOpFoldResults(getAsOpFoldResult(basis), dynamicBasis,
4773  staticBasis);
4774  build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4775  hasOuterBound);
4776 }
4777 
4778 void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4779  OperationState &odsState,
4780  Value linearIndex,
4781  ArrayRef<OpFoldResult> basis,
4782  bool hasOuterBound) {
4783  if (hasOuterBound && !basis.empty() && basis.front() == OpFoldResult()) {
4784  hasOuterBound = false;
4785  basis = basis.drop_front();
4786  }
4787  SmallVector<Value> dynamicBasis;
4788  SmallVector<int64_t> staticBasis;
4789  dispatchIndexOpFoldResults(basis, dynamicBasis, staticBasis);
4790  build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4791  hasOuterBound);
4792 }
4793 
4794 void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4795  OperationState &odsState,
4796  Value linearIndex, ArrayRef<int64_t> basis,
4797  bool hasOuterBound) {
4798  build(odsBuilder, odsState, linearIndex, ValueRange{}, basis, hasOuterBound);
4799 }
4800 
4801 LogicalResult AffineDelinearizeIndexOp::verify() {
4802  ArrayRef<int64_t> staticBasis = getStaticBasis();
4803  if (getNumResults() != staticBasis.size() &&
4804  getNumResults() != staticBasis.size() + 1)
4805  return emitOpError("should return an index for each basis element and up "
4806  "to one extra index");
4807 
4808  auto dynamicMarkersCount = llvm::count_if(staticBasis, ShapedType::isDynamic);
4809  if (static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
4810  return emitOpError(
4811  "mismatch between dynamic and static basis (kDynamic marker but no "
4812  "corresponding dynamic basis entry) -- this can only happen due to an "
4813  "incorrect fold/rewrite");
4814 
4815  if (!llvm::all_of(staticBasis, [](int64_t v) {
4816  return v > 0 || ShapedType::isDynamic(v);
4817  }))
4818  return emitOpError("no basis element may be statically non-positive");
4819 
4820  return success();
4821 }
4822 
4823 /// Given mixed basis of affine.delinearize_index/linearize_index replace
4824 /// constant SSA values with the constant integer value and return the new
4825 /// static basis. In case no such candidate for replacement exists, this utility
4826 /// returns std::nullopt.
4827 static std::optional<SmallVector<int64_t>>
4829  MutableOperandRange mutableDynamicBasis,
4830  ArrayRef<Attribute> dynamicBasis) {
4831  uint64_t dynamicBasisIndex = 0;
4832  for (OpFoldResult basis : dynamicBasis) {
4833  if (basis) {
4834  mutableDynamicBasis.erase(dynamicBasisIndex);
4835  } else {
4836  ++dynamicBasisIndex;
4837  }
4838  }
4839 
4840  // No constant SSA value exists.
4841  if (dynamicBasisIndex == dynamicBasis.size())
4842  return std::nullopt;
4843 
4844  SmallVector<int64_t> staticBasis;
4845  for (OpFoldResult basis : mixedBasis) {
4846  std::optional<int64_t> basisVal = getConstantIntValue(basis);
4847  if (!basisVal)
4848  staticBasis.push_back(ShapedType::kDynamic);
4849  else
4850  staticBasis.push_back(*basisVal);
4851  }
4852 
4853  return staticBasis;
4854 }
4855 
4856 LogicalResult
4857 AffineDelinearizeIndexOp::fold(FoldAdaptor adaptor,
4859  std::optional<SmallVector<int64_t>> maybeStaticBasis =
4860  foldCstValueToCstAttrBasis(getMixedBasis(), getDynamicBasisMutable(),
4861  adaptor.getDynamicBasis());
4862  if (maybeStaticBasis) {
4863  setStaticBasis(*maybeStaticBasis);
4864  return success();
4865  }
4866  // If we won't be doing any division or modulo (no basis or the one basis
4867  // element is purely advisory), simply return the input value.
4868  if (getNumResults() == 1) {
4869  result.push_back(getLinearIndex());
4870  return success();
4871  }
4872 
4873  if (adaptor.getLinearIndex() == nullptr)
4874  return failure();
4875 
4876  if (!adaptor.getDynamicBasis().empty())
4877  return failure();
4878 
4879  int64_t highPart = cast<IntegerAttr>(adaptor.getLinearIndex()).getInt();
4880  Type attrType = getLinearIndex().getType();
4881 
4882  ArrayRef<int64_t> staticBasis = getStaticBasis();
4883  if (hasOuterBound())
4884  staticBasis = staticBasis.drop_front();
4885  for (int64_t modulus : llvm::reverse(staticBasis)) {
4886  result.push_back(IntegerAttr::get(attrType, llvm::mod(highPart, modulus)));
4887  highPart = llvm::divideFloorSigned(highPart, modulus);
4888  }
4889  result.push_back(IntegerAttr::get(attrType, highPart));
4890  std::reverse(result.begin(), result.end());
4891  return success();
4892 }
4893 
4894 SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getEffectiveBasis() {
4895  OpBuilder builder(getContext());
4896  if (hasOuterBound()) {
4897  if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
4898  return getMixedValues(getStaticBasis().drop_front(),
4899  getDynamicBasis().drop_front(), builder);
4900 
4901  return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
4902  builder);
4903  }
4904 
4905  return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
4906 }
4907 
4908 SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getPaddedBasis() {
4909  SmallVector<OpFoldResult> ret = getMixedBasis();
4910  if (!hasOuterBound())
4911  ret.insert(ret.begin(), OpFoldResult());
4912  return ret;
4913 }
4914 
4915 namespace {
4916 
4917 // Drops delinearization indices that correspond to unit-extent basis
4918 struct DropUnitExtentBasis
4919  : public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
4921 
4922  LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
4923  PatternRewriter &rewriter) const override {
4924  SmallVector<Value> replacements(delinearizeOp->getNumResults(), nullptr);
4925  std::optional<Value> zero = std::nullopt;
4926  Location loc = delinearizeOp->getLoc();
4927  auto getZero = [&]() -> Value {
4928  if (!zero)
4929  zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
4930  return zero.value();
4931  };
4932 
4933  // Replace all indices corresponding to unit-extent basis with 0.
4934  // Remaining basis can be used to get a new `affine.delinearize_index` op.
4935  SmallVector<OpFoldResult> newBasis;
4936  for (auto [index, basis] :
4937  llvm::enumerate(delinearizeOp.getPaddedBasis())) {
4938  std::optional<int64_t> basisVal =
4939  basis ? getConstantIntValue(basis) : std::nullopt;
4940  if (basisVal == 1)
4941  replacements[index] = getZero();
4942  else
4943  newBasis.push_back(basis);
4944  }
4945 
4946  if (newBasis.size() == delinearizeOp.getNumResults())
4947  return rewriter.notifyMatchFailure(delinearizeOp,
4948  "no unit basis elements");
4949 
4950  if (!newBasis.empty()) {
4951  // Will drop the leading nullptr from `basis` if there was no outer bound.
4952  auto newDelinearizeOp = affine::AffineDelinearizeIndexOp::create(
4953  rewriter, loc, delinearizeOp.getLinearIndex(), newBasis);
4954  int newIndex = 0;
4955  // Map back the new delinearized indices to the values they replace.
4956  for (auto &replacement : replacements) {
4957  if (replacement)
4958  continue;
4959  replacement = newDelinearizeOp->getResult(newIndex++);
4960  }
4961  }
4962 
4963  rewriter.replaceOp(delinearizeOp, replacements);
4964  return success();
4965  }
4966 };
4967 
4968 /// If a `affine.delinearize_index`'s input is a `affine.linearize_index
4969 /// disjoint` and the two operations end with the same basis elements,
4970 /// cancel those parts of the operations out because they are inverses
4971 /// of each other.
4972 ///
4973 /// If the operations have the same basis, cancel them entirely.
4974 ///
4975 /// The `disjoint` flag is needed on the `affine.linearize_index` because
4976 /// otherwise, there is no guarantee that the inputs to the linearization are
4977 /// in-bounds the way the outputs of the delinearization would be.
4978 struct CancelDelinearizeOfLinearizeDisjointExactTail
4979  : public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
4981 
4982  LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
4983  PatternRewriter &rewriter) const override {
4984  auto linearizeOp = delinearizeOp.getLinearIndex()
4985  .getDefiningOp<affine::AffineLinearizeIndexOp>();
4986  if (!linearizeOp)
4987  return rewriter.notifyMatchFailure(delinearizeOp,
4988  "index doesn't come from linearize");
4989 
4990  if (!linearizeOp.getDisjoint())
4991  return rewriter.notifyMatchFailure(linearizeOp, "not disjoint");
4992 
4993  ValueRange linearizeIns = linearizeOp.getMultiIndex();
4994  // Note: we use the full basis so we don't lose outer bounds later.
4995  SmallVector<OpFoldResult> linearizeBasis = linearizeOp.getMixedBasis();
4996  SmallVector<OpFoldResult> delinearizeBasis = delinearizeOp.getMixedBasis();
4997  size_t numMatches = 0;
4998  for (auto [linSize, delinSize] : llvm::zip(
4999  llvm::reverse(linearizeBasis), llvm::reverse(delinearizeBasis))) {
5000  if (linSize != delinSize)
5001  break;
5002  ++numMatches;
5003  }
5004 
5005  if (numMatches == 0)
5006  return rewriter.notifyMatchFailure(
5007  delinearizeOp, "final basis element doesn't match linearize");
5008 
5009  // The easy case: everything lines up and the basis match sup completely.
5010  if (numMatches == linearizeBasis.size() &&
5011  numMatches == delinearizeBasis.size() &&
5012  linearizeIns.size() == delinearizeOp.getNumResults()) {
5013  rewriter.replaceOp(delinearizeOp, linearizeOp.getMultiIndex());
5014  return success();
5015  }
5016 
5017  Value newLinearize = affine::AffineLinearizeIndexOp::create(
5018  rewriter, linearizeOp.getLoc(), linearizeIns.drop_back(numMatches),
5019  ArrayRef<OpFoldResult>{linearizeBasis}.drop_back(numMatches),
5020  linearizeOp.getDisjoint());
5021  auto newDelinearize = affine::AffineDelinearizeIndexOp::create(
5022  rewriter, delinearizeOp.getLoc(), newLinearize,
5023  ArrayRef<OpFoldResult>{delinearizeBasis}.drop_back(numMatches),
5024  delinearizeOp.hasOuterBound());
5025  SmallVector<Value> mergedResults(newDelinearize.getResults());
5026  mergedResults.append(linearizeIns.take_back(numMatches).begin(),
5027  linearizeIns.take_back(numMatches).end());
5028  rewriter.replaceOp(delinearizeOp, mergedResults);
5029  return success();
5030  }
5031 };
5032 
5033 /// If the input to a delinearization is a disjoint linearization, and the
5034 /// last k > 1 components of the delinearization basis multiply to the
5035 /// last component of the linearization basis, break the linearization and
5036 /// delinearization into two parts, peeling off the last input to linearization.
5037 ///
5038 /// For example:
5039 /// %0 = affine.linearize_index [%z, %y, %x] by (3, 2, 32) : index
5040 /// %1:4 = affine.delinearize_index %0 by (2, 3, 8, 4) : index, ...
5041 /// becomes
5042 /// %0 = affine.linearize_index [%z, %y] by (3, 2) : index
5043 /// %1:2 = affine.delinearize_index %0 by (2, 3) : index
5044 /// %2:2 = affine.delinearize_index %x by (8, 4) : index
5045 /// where the original %1:4 is replaced by %1:2 ++ %2:2
5046 struct SplitDelinearizeSpanningLastLinearizeArg final
5047  : OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5049 
5050  LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5051  PatternRewriter &rewriter) const override {
5052  auto linearizeOp = delinearizeOp.getLinearIndex()
5053  .getDefiningOp<affine::AffineLinearizeIndexOp>();
5054  if (!linearizeOp)
5055  return rewriter.notifyMatchFailure(delinearizeOp,
5056  "index doesn't come from linearize");
5057 
5058  if (!linearizeOp.getDisjoint())
5059  return rewriter.notifyMatchFailure(linearizeOp,
5060  "linearize isn't disjoint");
5061 
5062  int64_t target = linearizeOp.getStaticBasis().back();
5063  if (ShapedType::isDynamic(target))
5064  return rewriter.notifyMatchFailure(
5065  linearizeOp, "linearize ends with dynamic basis value");
5066 
5067  int64_t sizeToSplit = 1;
5068  size_t elemsToSplit = 0;
5069  ArrayRef<int64_t> basis = delinearizeOp.getStaticBasis();
5070  for (int64_t basisElem : llvm::reverse(basis)) {
5071  if (ShapedType::isDynamic(basisElem))
5072  return rewriter.notifyMatchFailure(
5073  delinearizeOp, "dynamic basis element while scanning for split");
5074  sizeToSplit *= basisElem;
5075  elemsToSplit += 1;
5076 
5077  if (sizeToSplit > target)
5078  return rewriter.notifyMatchFailure(delinearizeOp,
5079  "overshot last argument size");
5080  if (sizeToSplit == target)
5081  break;
5082  }
5083 
5084  if (sizeToSplit < target)
5085  return rewriter.notifyMatchFailure(
5086  delinearizeOp, "product of known basis elements doesn't exceed last "
5087  "linearize argument");
5088 
5089  if (elemsToSplit < 2)
5090  return rewriter.notifyMatchFailure(
5091  delinearizeOp,
5092  "need at least two elements to form the basis product");
5093 
5094  Value linearizeWithoutBack = affine::AffineLinearizeIndexOp::create(
5095  rewriter, linearizeOp.getLoc(), linearizeOp.getMultiIndex().drop_back(),
5096  linearizeOp.getDynamicBasis(), linearizeOp.getStaticBasis().drop_back(),
5097  linearizeOp.getDisjoint());
5098  auto delinearizeWithoutSplitPart = affine::AffineDelinearizeIndexOp::create(
5099  rewriter, delinearizeOp.getLoc(), linearizeWithoutBack,
5100  delinearizeOp.getDynamicBasis(), basis.drop_back(elemsToSplit),
5101  delinearizeOp.hasOuterBound());
5102  auto delinearizeBack = affine::AffineDelinearizeIndexOp::create(
5103  rewriter, delinearizeOp.getLoc(), linearizeOp.getMultiIndex().back(),
5104  basis.take_back(elemsToSplit), /*hasOuterBound=*/true);
5105  SmallVector<Value> results = llvm::to_vector(
5106  llvm::concat<Value>(delinearizeWithoutSplitPart.getResults(),
5107  delinearizeBack.getResults()));
5108  rewriter.replaceOp(delinearizeOp, results);
5109 
5110  return success();
5111  }
5112 };
5113 } // namespace
5114 
5115 void affine::AffineDelinearizeIndexOp::getCanonicalizationPatterns(
5116  RewritePatternSet &patterns, MLIRContext *context) {
5117  patterns
5118  .insert<CancelDelinearizeOfLinearizeDisjointExactTail,
5119  DropUnitExtentBasis, SplitDelinearizeSpanningLastLinearizeArg>(
5120  context);
5121 }
5122 
5123 //===----------------------------------------------------------------------===//
5124 // LinearizeIndexOp
5125 //===----------------------------------------------------------------------===//
5126 
5127 void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5128  OperationState &odsState,
5129  ValueRange multiIndex, ValueRange basis,
5130  bool disjoint) {
5131  if (!basis.empty() && basis.front() == Value())
5132  basis = basis.drop_front();
5133  SmallVector<Value> dynamicBasis;
5134  SmallVector<int64_t> staticBasis;
5135  dispatchIndexOpFoldResults(getAsOpFoldResult(basis), dynamicBasis,
5136  staticBasis);
5137  build(odsBuilder, odsState, multiIndex, dynamicBasis, staticBasis, disjoint);
5138 }
5139 
5140 void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5141  OperationState &odsState,
5142  ValueRange multiIndex,
5143  ArrayRef<OpFoldResult> basis,
5144  bool disjoint) {
5145  if (!basis.empty() && basis.front() == OpFoldResult())
5146  basis = basis.drop_front();
5147  SmallVector<Value> dynamicBasis;
5148  SmallVector<int64_t> staticBasis;
5149  dispatchIndexOpFoldResults(basis, dynamicBasis, staticBasis);
5150  build(odsBuilder, odsState, multiIndex, dynamicBasis, staticBasis, disjoint);
5151 }
5152 
5153 void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5154  OperationState &odsState,
5155  ValueRange multiIndex,
5156  ArrayRef<int64_t> basis, bool disjoint) {
5157  build(odsBuilder, odsState, multiIndex, ValueRange{}, basis, disjoint);
5158 }
5159 
5160 LogicalResult AffineLinearizeIndexOp::verify() {
5161  size_t numIndexes = getMultiIndex().size();
5162  size_t numBasisElems = getStaticBasis().size();
5163  if (numIndexes != numBasisElems && numIndexes != numBasisElems + 1)
5164  return emitOpError("should be passed a basis element for each index except "
5165  "possibly the first");
5166 
5167  auto dynamicMarkersCount =
5168  llvm::count_if(getStaticBasis(), ShapedType::isDynamic);
5169  if (static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
5170  return emitOpError(
5171  "mismatch between dynamic and static basis (kDynamic marker but no "
5172  "corresponding dynamic basis entry) -- this can only happen due to an "
5173  "incorrect fold/rewrite");
5174 
5175  return success();
5176 }
5177 
5178 OpFoldResult AffineLinearizeIndexOp::fold(FoldAdaptor adaptor) {
5179  std::optional<SmallVector<int64_t>> maybeStaticBasis =
5180  foldCstValueToCstAttrBasis(getMixedBasis(), getDynamicBasisMutable(),
5181  adaptor.getDynamicBasis());
5182  if (maybeStaticBasis) {
5183  setStaticBasis(*maybeStaticBasis);
5184  return getResult();
5185  }
5186  // No indices linearizes to zero.
5187  if (getMultiIndex().empty())
5188  return IntegerAttr::get(getResult().getType(), 0);
5189 
5190  // One single index linearizes to itself.
5191  if (getMultiIndex().size() == 1)
5192  return getMultiIndex().front();
5193 
5194  if (llvm::is_contained(adaptor.getMultiIndex(), nullptr))
5195  return nullptr;
5196 
5197  if (!adaptor.getDynamicBasis().empty())
5198  return nullptr;
5199 
5200  int64_t result = 0;
5201  int64_t stride = 1;
5202  for (auto [length, indexAttr] :
5203  llvm::zip_first(llvm::reverse(getStaticBasis()),
5204  llvm::reverse(adaptor.getMultiIndex()))) {
5205  result = result + cast<IntegerAttr>(indexAttr).getInt() * stride;
5206  stride = stride * length;
5207  }
5208  // Handle the index element with no basis element.
5209  if (!hasOuterBound())
5210  result =
5211  result +
5212  cast<IntegerAttr>(adaptor.getMultiIndex().front()).getInt() * stride;
5213 
5214  return IntegerAttr::get(getResult().getType(), result);
5215 }
5216 
5217 SmallVector<OpFoldResult> AffineLinearizeIndexOp::getEffectiveBasis() {
5218  OpBuilder builder(getContext());
5219  if (hasOuterBound()) {
5220  if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
5221  return getMixedValues(getStaticBasis().drop_front(),
5222  getDynamicBasis().drop_front(), builder);
5223 
5224  return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
5225  builder);
5226  }
5227 
5228  return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
5229 }
5230 
5231 SmallVector<OpFoldResult> AffineLinearizeIndexOp::getPaddedBasis() {
5232  SmallVector<OpFoldResult> ret = getMixedBasis();
5233  if (!hasOuterBound())
5234  ret.insert(ret.begin(), OpFoldResult());
5235  return ret;
5236 }
5237 
5238 namespace {
5239 /// Rewrite `affine.linearize_index disjoint [%...a, %x, %...b] by (%...c, 1,
5240 /// %...d)` to `affine.linearize_index disjoint [%...a, %...b] by (%...c,
5241 /// %...d)`.
5242 
5243 /// Note that `disjoint` is required here, because, without it, we could have
5244 /// `affine.linearize_index [%...a, %c64, %...b] by (%...c, 1, %...d)`
5245 /// is a valid operation where the `%c64` cannot be trivially dropped.
5246 ///
5247 /// Alternatively, if `%x` in the above is a known constant 0, remove it even if
5248 /// the operation isn't asserted to be `disjoint`.
5249 struct DropLinearizeUnitComponentsIfDisjointOrZero final
5250  : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5252 
5253  LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5254  PatternRewriter &rewriter) const override {
5255  ValueRange multiIndex = op.getMultiIndex();
5256  size_t numIndices = multiIndex.size();
5257  SmallVector<Value> newIndices;
5258  newIndices.reserve(numIndices);
5259  SmallVector<OpFoldResult> newBasis;
5260  newBasis.reserve(numIndices);
5261 
5262  if (!op.hasOuterBound()) {
5263  newIndices.push_back(multiIndex.front());
5264  multiIndex = multiIndex.drop_front();
5265  }
5266 
5267  SmallVector<OpFoldResult> basis = op.getMixedBasis();
5268  for (auto [index, basisElem] : llvm::zip_equal(multiIndex, basis)) {
5269  std::optional<int64_t> basisEntry = getConstantIntValue(basisElem);
5270  if (!basisEntry || *basisEntry != 1) {
5271  newIndices.push_back(index);
5272  newBasis.push_back(basisElem);
5273  continue;
5274  }
5275 
5276  std::optional<int64_t> indexValue = getConstantIntValue(index);
5277  if (!op.getDisjoint() && (!indexValue || *indexValue != 0)) {
5278  newIndices.push_back(index);
5279  newBasis.push_back(basisElem);
5280  continue;
5281  }
5282  }
5283  if (newIndices.size() == numIndices)
5284  return rewriter.notifyMatchFailure(op,
5285  "no unit basis entries to replace");
5286 
5287  if (newIndices.size() == 0) {
5288  rewriter.replaceOpWithNewOp<arith::ConstantIndexOp>(op, 0);
5289  return success();
5290  }
5291  rewriter.replaceOpWithNewOp<affine::AffineLinearizeIndexOp>(
5292  op, newIndices, newBasis, op.getDisjoint());
5293  return success();
5294  }
5295 };
5296 
5298  ArrayRef<OpFoldResult> terms) {
5299  int64_t nDynamic = 0;
5300  SmallVector<Value> dynamicPart;
5301  AffineExpr result = builder.getAffineConstantExpr(1);
5302  for (OpFoldResult term : terms) {
5303  if (!term)
5304  return term;
5305  std::optional<int64_t> maybeConst = getConstantIntValue(term);
5306  if (maybeConst) {
5307  result = result * builder.getAffineConstantExpr(*maybeConst);
5308  } else {
5309  dynamicPart.push_back(cast<Value>(term));
5310  result = result * builder.getAffineSymbolExpr(nDynamic++);
5311  }
5312  }
5313  if (auto constant = dyn_cast<AffineConstantExpr>(result))
5314  return getAsIndexOpFoldResult(builder.getContext(), constant.getValue());
5315  return AffineApplyOp::create(builder, loc, result, dynamicPart).getResult();
5316 }
5317 
5318 /// If conseceutive outputs of a delinearize_index are linearized with the same
5319 /// bounds, canonicalize away the redundant arithmetic.
5320 ///
5321 /// That is, if we have
5322 /// ```
5323 /// %s:N = affine.delinearize_index %x into (...a, B1, B2, ... BK, ...b)
5324 /// %t = affine.linearize_index [...c, %s#I, %s#(I + 1), ... %s#(I+K-1), ...d]
5325 /// by (...e, B1, B2, ..., BK, ...f)
5326 /// ```
5327 ///
5328 /// We can rewrite this to
5329 /// ```
5330 /// B = B1 * B2 ... BK
5331 /// %sMerged:(N-K+1) affine.delinearize_index %x into (...a, B, ...b)
5332 /// %t = affine.linearize_index [...c, %s#I, ...d] by (...e, B, ...f)
5333 /// ```
5334 /// where we replace all results of %s unaffected by the change with results
5335 /// from %sMerged.
5336 ///
5337 /// As a special case, if all results of the delinearize are merged in this way
5338 /// we can replace those usages with %x, thus cancelling the delinearization
5339 /// entirely, as in
5340 /// ```
5341 /// %s:3 = affine.delinearize_index %x into (2, 4, 8)
5342 /// %t = affine.linearize_index [%s#0, %s#1, %s#2, %c0] by (2, 4, 8, 16)
5343 /// ```
5344 /// becoming `%t = affine.linearize_index [%x, %c0] by (64, 16)`
5345 struct CancelLinearizeOfDelinearizePortion final
5346  : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5348 
5349 private:
5350  // Struct representing a case where the cancellation pattern
5351  // applies. A `Match` means that `length` inputs to the linearize operation
5352  // starting at `linStart` can be cancelled with `length` outputs of
5353  // `delinearize`, starting from `delinStart`.
5354  struct Match {
5355  AffineDelinearizeIndexOp delinearize;
5356  unsigned linStart = 0;
5357  unsigned delinStart = 0;
5358  unsigned length = 0;
5359  };
5360 
5361 public:
5362  LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp linearizeOp,
5363  PatternRewriter &rewriter) const override {
5364  SmallVector<Match> matches;
5365 
5366  const SmallVector<OpFoldResult> linBasis = linearizeOp.getPaddedBasis();
5367  ArrayRef<OpFoldResult> linBasisRef = linBasis;
5368 
5369  ValueRange multiIndex = linearizeOp.getMultiIndex();
5370  unsigned numLinArgs = multiIndex.size();
5371  unsigned linArgIdx = 0;
5372  // We only want to replace one run from the same delinearize op per
5373  // pattern invocation lest we run into invalidation issues.
5374  llvm::SmallPtrSet<Operation *, 2> alreadyMatchedDelinearize;
5375  while (linArgIdx < numLinArgs) {
5376  auto asResult = dyn_cast<OpResult>(multiIndex[linArgIdx]);
5377  if (!asResult) {
5378  linArgIdx++;
5379  continue;
5380  }
5381 
5382  auto delinearizeOp =
5383  dyn_cast<AffineDelinearizeIndexOp>(asResult.getOwner());
5384  if (!delinearizeOp) {
5385  linArgIdx++;
5386  continue;
5387  }
5388 
5389  /// Result 0 of the delinearize and argument 0 of the linearize can
5390  /// leave their maximum value unspecified. However, even if this happens
5391  /// we can still sometimes start the match process. Specifically, if
5392  /// - The argument we're matching is result 0 and argument 0 (so the
5393  /// bounds don't matter). For example,
5394  ///
5395  /// %0:2 = affine.delinearize_index %x into (8) : index, index
5396  /// %1 = affine.linearize_index [%s#0, %s#1, ...] (8, ...)
5397  /// allows cancellation
5398  /// - The delinearization doesn't specify a bound, but the linearization
5399  /// is `disjoint`, which asserts that the bound on the linearization is
5400  /// correct.
5401  unsigned delinArgIdx = asResult.getResultNumber();
5402  SmallVector<OpFoldResult> delinBasis = delinearizeOp.getPaddedBasis();
5403  OpFoldResult firstDelinBound = delinBasis[delinArgIdx];
5404  OpFoldResult firstLinBound = linBasis[linArgIdx];
5405  bool boundsMatch = firstDelinBound == firstLinBound;
5406  bool bothAtFront = linArgIdx == 0 && delinArgIdx == 0;
5407  bool knownByDisjoint =
5408  linearizeOp.getDisjoint() && delinArgIdx == 0 && !firstDelinBound;
5409  if (!boundsMatch && !bothAtFront && !knownByDisjoint) {
5410  linArgIdx++;
5411  continue;
5412  }
5413 
5414  unsigned j = 1;
5415  unsigned numDelinOuts = delinearizeOp.getNumResults();
5416  for (; j + linArgIdx < numLinArgs && j + delinArgIdx < numDelinOuts;
5417  ++j) {
5418  if (multiIndex[linArgIdx + j] !=
5419  delinearizeOp.getResult(delinArgIdx + j))
5420  break;
5421  if (linBasis[linArgIdx + j] != delinBasis[delinArgIdx + j])
5422  break;
5423  }
5424  // If there're multiple matches against the same delinearize_index,
5425  // only rewrite the first one we find to prevent invalidations. The next
5426  // ones will be taken care of by subsequent pattern invocations.
5427  if (j <= 1 || !alreadyMatchedDelinearize.insert(delinearizeOp).second) {
5428  linArgIdx++;
5429  continue;
5430  }
5431  matches.push_back(Match{delinearizeOp, linArgIdx, delinArgIdx, j});
5432  linArgIdx += j;
5433  }
5434 
5435  if (matches.empty())
5436  return rewriter.notifyMatchFailure(
5437  linearizeOp, "no run of delinearize outputs to deal with");
5438 
5439  // Record all the delinearize replacements so we can do them after creating
5440  // the new linearization operation, since the new operation might use
5441  // outputs of something we're replacing.
5442  SmallVector<SmallVector<Value>> delinearizeReplacements;
5443 
5444  SmallVector<Value> newIndex;
5445  newIndex.reserve(numLinArgs);
5446  SmallVector<OpFoldResult> newBasis;
5447  newBasis.reserve(numLinArgs);
5448  unsigned prevMatchEnd = 0;
5449  for (Match m : matches) {
5450  unsigned gap = m.linStart - prevMatchEnd;
5451  llvm::append_range(newIndex, multiIndex.slice(prevMatchEnd, gap));
5452  llvm::append_range(newBasis, linBasisRef.slice(prevMatchEnd, gap));
5453  // Update here so we don't forget this during early continues
5454  prevMatchEnd = m.linStart + m.length;
5455 
5456  PatternRewriter::InsertionGuard g(rewriter);
5457  rewriter.setInsertionPoint(m.delinearize);
5458 
5459  ArrayRef<OpFoldResult> basisToMerge =
5460  linBasisRef.slice(m.linStart, m.length);
5461  // We use the slice from the linearize's basis above because of the
5462  // "bounds inferred from `disjoint`" case above.
5463  OpFoldResult newSize =
5464  computeProduct(linearizeOp.getLoc(), rewriter, basisToMerge);
5465 
5466  // Trivial case where we can just skip past the delinearize all together
5467  if (m.length == m.delinearize.getNumResults()) {
5468  newIndex.push_back(m.delinearize.getLinearIndex());
5469  newBasis.push_back(newSize);
5470  // Pad out set of replacements so we don't do anything with this one.
5471  delinearizeReplacements.push_back(SmallVector<Value>());
5472  continue;
5473  }
5474 
5475  SmallVector<Value> newDelinResults;
5476  SmallVector<OpFoldResult> newDelinBasis = m.delinearize.getPaddedBasis();
5477  newDelinBasis.erase(newDelinBasis.begin() + m.delinStart,
5478  newDelinBasis.begin() + m.delinStart + m.length);
5479  newDelinBasis.insert(newDelinBasis.begin() + m.delinStart, newSize);
5480  auto newDelinearize = AffineDelinearizeIndexOp::create(
5481  rewriter, m.delinearize.getLoc(), m.delinearize.getLinearIndex(),
5482  newDelinBasis);
5483 
5484  // Since there may be other uses of the indices we just merged together,
5485  // create a residual affine.delinearize_index that delinearizes the
5486  // merged output into its component parts.
5487  Value combinedElem = newDelinearize.getResult(m.delinStart);
5488  auto residualDelinearize = AffineDelinearizeIndexOp::create(
5489  rewriter, m.delinearize.getLoc(), combinedElem, basisToMerge);
5490 
5491  // Swap all the uses of the unaffected delinearize outputs to the new
5492  // delinearization so that the old code can be removed if this
5493  // linearize_index is the only user of the merged results.
5494  llvm::append_range(newDelinResults,
5495  newDelinearize.getResults().take_front(m.delinStart));
5496  llvm::append_range(newDelinResults, residualDelinearize.getResults());
5497  llvm::append_range(
5498  newDelinResults,
5499  newDelinearize.getResults().drop_front(m.delinStart + 1));
5500 
5501  delinearizeReplacements.push_back(newDelinResults);
5502  newIndex.push_back(combinedElem);
5503  newBasis.push_back(newSize);
5504  }
5505  llvm::append_range(newIndex, multiIndex.drop_front(prevMatchEnd));
5506  llvm::append_range(newBasis, linBasisRef.drop_front(prevMatchEnd));
5507  rewriter.replaceOpWithNewOp<AffineLinearizeIndexOp>(
5508  linearizeOp, newIndex, newBasis, linearizeOp.getDisjoint());
5509 
5510  for (auto [m, newResults] :
5511  llvm::zip_equal(matches, delinearizeReplacements)) {
5512  if (newResults.empty())
5513  continue;
5514  rewriter.replaceOp(m.delinearize, newResults);
5515  }
5516 
5517  return success();
5518  }
5519 };
5520 
5521 /// Strip leading zero from affine.linearize_index.
5522 ///
5523 /// `affine.linearize_index [%c0, ...a] by (%x, ...b)` can be rewritten
5524 /// to `affine.linearize_index [...a] by (...b)` in all cases.
5525 struct DropLinearizeLeadingZero final
5526  : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5528 
5529  LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5530  PatternRewriter &rewriter) const override {
5531  Value leadingIdx = op.getMultiIndex().front();
5532  if (!matchPattern(leadingIdx, m_Zero()))
5533  return failure();
5534 
5535  if (op.getMultiIndex().size() == 1) {
5536  rewriter.replaceOp(op, leadingIdx);
5537  return success();
5538  }
5539 
5540  SmallVector<OpFoldResult> mixedBasis = op.getMixedBasis();
5541  ArrayRef<OpFoldResult> newMixedBasis = mixedBasis;
5542  if (op.hasOuterBound())
5543  newMixedBasis = newMixedBasis.drop_front();
5544 
5545  rewriter.replaceOpWithNewOp<affine::AffineLinearizeIndexOp>(
5546  op, op.getMultiIndex().drop_front(), newMixedBasis, op.getDisjoint());
5547  return success();
5548  }
5549 };
5550 } // namespace
5551 
5552 void affine::AffineLinearizeIndexOp::getCanonicalizationPatterns(
5553  RewritePatternSet &patterns, MLIRContext *context) {
5554  patterns.add<CancelLinearizeOfDelinearizePortion, DropLinearizeLeadingZero,
5555  DropLinearizeUnitComponentsIfDisjointOrZero>(context);
5556 }
5557 
5558 //===----------------------------------------------------------------------===//
5559 // TableGen'd op method definitions
5560 //===----------------------------------------------------------------------===//
5561 
5562 #define GET_OP_CLASSES
5563 #include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
static Value getStride(Location loc, MemRefType mType, Value base, RewriterBase &rewriter)
Maps the 2-dim memref shape to the 64-bit stride.
Definition: AMXDialect.cpp:85
static AffineForOp buildAffineLoopFromConstants(OpBuilder &builder, Location loc, int64_t lb, int64_t ub, int64_t step, AffineForOp::BodyBuilderFn bodyBuilderFn)
Creates an affine loop from the bounds known to be constants.
Definition: AffineOps.cpp:2889
static bool hasTrivialZeroTripCount(AffineForOp op)
Returns true if the affine.for has zero iterations in trivial cases.
Definition: AffineOps.cpp:2610
static LogicalResult verifyMemoryOpIndexing(AffineMemOpTy op, AffineMapAttr mapAttr, Operation::operand_range mapOperands, MemRefType memrefType, unsigned numIndexOperands)
Verify common indexing invariants of affine.load, affine.store, affine.vector_load and affine....
Definition: AffineOps.cpp:3282
static void printAffineMinMaxOp(OpAsmPrinter &p, T op)
Definition: AffineOps.cpp:3460
static bool isResultTypeMatchAtomicRMWKind(Type resultType, arith::AtomicRMWKind op)
Definition: AffineOps.cpp:4093
static bool remainsLegalAfterInline(Value value, Region *src, Region *dest, const IRMapping &mapping, function_ref< bool(Value, Region *)> legalityCheck)
Checks if value known to be a legal affine dimension or symbol in src region remains legal if the ope...
Definition: AffineOps.cpp:62
static void printMinMaxBound(OpAsmPrinter &p, AffineMapAttr mapAttr, DenseIntElementsAttr group, ValueRange operands, StringRef keyword)
Prints a lower(upper) bound of an affine parallel loop with max(min) conditions in it.
Definition: AffineOps.cpp:4240
static void LLVM_ATTRIBUTE_UNUSED simplifyMapWithOperands(AffineMap &map, ArrayRef< Value > operands)
Simplify the map while exploiting information on the values in operands.
Definition: AffineOps.cpp:1036
static OpFoldResult foldMinMaxOp(T op, ArrayRef< Attribute > operands)
Fold an affine min or max operation with the given operands.
Definition: AffineOps.cpp:3496
static bool isTopLevelValueOrAbove(Value value, Region *region)
A utility function to check if a value is defined at the top level of region or is an argument of reg...
Definition: AffineOps.cpp:432
static LogicalResult canonicalizeLoopBounds(AffineForOp forOp)
Canonicalize the bounds of the given loop.
Definition: AffineOps.cpp:2464
static void simplifyExprAndOperands(AffineExpr &expr, unsigned numDims, unsigned numSymbols, ArrayRef< Value > operands)
Simplify expr while exploiting information from the values in operands.
Definition: AffineOps.cpp:822
static bool isValidAffineIndexOperand(Value value, Region *region)
Definition: AffineOps.cpp:492
static void canonicalizeMapOrSetAndOperands(MapOrSet *mapOrSet, SmallVectorImpl< Value > *operands)
Definition: AffineOps.cpp:1542
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
Definition: AffineOps.cpp:757
static ParseResult parseBound(bool isLower, OperationState &result, OpAsmParser &p)
Parse a for operation loop bounds.
Definition: AffineOps.cpp:2153
static std::optional< int64_t > getLowerBound(Value iv)
Gets the constant lower bound on an iv.
Definition: AffineOps.cpp:749
static void canonicalizePromotedSymbols(MapOrSet *mapOrSet, SmallVectorImpl< Value > *operands)
Definition: AffineOps.cpp:1448
static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType, VectorType vectorType)
Verify common invariants of affine.vector_load and affine.vector_store.
Definition: AffineOps.cpp:4642
static void simplifyMinOrMaxExprWithOperands(AffineMap &map, ArrayRef< Value > operands, bool isMax)
Simplify the expressions in map while making use of lower or upper bounds of its operands.
Definition: AffineOps.cpp:925
static ParseResult parseAffineMinMaxOp(OpAsmParser &parser, OperationState &result)
Definition: AffineOps.cpp:3473
static void composeSetAndOperands(IntegerSet &set, SmallVectorImpl< Value > &operands, bool composeAffineMin=false)
Compose any affine.apply ops feeding into operands of the integer set set by composing the maps of su...
Definition: AffineOps.cpp:3174
static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index, Region *region)
Returns true if the 'index' dimension of the memref defined by memrefDefOp is a statically shaped one...
Definition: AffineOps.cpp:349
static bool isNonNegativeBoundedBy(AffineExpr e, ArrayRef< Value > operands, int64_t k)
Check if e is known to be: 0 <= e < k.
Definition: AffineOps.cpp:697
static ParseResult parseAffineMapWithMinMax(OpAsmParser &parser, OperationState &result, MinMaxKind kind)
Parses an affine map that can contain a min/max for groups of its results, e.g., max(expr-1,...
Definition: AffineOps.cpp:4355
static AffineForOp buildAffineLoopFromValues(OpBuilder &builder, Location loc, Value lb, Value ub, int64_t step, AffineForOp::BodyBuilderFn bodyBuilderFn)
Creates an affine loop from the bounds that may or may not be constants.
Definition: AffineOps.cpp:2898
static void printDimAndSymbolList(Operation::operand_iterator begin, Operation::operand_iterator end, unsigned numDims, OpAsmPrinter &printer)
Prints dimension and symbol list.
Definition: AffineOps.cpp:497
static int64_t getLargestKnownDivisor(AffineExpr e, ArrayRef< Value > operands)
Returns the largest known divisor of e.
Definition: AffineOps.cpp:659
static void composeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Iterate over operands and fold away all those produced by an AffineApplyOp iteratively.
Definition: AffineOps.cpp:1196
static void legalizeDemotedDims(MapOrSet &mapOrSet, SmallVectorImpl< Value > &operands)
A valid affine dimension may appear as a symbol in affine.apply operations.
Definition: AffineOps.cpp:1496
static OpTy makeComposedMinMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Definition: AffineOps.cpp:1385
static void buildAffineLoopNestImpl(OpBuilder &builder, Location loc, BoundListTy lbs, BoundListTy ubs, ArrayRef< int64_t > steps, function_ref< void(OpBuilder &, Location, ValueRange)> bodyBuilderFn, LoopCreatorTy &&loopCreatorFn)
Builds an affine loop nest, using "loopCreatorFn" to create individual loop operations.
Definition: AffineOps.cpp:2848
static LogicalResult foldLoopBounds(AffineForOp forOp)
Fold the constant bounds of a loop.
Definition: AffineOps.cpp:2418
static LogicalResult replaceAffineMinBoundingBoxExpression(AffineMinOp minOp, AffineExpr dimOrSym, AffineMap *map, ValueRange dims, ValueRange syms)
Assuming dimOrSym is a quantity in the apply op map map and defined by minOp = affine_min(x_1,...
Definition: AffineOps.cpp:1061
static LogicalResult verifyDimAndSymbolIdentifiers(OpTy &op, Operation::operand_range operands, unsigned numDims)
Utility function to verify that a set of operands are valid dimension and symbol identifiers.
Definition: AffineOps.cpp:529
static OpFoldResult makeComposedFoldedMinMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Definition: AffineOps.cpp:1400
static bool isDimOpValidSymbol(ShapedDimOpInterface dimOp, Region *region)
Returns true if the result of the dim op is a valid symbol for region.
Definition: AffineOps.cpp:368
static bool isQTimesDPlusR(AffineExpr e, ArrayRef< Value > operands, int64_t &div, AffineExpr &quotientTimesDiv, AffineExpr &rem)
Check if expression e is of the form d*e_1 + e_2 where 0 <= e_2 < d.
Definition: AffineOps.cpp:725
static ParseResult deduplicateAndResolveOperands(OpAsmParser &parser, ArrayRef< SmallVector< OpAsmParser::UnresolvedOperand >> operands, SmallVectorImpl< Value > &uniqueOperands, SmallVectorImpl< AffineExpr > &replacements, AffineExprKind kind)
Given a list of lists of parsed operands, populates uniqueOperands with unique operands.
Definition: AffineOps.cpp:4308
static LogicalResult replaceDimOrSym(AffineMap *map, unsigned dimOrSymbolPosition, SmallVectorImpl< Value > &dims, SmallVectorImpl< Value > &syms, bool replaceAffineMin)
Replace all occurrences of AffineExpr at position pos in map by the defining AffineApplyOp expression...
Definition: AffineOps.cpp:1140
static LogicalResult verifyAffineMinMaxOp(T op)
Definition: AffineOps.cpp:3447
static void printBound(AffineMapAttr boundMap, Operation::operand_range boundOperands, const char *prefix, OpAsmPrinter &p)
Definition: AffineOps.cpp:2328
static void composeMultiResultAffineMap(AffineMap &map, SmallVectorImpl< Value > &operands, bool composeAffineMin=false)
Composes the given affine map with the given list of operands, pulling in the maps from any affine....
Definition: AffineOps.cpp:1299
static std::optional< SmallVector< int64_t > > foldCstValueToCstAttrBasis(ArrayRef< OpFoldResult > mixedBasis, MutableOperandRange mutableDynamicBasis, ArrayRef< Attribute > dynamicBasis)
Given mixed basis of affine.delinearize_index/linearize_index replace constant SSA values with the co...
Definition: AffineOps.cpp:4828
static LogicalResult canonicalizeMapExprAndTermOrder(AffineMap &map)
Canonicalize the result expression order of an affine map and return success if the order changed.
Definition: AffineOps.cpp:3659
static Value getZero(OpBuilder &b, Location loc, Type elementType)
Get zero value for an element type.
static Value getMemRef(Operation *memOp)
Returns the memref being read/written by a memref/affine load/store op.
Definition: Utils.cpp:246
static Operation * materializeConstant(Dialect *dialect, OpBuilder &builder, Attribute value, Type type, Location loc)
A utility function used to materialize a constant for a given attribute and type.
Definition: FoldUtils.cpp:50
static MLIRContext * getContext(OpFoldResult val)
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
union mlir::linalg::@1241::ArityGroupAndKind::Kind kind
static Operation::operand_range getLowerBoundOperands(AffineForOp forOp)
Definition: SCFToGPU.cpp:73
static Operation::operand_range getUpperBoundOperands(AffineForOp forOp)
Definition: SCFToGPU.cpp:78
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
RetTy walkPostOrder(AffineExpr expr)
Base type for affine expression.
Definition: AffineExpr.h:68
AffineExpr floorDiv(uint64_t v) const
Definition: AffineExpr.cpp:959
AffineExprKind getKind() const
Return the classification for this type.
Definition: AffineExpr.cpp:33
int64_t getLargestKnownDivisor() const
Returns the greatest known integral divisor of this affine expression.
Definition: AffineExpr.cpp:241
MLIRContext * getContext() const
Definition: AffineExpr.cpp:31
AffineExpr replace(AffineExpr expr, AffineExpr replacement) const
Sparse replace method.
Definition: AffineExpr.cpp:179
AffineExpr ceilDiv(uint64_t v) const
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
AffineMap getSliceMap(unsigned start, unsigned length) const
Returns the map consisting of length expressions starting from start.
Definition: AffineMap.cpp:655
MLIRContext * getContext() const
Definition: AffineMap.cpp:339
bool isFunctionOfDim(unsigned position) const
Return true if any affine expression involves AffineDimExpr position.
Definition: AffineMap.h:221
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
AffineMap shiftDims(unsigned shift, unsigned offset=0) const
Replace dims[offset ...
Definition: AffineMap.h:267
unsigned getNumSymbols() const
Definition: AffineMap.cpp:394
unsigned getNumDims() const
Definition: AffineMap.cpp:390
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:403
bool isFunctionOfSymbol(unsigned position) const
Return true if any affine expression involves AffineSymbolExpr position.
Definition: AffineMap.h:228
unsigned getNumResults() const
Definition: AffineMap.cpp:398
AffineMap replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements, unsigned numResultDims, unsigned numResultSyms) const
This method substitutes any uses of dimensions and symbols (e.g.
Definition: AffineMap.cpp:496
unsigned getNumInputs() const
Definition: AffineMap.cpp:399
AffineMap shiftSymbols(unsigned shift, unsigned offset=0) const
Replace symbols[offset ...
Definition: AffineMap.h:280
AffineExpr getResult(unsigned idx) const
Definition: AffineMap.cpp:407
AffineMap replace(AffineExpr expr, AffineExpr replacement, unsigned numResultDims, unsigned numResultSyms) const
Sparse replace method.
Definition: AffineMap.cpp:511
static AffineMap getConstantMap(int64_t val, MLIRContext *context)
Returns a single constant result affine map.
Definition: AffineMap.cpp:124
AffineMap getSubMap(ArrayRef< unsigned > resultPos) const
Returns the map consisting of the resultPos subset.
Definition: AffineMap.cpp:647
LogicalResult constantFold(ArrayRef< Attribute > operandConstants, SmallVectorImpl< Attribute > &results, bool *hasPoison=nullptr) const
Folds the results of the application of an affine map on the provided operands to a constant if possi...
Definition: AffineMap.cpp:430
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr >> exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
Definition: AffineMap.cpp:308
@ Paren
Parens surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
Definition: AsmPrinter.cpp:72
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:33
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:244
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition: Block.cpp:153
BlockArgListType getArguments()
Definition: Block.h:87
Operation & front()
Definition: Block.h:153
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:51
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:162
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition: Builders.cpp:227
AffineMap getDimIdentityMap()
Definition: Builders.cpp:382
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition: Builders.cpp:386
AffineExpr getAffineSymbolExpr(unsigned position)
Definition: Builders.cpp:367
AffineExpr getAffineConstantExpr(int64_t constant)
Definition: Builders.cpp:371
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
Definition: Builders.cpp:178
IntegerAttr getI64IntegerAttr(int64_t value)
Definition: Builders.cpp:111
IntegerType getIntegerType(unsigned width)
Definition: Builders.cpp:66
NoneType getNoneType()
Definition: Builders.cpp:87
BoolAttr getBoolAttr(bool value)
Definition: Builders.cpp:99
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
Definition: Builders.cpp:375
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
Definition: Builders.cpp:377
MLIRContext * getContext() const
Definition: Builders.h:56
AffineMap getSymbolIdentityMap()
Definition: Builders.cpp:395
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition: Builders.cpp:265
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:280
IndexType getIndexType()
Definition: Builders.cpp:50
An attribute that represents a reference to a dense integer vector or tensor object.
This is the interface that must be implemented by the dialects of operations to be inlined.
Definition: InliningUtils.h:44
DialectInlinerInterface(Dialect *dialect)
Definition: InliningUtils.h:46
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition: IRMapping.h:72
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition: Builders.h:623
Location getLoc() const
Accessors for the implied location.
Definition: Builders.h:656
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition: IntegerSet.h:44
unsigned getNumDims() const
Definition: IntegerSet.cpp:15
static IntegerSet get(unsigned dimCount, unsigned symbolCount, ArrayRef< AffineExpr > constraints, ArrayRef< bool > eqFlags)
MLIRContext * getContext() const
Definition: IntegerSet.cpp:57
unsigned getNumInputs() const
Definition: IntegerSet.cpp:17
ArrayRef< AffineExpr > getConstraints() const
Definition: IntegerSet.cpp:41
ArrayRef< bool > getEqFlags() const
Returns the equality bits, which specify whether each of the constraints is an equality or inequality...
Definition: IntegerSet.cpp:51
unsigned getNumSymbols() const
Definition: IntegerSet.cpp:16
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:63
This class provides a mutable adaptor for a range of operands.
Definition: ValueRange.h:118
void erase(unsigned subStart, unsigned subLen=1)
Erase the operands within the given sub-range.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void pop_back()
Pop last element from list.
Attribute erase(StringAttr name)
Erase the attribute with the given name from the list.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult parseAffineMapOfSSAIds(SmallVectorImpl< UnresolvedOperand > &operands, Attribute &map, StringRef attrName, NamedAttrList &attrs, Delimiter delimiter=Delimiter::Square)=0
Parses an affine map attribute where dims and symbols are SSA operands.
ParseResult parseAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)
Parse a list of assignments of the form (x1 = y1, x2 = y2, ...)
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseAffineExprOfSSAIds(SmallVectorImpl< UnresolvedOperand > &dimOperands, SmallVectorImpl< UnresolvedOperand > &symbOperands, AffineExpr &expr)=0
Parses an affine expression where dims and symbols are SSA operands.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands, ValueRange symOperands)=0
Prints an affine expression of SSA ids with SSA id names used instead of dims and symbols.
virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr, ValueRange operands)=0
Prints an affine map of SSA ids, where SSA id names are used in place of dims/symbols.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:348
This class helps build Operations.
Definition: Builders.h:207
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition: Builders.h:445
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition: Builders.cpp:429
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:431
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:398
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition: Builders.h:320
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:456
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition: Builders.h:442
This class represents a single result from folding an operation.
Definition: OpDefinition.h:272
This class represents an operand of an operation.
Definition: Value.h:257
A trait of region holding operations that defines a new scope for polyhedral optimization purposes.
This class provides the API for ops that are known to be isolated from above.
A trait used to provide symbol table functionalities to a region operation.
Definition: SymbolTable.h:452
This class implements the operand iterators for the Operation class.
Definition: ValueRange.h:43
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition: Operation.h:749
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:378
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition: Operation.h:230
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
Definition: Operation.cpp:218
operand_range::iterator operand_iterator
Definition: Operation.h:372
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:672
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:793
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition: Region.h:200
bool empty()
Definition: Region.h:60
Block & front()
Definition: Region.h:65
bool hasOneBlock()
Return true if this region has exactly one block.
Definition: Region.h:68
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:855
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:368
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:726
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void finalizeOpModification(Operation *op)
This method is used to signal the end of an in-place modification of the given operation.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues={})
Inline the operations of block 'source' into block 'dest' before the given position.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
Definition: PatternMatch.h:638
virtual void startOpModification(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
Definition: PatternMatch.h:622
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:529
This class represents a specific instance of an effect.
static DerivedEffect * get()
Returns a unique instance for the derived effect class.
static DefaultResource * get()
Returns a unique instance for the given effect class.
std::vector< SmallVector< int64_t, 8 > > operandExprStack
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:37
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
bool isIndex() const
Definition: Types.cpp:54
A variable that can be added to the constraint set as a "column".
static bool compare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
Return "true" if "lhs cmp rhs" was proven to hold.
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition: Value.cpp:39
AffineBound represents a lower or upper bound in the for operation.
Definition: AffineOps.h:550
AffineDmaStartOp starts a non-blocking DMA operation that transfers data from a source memref to a de...
Definition: AffineOps.h:106
AffineDmaWaitOp blocks until the completion of a DMA operation associated with the tag element 'tag[i...
Definition: AffineOps.h:330
An AffineValueMap is an affine map plus its ML value operands and results for analysis purposes.
LogicalResult canonicalize()
Attempts to canonicalize the map and operands.
Definition: AffineOps.cpp:4200
ArrayRef< Value > getOperands() const
AffineExpr getResult(unsigned i)
unsigned getNumResults() const
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition: ArithOps.cpp:359
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
constexpr auto RecursivelySpeculatable
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto NotSpeculatable
void buildAffineLoopNest(OpBuilder &builder, Location loc, ArrayRef< int64_t > lbs, ArrayRef< int64_t > ubs, ArrayRef< int64_t > steps, function_ref< void(OpBuilder &, Location, ValueRange)> bodyBuilderFn=nullptr)
Builds a perfect nest of affine.for loops, i.e., each loop except the innermost one contains only ano...
Definition: AffineOps.cpp:2911
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
Definition: AffineOps.cpp:1276
void extractForInductionVars(ArrayRef< AffineForOp > forInsts, SmallVectorImpl< Value > *ivs)
Extracts the induction variables from a list of AffineForOps and places them in the output argument i...
Definition: AffineOps.cpp:2825
bool isValidDim(Value value)
Returns true if the given Value can be used as a dimension id in the region of the closest surroundin...
Definition: AffineOps.cpp:290
bool isAffineInductionVar(Value val)
Returns true if the provided value is the induction variable of an AffineForOp or AffineParallelOp.
Definition: AffineOps.cpp:2797
SmallVector< OpFoldResult > makeComposedFoldedMultiResultAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Variant of makeComposedFoldedAffineApply suitable for multi-result maps.
Definition: AffineOps.cpp:1374
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
Definition: AffineOps.cpp:2801
void canonicalizeMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands)
Modifies both map and operands in-place so as to:
Definition: AffineOps.cpp:1619
OpFoldResult makeComposedFoldedAffineMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineMinOp that computes a maximum across the results of applying map to operands,...
Definition: AffineOps.cpp:1439
bool isAffineForInductionVar(Value val)
Returns true if the provided value is the induction variable of an AffineForOp.
Definition: AffineOps.cpp:2789
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
Definition: AffineOps.cpp:1329
OpFoldResult makeComposedFoldedAffineMin(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineMinOp that computes a minimum across the results of applying map to operands,...
Definition: AffineOps.cpp:1432
bool isTopLevelValue(Value value)
A utility function to check if a value is defined at the top level of an op with trait AffineScope or...
Definition: AffineOps.cpp:250
Region * getAffineAnalysisScope(Operation *op)
Returns the closest region enclosing op that is held by a non-affine operation; nullptr if there is n...
Definition: AffineOps.cpp:275
void fullyComposeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Given an affine map map and its input operands, this method composes into map, maps of AffineApplyOps...
Definition: AffineOps.cpp:1260
void canonicalizeSetAndOperands(IntegerSet *set, SmallVectorImpl< Value > *operands)
Canonicalizes an integer set the same way canonicalizeMapAndOperands does for affine maps.
Definition: AffineOps.cpp:1624
void extractInductionVars(ArrayRef< Operation * > affineOps, SmallVectorImpl< Value > &ivs)
Extracts the induction variables from a list of either AffineForOp or AffineParallelOp and places the...
Definition: AffineOps.cpp:2832
bool isValidSymbol(Value value)
Returns true if the given value can be used as a symbol in the region of the closest surrounding op t...
Definition: AffineOps.cpp:412
AffineParallelOp getAffineParallelInductionVarOwner(Value val)
Returns true if the provided value is among the induction variables of an AffineParallelOp.
Definition: AffineOps.cpp:2812
Region * getAffineScope(Operation *op)
Returns the closest region enclosing op that is held by an operation with trait AffineScope; nullptr ...
Definition: AffineOps.cpp:265
ParseResult parseDimAndSymbolList(OpAsmParser &parser, SmallVectorImpl< Value > &operands, unsigned &numDims)
Parses dimension and symbol list.
Definition: AffineOps.cpp:507
bool isAffineParallelInductionVar(Value val)
Returns true if val is the induction variable of an AffineParallelOp.
Definition: AffineOps.cpp:2793
AffineMinOp makeComposedAffineMin(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Returns an AffineMinOp obtained by composing map and operands with AffineApplyOps supplying those ope...
Definition: AffineOps.cpp:1394
BaseMemRefType getMemRefType(TensorType tensorType, const BufferizationOptions &options, MemRefLayoutAttrInterface layout={}, Attribute memorySpace=nullptr)
Return a MemRefType to which the TensorType can be bufferized.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
Definition: MemRefOps.cpp:45
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition: Query.cpp:21
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition: Remarks.h:491
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
Definition: AffineMap.cpp:766
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition: Matchers.h:490
OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val)
Convert int64_t to integer attributes of index type and return them as OpFoldResult.
const FrozenRewritePatternSet GreedyRewriteConfig bool * changed
AffineMap removeDuplicateExprs(AffineMap map)
Returns a map with the same dimension and symbol count as map, but whose results are the unique affin...
Definition: AffineMap.cpp:776
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::optional< int64_t > getBoundForAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols, ArrayRef< std::optional< int64_t >> constLowerBounds, ArrayRef< std::optional< int64_t >> constUpperBounds, bool isUpper)
Get a lower or upper (depending on isUpper) bound for expr while using the constant lower and upper b...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:304
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
AffineExprKind
Definition: AffineExpr.h:40
@ CeilDiv
RHS of ceildiv is always a constant or a symbolic expression.
@ Mod
RHS of mod is always a constant or a symbolic expression with a positive value.
@ DimId
Dimensional identifier.
@ FloorDiv
RHS of floordiv is always a constant or a symbolic expression.
@ SymbolId
Symbolic identifier.
AffineExpr getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs, AffineExpr rhs)
Definition: AffineExpr.cpp:68
std::function< SmallVector< Value >(OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Definition: Matchers.h:442
const FrozenRewritePatternSet & patterns
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
Definition: AffineExpr.cpp:643
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition: Matchers.h:369
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
Definition: AffineExpr.cpp:619
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition: Verifier.cpp:423
AffineMap foldAttributesIntoMap(Builder &b, AffineMap map, ArrayRef< OpFoldResult > operands, SmallVector< Value > &remainingValues)
Fold all attributes among the given operands into the affine map.
Definition: AffineMap.cpp:738
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
Definition: AffineExpr.cpp:629
Canonicalize the affine map result expression order of an affine min/max operation.
Definition: AffineOps.cpp:3713
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Definition: AffineOps.cpp:3716
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Definition: AffineOps.cpp:3730
Remove duplicated expressions in affine min/max ops.
Definition: AffineOps.cpp:3529
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Definition: AffineOps.cpp:3532
Merge an affine min/max op to its consumers if its consumer is also an affine min/max op.
Definition: AffineOps.cpp:3572
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Definition: AffineOps.cpp:3575
This is the representation of an operand reference.
This class represents a listener that may be used to hook into various actions within an OpBuilder.
Definition: Builders.h:285
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:314
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
Definition: PatternMatch.h:322
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) a properties of the provided type to be set on the operation on creation.
SmallVector< Value, 4 > operands
void addOperands(ValueRange newOperands)
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addTypes(ArrayRef< Type > newTypes)
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.
NamedAttrList attributes
SmallVector< Type, 4 > types
Types of the results of this operation.
Region * addRegion()
Create a region that should be attached to the operation.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.