MLIR  19.0.0git
Transforms.cpp
Go to the documentation of this file.
1 //===- Transforms.cpp - Linalg transformations as patterns ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements logic and helpers to expose Linalg transforms as rewrite
10 // patterns.
11 //
12 //===----------------------------------------------------------------------===//
13 
28 #include "mlir/IR/AffineExpr.h"
29 #include "mlir/IR/Matchers.h"
30 #include "mlir/Pass/Pass.h"
31 #include "mlir/Support/LLVM.h"
33 #include "llvm/ADT/ScopeExit.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <type_traits>
38 #include <utility>
39 
40 #define DEBUG_TYPE "linalg-transforms"
41 
42 using namespace mlir;
43 using namespace mlir::linalg;
44 
45 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ")
46 #define DBGSNL() (llvm::dbgs() << "\n")
47 
48 //===----------------------------------------------------------------------===//
49 // Transformations exposed as functional-style API calls.
50 //===----------------------------------------------------------------------===//
51 
52 //===----------------------------------------------------------------------===//
53 // peelLoop transformation.
54 //===----------------------------------------------------------------------===//
55 
56 /// Try to peel and canonicalize loop `op` and return the new result.
57 /// Also applies affine_min/max bounds simplification on the fly where relevant.
58 // TODO: Add support for scf.parallel and affine.for loops.
60  Operation *op) {
62  .Case<scf::ForOp>([&](scf::ForOp forOp) {
63  scf::ForOp partialIteration;
64  if (succeeded(scf::peelForLoopAndSimplifyBounds(rewriter, forOp,
65  partialIteration)))
66  return partialIteration->getResults();
67  assert(!partialIteration && "expected that loop was not peeled");
68  return forOp->getResults();
69  })
70  .Default([&](Operation *op) { return op->getResults(); });
71 }
72 
73 /// Peel 'loops' and applies affine_min/max bounds simplification on the fly
74 /// where relevant.
76  ArrayRef<scf::ForOp> loops) {
77  for (auto loopOp : loops)
78  peelLoop(rewriter, loopOp);
79 }
80 
81 //===----------------------------------------------------------------------===//
82 // pack transformation.
83 //===----------------------------------------------------------------------===//
84 
85 #ifndef NDEBUG
86 /// Return true if `map` has 0 or 1 result function of AffineDimExpr(dim).
87 static bool hasAtMostOneResultFunctionOfDim(AffineMap map, int64_t dim) {
88  bool found = false;
89  for (AffineExpr e : map.getResults()) {
90  if (!e.isFunctionOfDim(dim))
91  continue;
92  if (found)
93  return false;
94  found = true;
95  }
96  return true;
97 }
98 #endif // NDEBUG
99 
100 /// Return the index of the first result of `map` that is a function of
101 /// AffineDimExpr(dim), std::nullopt otherwise.
102 static std::optional<int64_t> getFirstResultIndexFunctionOf(AffineMap map,
103  int64_t dim) {
104  for (int64_t i = 0, e = map.getNumResults(); i < e; ++i) {
105  AffineExpr expr = map.getResult(i);
106  if (!expr.isFunctionOfDim(dim))
107  continue;
108  return i;
109  }
110  return std::nullopt;
111 }
112 
113 /// Perform one step of packing of a LinalgOp's metadata along `dim` into the
114 /// `newDim` at `iteratorTypes.size()` by:
115 /// 1. Appending `iteratorTypes[newDim]`, equal to `iteratorTypes[dim]`.
116 /// 2. Appending a `newDim` to the domain of every indexing map.
117 /// 3. For each operand (i.e. for each map in `indexingMaps`), perform packing
118 /// by potentially adding a `newDim` result to `map`.
119 /// The preserved invariant is that `iteratorTypes.size()` is always equal to
120 /// `map.getNumDims()` for every map in `indexingMaps`.
121 ///
122 /// Update `indexingMaps` and `iteratorTypes` inplace as one step of the update.
123 /// Return a vector that records the optional packing for each operand.
124 /// Return failure if the packed indexing cannot be represented with a LinalgOp.
125 ///
126 /// Further details:
127 /// ================
128 /// The current implementation of packing (i.e. data tiling) consists of
129 /// rewriting a linearized strip-mined form into a higher-dimensional access.
130 /// e.g. consider an access `A[I][f(j, k, l)]` and packing by 4; we rewrite
131 /// `I` into `4 * i + ii`, where `0 <= ii < 4`.
132 /// The access is further rewritten as `A[i][f(j, k, l)][ii]`.
133 ///
134 /// This rewrite into higher dimensional access is not possible for general
135 /// AffineExpr in Linalg atm, it is restricted to an AffineDimExpr:
136 /// e.g. consider an access `A[I + J][f(j, k, l)]` and packing by 4; we
137 /// rewrite `I + J` into `4 * i + ii + J`, where `0 <= ii < 4`.
138 /// The rewrite of the access would be a form not representable in Linalg:
139 /// `A[i + (ii + J) / 4][f(j, k, l)][(ii + J) % 4]`.
140 /// Note however that as `J` and `ii` iterate, the accesses do not have a
141 /// particular alignment, so packing does not achieve alignment in this case
142 ///
143 /// In the future, we may want to consider a mixed-form that allows some
144 /// alignment in the presence of multiple accesses:
145 /// `A[I][f(j, k, l)]` and `B[I + J][f(j, k, l)]`
146 /// And would rewrite accesses as:
147 /// `A[i][f(j, k, l)][ii]` and `B[4 * i + ii + J][f(j, k, l)]`
148 static FailureOr<SmallVector<std::optional<int64_t>>>
151  int64_t dim) {
152  int64_t newDim = iteratorTypes.size();
153  iteratorTypes.push_back(iteratorTypes[dim]);
154 
155  SmallVector<std::optional<int64_t>> packedDimPerIndexingMap(
156  indexingMaps.size(), std::nullopt);
157  SmallVector<AffineMap> newMaps;
158  for (int64_t operandIdx = 0, e = indexingMaps.size(); operandIdx < e;
159  ++operandIdx) {
160  AffineMap map = indexingMaps[operandIdx];
161 
162  // Add the `newDim` to map whatever the case.
163  assert(map.getNumDims() == newDim && "num dims invariant violation");
164  map = map.shiftDims(1, newDim);
165 
166  // Get the at-most-1 index of the result that is a function of `dim`.
167  // If we can find one, we insert `AffineDimExpr(newDim)` to the map, which
168  // logically chunks dimension `dim` into `K * dim + newDim`, where the
169  // packing factor `K` is specified separately.
170  assert(hasAtMostOneResultFunctionOfDim(map, dim) &&
171  "num results invariant violation");
172  auto maybeOperandDimensionToPack = getFirstResultIndexFunctionOf(map, dim);
173  if (!maybeOperandDimensionToPack.has_value()) {
174  newMaps.push_back(map);
175  continue;
176  }
177 
178  // We can only pack AffineDimExpr atm.
179  if (!isa<AffineDimExpr>(map.getResult(maybeOperandDimensionToPack.value())))
180  return failure();
181 
182  // Add `newDim` to the results of the map.
183  map = map.insertResult(Builder(map.getContext()).getAffineDimExpr(newDim),
184  map.getNumResults());
185  newMaps.push_back(map);
186 
187  // Record the that `operandIdx` is packed.
188  packedDimPerIndexingMap[operandIdx] = maybeOperandDimensionToPack;
189  }
190  indexingMaps = newMaps;
191 
192  return packedDimPerIndexingMap;
193 }
194 
195 namespace {
196 
197 /// Helper struct to encode packing along one dimension of a LinalgOp.
198 struct PackedOperandsDim {
199  OpFoldResult packedSize;
200  SmallVector<std::optional<int64_t>> packedDimForEachOperand;
201 };
202 
203 /// Helper struct to encode packing along all dimensions of a LinalgOp.
204 struct PackedOperandsDimList {
205  void pushBack(PackedOperandsDim &&packedOperandsDims) {
206  spec.emplace_back(packedOperandsDims);
207  }
208  /// Return all the dims that have been packed for operand @ `operandPos`.
209  SmallVector<int64_t> extractPackedDimsForOperand(int64_t operandPos);
210  /// Return all the pack sizes by which an operand @ `operandPos` is packed.
211  SmallVector<OpFoldResult> extractPackSizesForOperand(int64_t operandPos);
212 
213 private:
215 };
216 
217 } // namespace
218 
219 FailureOr<LowerPackResult> linalg::lowerPack(RewriterBase &rewriter,
220  tensor::PackOp packOp) {
221  // 1. Filter out NYI cases.
222  auto packedTensorType =
223  cast<RankedTensorType>(packOp->getResultTypes().front());
224  if (llvm::any_of(packOp.getStaticInnerTiles(),
225  [](int64_t size) { return ShapedType::isDynamic(size); })) {
226  return rewriter.notifyMatchFailure(
227  packOp,
228  "non-static shape NYI, needs a more powerful tensor.expand_shape op");
229  }
230 
231  Location loc = packOp->getLoc();
232  OpBuilder::InsertionGuard g(rewriter);
233  rewriter.setInsertionPoint(packOp);
234 
235  // 2. Compute the permutation vector to shuffle packed shape into the shape
236  // before any outer or inner permutations have been applied.
237  PackingMetadata packingMetadata = computePackingMetadata(
238  packedTensorType.getRank(), packOp.getInnerDimsPos());
239  SmallVector<int64_t> packedToStripMinedShapePerm =
241 
242  // 3. Compute the stripMinedShape: this is the packed shape before any outer
243  // or inner permutations have been applied.
244  SmallVector<int64_t> stripMinedShape(packedTensorType.getShape());
245  applyPermutationToVector(stripMinedShape, packedToStripMinedShapePerm);
246 
247  // 4. Pad the source of packOp to a shape we can expand into stripMinedShape.
248  SmallVector<OpFoldResult> lows(packOp.getSourceRank(),
249  rewriter.getIndexAttr(0));
250  SmallVector<OpFoldResult> highs(packOp.getSourceRank(),
251  rewriter.getIndexAttr(0));
252  for (auto [pos, innerSize] :
253  llvm::zip_equal(packOp.getInnerDimsPos(), packOp.getMixedTiles())) {
254  int outerPos =
255  packedToStripMinedShapePerm[packingMetadata.outerPositions[pos]];
256  OpFoldResult origSize =
257  tensor::getMixedSize(rewriter, loc, packOp.getSource(), pos);
258  OpFoldResult outerSize =
259  tensor::getMixedSize(rewriter, loc, packOp.getDest(), outerPos);
260  AffineExpr s0, d0, d1;
261  bindDims(rewriter.getContext(), d0, d1);
262  bindSymbols(rewriter.getContext(), s0);
263  auto map = AffineMap::get(/*dimCount=*/2, /*symbolCount=*/1, d0 * s0 - d1);
265  rewriter, loc, map, {outerSize, origSize, innerSize});
266  }
267  RankedTensorType collapsed = tensor::CollapseShapeOp::inferCollapsedType(
268  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape),
269  packingMetadata.reassociations);
270  Value paddingValue = packOp.getPaddingValue();
271  if (!paddingValue) {
272  paddingValue = rewriter.create<arith::ConstantOp>(
273  loc, rewriter.getZeroAttr(getElementTypeOrSelf(collapsed)));
274  }
275  auto padOp =
276  rewriter.create<tensor::PadOp>(loc, collapsed, packOp.getSource(), lows,
277  highs, paddingValue, /*nofold=*/false);
278 
279  LLVM_DEBUG(
280  DBGSNL(); DBGSNL(); llvm::interleaveComma(packingMetadata.insertPositions,
281  DBGS() << "insertPositions: ");
282  DBGSNL(); llvm::interleaveComma(packingMetadata.outerPositions,
283  DBGS() << "outerPositions: ");
284  DBGSNL(); llvm::interleaveComma(packedTensorType.getShape(),
285  DBGS() << "packedShape: ");
286  DBGSNL();
287  llvm::interleaveComma(packedToStripMinedShapePerm,
288  DBGS() << "packedToStripMinedShapePerm: ");
289  DBGSNL(); llvm::interleaveComma(
290  packingMetadata.reassociations, DBGS() << "reassociations: ",
291  [&](ReassociationIndices ri) {
292  llvm::interleaveComma(ri, llvm::dbgs() << "|");
293  });
294  DBGSNL();
295  llvm::interleaveComma(stripMinedShape, DBGS() << "stripMinedShape: ");
296  DBGSNL(); DBGS() << "collapsed type: " << collapsed; DBGSNL(););
297 
298  if (packOp.isLikePad()) {
299  // Pack ops which operate as simple pads may not produce legal
300  // tensor.insert_slice operations when the packed type does not rank reduce
301  // to the padded type.
302  SliceVerificationResult rankReduces =
303  isRankReducedType(packedTensorType, padOp.getResultType());
304 
305  if (rankReduces == SliceVerificationResult::Success) {
306  // This pack is just a plain pad.
307  // Just insert the pad in the higher ranked tensor.
308  auto emptyOp =
309  rewriter.create<tensor::EmptyOp>(loc, packedTensorType, ValueRange{});
310  // Offsets.
311  SmallVector<OpFoldResult> zeros(packOp.getDestRank(),
312  rewriter.getIndexAttr(0));
313  // Strides.
314  SmallVector<OpFoldResult> ones(packOp.getDestRank(),
315  rewriter.getIndexAttr(1));
317  tensor::getMixedSizes(rewriter, loc, packOp.getDest());
318 
319  auto insertSliceOp = rewriter.create<tensor::InsertSliceOp>(
320  loc, /*source=*/padOp, /*dest=*/emptyOp,
321  /*offsets=*/zeros, sizes,
322  /*strides=*/ones);
323 
324  LLVM_DEBUG(DBGS() << "insert_slice op: " << insertSliceOp; DBGSNL(););
325 
326  rewriter.replaceOp(packOp, insertSliceOp->getResults());
327 
328  return LowerPackResult{padOp, /*reshapeOp=*/nullptr,
329  /*transposeOp=*/nullptr};
330  }
331  }
332 
333  // 5. Expand from the padded result to the stripMinedShape.
334  auto expandShapeResultType =
335  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape);
336  auto reshapeOp = rewriter.create<tensor::ExpandShapeOp>(
337  loc, expandShapeResultType, padOp.getResult(),
338  packingMetadata.reassociations);
339 
340  // 6. Transpose stripMinedShape to packedShape.
341  SmallVector<int64_t> transpPerm =
342  invertPermutationVector(packedToStripMinedShapePerm);
343  auto transposeOp = rewriter.create<linalg::TransposeOp>(
344  loc, reshapeOp.getResult(), packOp.getDest(), transpPerm);
345 
346  LLVM_DEBUG(DBGSNL(); DBGSNL(); DBGSNL();
347  DBGS() << "reshape op: " << reshapeOp; DBGSNL();
348  llvm::interleaveComma(transpPerm, DBGS() << "transpPerm: ");
349  DBGSNL(); DBGS() << "transpose op: " << transposeOp; DBGSNL(););
350 
351  // 7. Replace packOp by transposeOp.
352  rewriter.replaceOp(packOp, transposeOp->getResults());
353 
354  return LowerPackResult{padOp, reshapeOp, transposeOp};
355 }
356 
357 FailureOr<LowerUnPackOpResult> linalg::lowerUnPack(RewriterBase &rewriter,
358  tensor::UnPackOp unPackOp) {
359  Location loc = unPackOp->getLoc();
360  OpBuilder::InsertionGuard g(rewriter);
361  rewriter.setInsertionPoint(unPackOp);
362 
363  RankedTensorType packedTensorType = unPackOp.getSourceType();
364  int64_t packedRank = packedTensorType.getRank();
365 
366  OpFoldResult zero = rewriter.getIndexAttr(0), one = rewriter.getIndexAttr(1);
367  auto destTensorType = cast<RankedTensorType>(unPackOp.getDest().getType());
368  if (unPackOp.isLikeUnPad()) {
369  // This unpack is just a plain unpad.
370  // Just extract the slice from the higher ranked tensor.
371  ArrayRef<int64_t> destShape = destTensorType.getShape();
372  // The inner dimensions stay the same as the destination tensor, but the
373  // outer ones are additional 1s.
374  SmallVector<OpFoldResult> sizes(packedRank - destShape.size(), one);
375  sizes.append(tensor::getMixedSizes(rewriter, loc, unPackOp.getDest()));
376 
377  auto extractSliceOp = rewriter.create<tensor::ExtractSliceOp>(
378  loc, destTensorType, unPackOp.getSource(),
379  SmallVector<OpFoldResult>(packedRank, zero), sizes,
380  SmallVector<OpFoldResult>(packedRank, one));
381 
382  rewriter.replaceOp(unPackOp, extractSliceOp->getResults());
383 
384  return LowerUnPackOpResult{/*emptyOp=*/nullptr, /*transposeOp=*/nullptr,
385  /*reshapeOp=*/nullptr, extractSliceOp};
386  }
387 
388  // 1. Compute the permutation vector to shuffle packed shape into the shape
389  // before any outer or inner permutations have been applied.
390  PackingMetadata packingMetadata;
391  SmallVector<int64_t> packedToStripMinedShapePerm =
392  tensor::getUnPackInverseSrcPerm(unPackOp, packingMetadata);
393 
394  // 2. Compute the stripMinedShape: this is the packed shape without outer and
395  // inner permutations.
396  SmallVector<int64_t> stripMinedShape(packedTensorType.getShape());
397  applyPermutationToVector(stripMinedShape, packedToStripMinedShapePerm);
398 
399  // 3. Transpose packedShape to stripMinedShape.
400  RankedTensorType stripMinedTensorType =
401  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape);
402  RankedTensorType collapsedType = tensor::CollapseShapeOp::inferCollapsedType(
403  stripMinedTensorType, packingMetadata.reassociations);
404 
405  // Get dynamic dims from input tensor based on packedToStripMinedShapePerm
406  // permutation.
408  tensor::getMixedSizes(rewriter, loc, unPackOp.getSource());
409  applyPermutationToVector(dims, packedToStripMinedShapePerm);
410  auto emptyOp = rewriter.create<tensor::EmptyOp>(
411  loc, dims, stripMinedTensorType.getElementType());
412  auto transposeOp = rewriter.create<linalg::TransposeOp>(
413  loc, unPackOp.getSource(), emptyOp, packedToStripMinedShapePerm);
414 
415  LLVM_DEBUG(
416  DBGSNL(); DBGSNL(); llvm::interleaveComma(packingMetadata.insertPositions,
417  DBGS() << "insertPositions: ");
418  DBGSNL(); llvm::interleaveComma(packedTensorType.getShape(),
419  DBGS() << "packedShape: ");
420  DBGSNL();
421  llvm::interleaveComma(packedToStripMinedShapePerm,
422  DBGS() << "packedToStripMinedShapePerm: ");
423  DBGSNL(); llvm::interleaveComma(
424  packingMetadata.reassociations, DBGS() << "reassociations: ",
425  [&](ReassociationIndices ri) {
426  llvm::interleaveComma(ri, llvm::dbgs() << "|");
427  });
428  DBGSNL();
429  llvm::interleaveComma(stripMinedShape, DBGS() << "stripMinedShape: ");
430  DBGSNL(); DBGS() << "collapsed type: " << collapsedType; DBGSNL(););
431 
432  // 4. Collapse from the stripMinedShape to the padded result.
433  auto reshapeOp = rewriter.create<tensor::CollapseShapeOp>(
434  loc, collapsedType, transposeOp->getResult(0),
435  packingMetadata.reassociations);
436 
437  // 5. ExtractSlice.
438  int64_t destRank = destTensorType.getRank();
439  auto extractSliceOp = rewriter.create<tensor::ExtractSliceOp>(
440  loc, destTensorType, reshapeOp->getResult(0),
441  SmallVector<OpFoldResult>(destRank, zero),
442  tensor::getMixedSizes(rewriter, loc, unPackOp.getDest()),
443  SmallVector<OpFoldResult>(destRank, one));
444 
445  // 6. Inject a copy to preserve DPS.
446  auto copyOp = rewriter.create<linalg::CopyOp>(
447  loc, extractSliceOp->getResult(0), unPackOp.getDest());
448 
449  // 7. Replace unPackOp by copyOp.
450  rewriter.replaceOp(unPackOp, copyOp->getResults());
451 
452  return LowerUnPackOpResult{emptyOp, transposeOp, reshapeOp, extractSliceOp};
453 }
454 
456 PackedOperandsDimList::extractPackedDimsForOperand(int64_t operandPos) {
458  for (auto &i : spec) {
459  if (!i.packedDimForEachOperand[operandPos].has_value())
460  continue;
461  res.push_back(i.packedDimForEachOperand[operandPos].value());
462  }
463  return res;
464 }
465 
467 PackedOperandsDimList::extractPackSizesForOperand(int64_t operandPos) {
469  for (auto &i : spec) {
470  if (!i.packedDimForEachOperand[operandPos].has_value())
471  continue;
472  res.push_back(i.packedSize);
473  }
474  return res;
475 }
476 
477 /// Implement packing of a single LinalgOp by performing packing by
478 /// `packedSizes`. There must be one packedSizes entry per `linalgOp` iterator.
479 /// Return the packed Linalg op on success, failure otherwise.
480 FailureOr<PackResult> linalg::pack(RewriterBase &rewriter,
481  linalg::LinalgOp linalgOp,
482  ArrayRef<OpFoldResult> packedSizes) {
483  if (packedSizes.size() != linalgOp.getNumLoops()) {
484  return rewriter.notifyMatchFailure(linalgOp,
485  "incorrect number of pack sizes");
486  }
487 
488  Location loc = linalgOp->getLoc();
489  SmallVector<AffineMap> indexingMaps = linalgOp.getIndexingMapsArray();
490  SmallVector<utils::IteratorType> iteratorTypes =
491  linalgOp.getIteratorTypesArray();
492  LLVM_DEBUG(DBGS() << "Start packing: " << linalgOp << "\n";
493  llvm::interleaveComma(indexingMaps, DBGS() << "maps: "); DBGSNL();
494  llvm::interleaveComma(iteratorTypes, DBGS() << "iterators: ");
495  DBGSNL(););
496 
499  // Step 1. Pack each dim of the LinalgOp metadata by packedSizes[i].
500  PackedOperandsDimList listOfPackedOperandsDim;
501  for (int64_t i = 0, e = packedSizes.size(); i < e; ++i) {
502  std::optional<int64_t> maybeConstant = getConstantIntValue(packedSizes[i]);
503  // Skip tile sizes explicitly set to 0.
504  if (maybeConstant.has_value() && maybeConstant.value() == 0)
505  continue;
506 
507  PackedOperandsDim packedOperandsDims;
508  packedOperandsDims.packedSize = packedSizes[i];
509  FailureOr<SmallVector<std::optional<int64_t>>>
510  maybePackedDimForEachOperand =
511  packLinalgMetadataOnce(indexingMaps, iteratorTypes, i);
512  if (failed(maybePackedDimForEachOperand))
513  return failure();
514  packedOperandsDims.packedDimForEachOperand = *maybePackedDimForEachOperand;
515  listOfPackedOperandsDim.pushBack(std::move(packedOperandsDims));
516 
517  LLVM_DEBUG(
518  DBGS() << "++++ After pack size #" << i << ": " << packedSizes[i]
519  << "\n";
520  llvm::interleaveComma(indexingMaps, DBGS() << "maps: "); DBGSNL();
521  llvm::interleaveComma(iteratorTypes, DBGS() << "iterators: "); DBGSNL();
522  llvm::interleaveComma(packedOperandsDims.packedDimForEachOperand,
523  DBGS() << "packedDimForEachOperand: ");
524  DBGSNL(););
525  }
526 
527  // Step 2. Propagate packing to all LinalgOp operands.
528  SmallVector<Value> inputsAndInits, results;
529  SmallVector<OpOperand *> initOperands = llvm::to_vector(llvm::map_range(
530  linalgOp.getDpsInitsMutable(), [](OpOperand &o) { return &o; }));
531  SmallVector<OpOperand *> inputOperands = linalgOp.getDpsInputOperands();
532  for (const auto &operandsList : {inputOperands, initOperands}) {
533  for (OpOperand *opOperand : operandsList) {
534  int64_t pos = opOperand->getOperandNumber();
535  Value operand = opOperand->get();
536  SmallVector<int64_t> innerPos =
537  listOfPackedOperandsDim.extractPackedDimsForOperand(pos);
538  SmallVector<OpFoldResult> innerPackSizes =
539  listOfPackedOperandsDim.extractPackSizesForOperand(pos);
540  LLVM_DEBUG(
541  DBGS() << "operand: " << operand << "\n";
542  llvm::interleaveComma(innerPos, DBGS() << "innerPos: "); DBGSNL();
543  llvm::interleaveComma(innerPackSizes, DBGS() << "innerPackSizes: ");
544  DBGSNL(););
545  if (innerPackSizes.empty()) {
546  inputsAndInits.push_back(operand);
547  continue;
548  }
549  Value dest = tensor::PackOp::createDestinationTensor(
550  rewriter, loc, operand, innerPackSizes, innerPos,
551  /*outerDimsPerm=*/{});
552  ShapedType operandType = cast<ShapedType>(operand.getType());
553  bool areConstantTiles =
554  llvm::all_of(innerPackSizes, [](OpFoldResult tile) {
555  return getConstantIntValue(tile).has_value();
556  });
557  if (areConstantTiles && operandType.hasStaticShape() &&
558  !tensor::PackOp::requirePaddingValue(
559  operandType.getShape(), innerPos,
560  cast<ShapedType>(dest.getType()).getShape(), {},
561  innerPackSizes)) {
562  packOps.push_back(rewriter.create<tensor::PackOp>(
563  loc, operand, dest, innerPos, innerPackSizes));
564  } else {
565  // TODO: value of the padding attribute should be determined by
566  // consumers.
567  auto zeroAttr =
568  rewriter.getZeroAttr(getElementTypeOrSelf(dest.getType()));
569  Value zero = rewriter.create<arith::ConstantOp>(loc, zeroAttr);
570  packOps.push_back(rewriter.create<tensor::PackOp>(
571  loc, operand, dest, innerPos, innerPackSizes, zero));
572  }
573  inputsAndInits.push_back(packOps.back());
574  }
575  }
576 
577  // Step 3. Build the packed op, use the type of `inits` as result types.
578  ValueRange inputs =
579  ValueRange{inputsAndInits}.take_front(linalgOp.getNumDpsInputs());
580  ValueRange inits =
581  ValueRange{inputsAndInits}.take_back(linalgOp.getNumDpsInits());
582  auto packedLinalgOp = rewriter.create<linalg::GenericOp>(
583  linalgOp.getLoc(), inits.getTypes(), inputs, inits, indexingMaps,
584  iteratorTypes);
585  packedLinalgOp.getRegion().takeBody(linalgOp->getRegion(0));
586 
587  // Step 4. Propagate packing to all the op results.
588  for (OpResult result : packedLinalgOp->getResults()) {
589  int64_t resultNum = result.getResultNumber();
590  tensor::PackOp maybePackedInit =
591  inits[resultNum].getDefiningOp<tensor::PackOp>();
592  if (!maybePackedInit) {
593  results.push_back(result);
594  continue;
595  }
596  // Build the symmetrical UnPackOp to the existing PackOp.
597  unPackOps.push_back(rewriter.create<tensor::UnPackOp>(
598  packedLinalgOp->getLoc(), result, maybePackedInit.getSource(),
599  maybePackedInit.getInnerDimsPos(), maybePackedInit.getMixedTiles()));
600  results.push_back(unPackOps.back());
601  }
602 
603  // Step 5. Replace `linalgOp`.
604  rewriter.replaceOp(linalgOp, results);
605 
606  // Return packedLinalgOp.
607  return PackResult{packOps,
608  cast<linalg::LinalgOp>(packedLinalgOp.getOperation()),
609  unPackOps};
610 }
611 
612 //===----------------------------------------------------------------------===//
613 // packTranspose transformation.
614 //===----------------------------------------------------------------------===//
615 
616 /// Return a copy of `tensorType` after permutation by `permutationVector`.
617 // Note: Should be a new method in of MemRef/RankedTensor/VectorType::Builder
618 // but this would introduce a dependence on Dialect in IR.
619 // TODO: Restructure.
620 static RankedTensorType permuteShape(RankedTensorType tensorType,
621  ArrayRef<int64_t> permutationVector) {
622  SmallVector<int64_t> shape(tensorType.getShape());
623  applyPermutationToVector(shape, permutationVector);
624  return RankedTensorType::Builder(tensorType).setShape(shape);
625 }
626 
627 /// Return a new GenericOp obtained by transposing opOperand by the permutation
628 /// vector:
629 /// - the corresponding indexing map is transposed by `permutation`
630 /// - the corresponding operand value is replaced by `transposedValue`
631 /// `linalgOp` is replaced by the return op in the process.
632 /// Asserts that `transposedValue` is of the proper transposed ShapedType.
634  RewriterBase &rewriter, LinalgOp linalgOp, OpOperand &opOperand,
635  ArrayRef<int64_t> permutation, Value transposedValue) {
636  // Sanity check the operand.
637  assert(linalgOp == opOperand.getOwner() && "linalg op must own the operand");
638 
639  // Sanity check of the expected transposed tensor type.
640  auto tensorType = permuteShape(
641  cast<RankedTensorType>(opOperand.get().getType()), permutation);
642  (void)tensorType;
643  assert(tensorType == transposedValue.getType() &&
644  "expected tensor type mismatch");
645 
646  // Compute the transposed indexing map.
647  // Sigh unsigned pollution.
648  SmallVector<unsigned> tmpTransposition = llvm::to_vector(
649  llvm::map_range(permutation, [](int64_t i) -> unsigned { return i; }));
650  AffineMap permutationMap =
651  AffineMap::getPermutationMap(tmpTransposition, rewriter.getContext());
652  AffineMap transposedMap =
653  permutationMap.compose(linalgOp.getMatchingIndexingMap(&opOperand));
654 
655  // Set the transposed indexing map in the proper position.
656  SmallVector<AffineMap> indexingMaps = linalgOp.getIndexingMapsArray();
657  indexingMaps[linalgOp.getIndexingMapIndex(&opOperand)] = transposedMap;
658  // Set the transposedValue in the proper operand position.
659  SmallVector<Value> operands = linalgOp->getOperands();
660  operands[opOperand.getOperandNumber()] = transposedValue;
661 
662  ValueRange operandsRef(operands);
663  auto transposedGenericOp = rewriter.create<linalg::GenericOp>(
664  /*location=*/linalgOp->getLoc(),
665  /*resultTensorTypes=*/
666  operandsRef.drop_front(linalgOp.getNumDpsInputs()).getTypes(),
667  /*inputs=*/operandsRef.take_front(linalgOp.getNumDpsInputs()),
668  /*outputs=*/operandsRef.drop_front(linalgOp.getNumDpsInputs()),
669  /*indexingMaps=*/indexingMaps,
670  /*iteratorTypes=*/linalgOp.getIteratorTypesArray());
671  transposedGenericOp.getRegion().takeBody(linalgOp->getRegion(0));
672  rewriter.replaceOp(linalgOp, transposedGenericOp->getResults());
673 
674  return cast<linalg::LinalgOp>(transposedGenericOp.getOperation());
675 }
676 
677 FailureOr<PackTransposeResult>
678 linalg::packTranspose(RewriterBase &rewriter, tensor::PackOp packOp,
679  linalg::LinalgOp linalgOp, tensor::UnPackOp maybeUnPackOp,
680  ArrayRef<int64_t> outerPerm,
681  ArrayRef<int64_t> innerPerm) {
682  Location loc = linalgOp.getLoc();
683 
684  // Step 1. Transpose packOp.
685  rewriter.setInsertionPoint(packOp);
686  tensor::PackOp transposedPackOp =
687  packOp.createTransposedClone(rewriter, loc, innerPerm, outerPerm);
688 
689  if (!packOp.getResult().hasOneUse())
690  return rewriter.notifyMatchFailure(linalgOp, "expect single pack use");
691 
692  OpOperand &packUse = *packOp->getUses().begin();
693  if (packUse.getOwner() != linalgOp) {
694  return rewriter.notifyMatchFailure(
695  linalgOp, "not a single use by the LinalgOp target");
696  }
697  if (maybeUnPackOp &&
698  (!linalgOp.isDpsInit(&packUse) ||
699  maybeUnPackOp.getSource() != linalgOp.getTiedOpResult(&packUse))) {
700  return rewriter.notifyMatchFailure(linalgOp,
701  "not produced by the LinalgOp target");
702  }
703 
704  // Step 2. Transpose linalgOp.
705  // transposedPackOp.getOuterDimsPerm() may be empty, in which case it is the
706  // identity. Don't rely on it.
707  int64_t numLeadingDims = packOp.getSourceRank();
708  int64_t numTrailingDims = packOp.getInnerDimsPos().size();
709  // Step 2.a. Compute the permutation on the whole operand.
710  // Leading part just reuse the outerPerm.
711  SmallVector<int64_t> permutation(outerPerm);
712  if (permutation.empty())
713  llvm::append_range(permutation, llvm::seq<int64_t>(0, numLeadingDims));
714  // Trailing part needs to reindex positions by `numLeadingDims`.
715  if (innerPerm.empty()) {
716  llvm::append_range(
717  permutation,
718  llvm::seq<int64_t>(numLeadingDims, numLeadingDims + numTrailingDims));
719  } else {
720  llvm::append_range(permutation,
721  llvm::map_range(innerPerm, [&](int64_t pos) {
722  return numLeadingDims + pos;
723  }));
724  }
725  if (!isPermutationVector(permutation))
726  return rewriter.notifyMatchFailure(linalgOp, "invalid permutation");
727 
728  // Step 2.b. Save the transposedPackUse operand number in case we need to
729  // get the tied OpResult after `linalgOp` has been replaced.
730  int64_t packUseOperandNumber = packUse.getOperandNumber();
731  // Step 2.c. Actually perform the transposition.
732  rewriter.setInsertionPoint(linalgOp);
733  linalg::LinalgOp transposedLinalgOp = transposeOneLinalgOperandAndReplace(
734  rewriter, linalgOp, packUse, permutation, transposedPackOp.getResult());
735 
736  // Step 3. Maybe transpose unPackOp.
737  tensor::UnPackOp transposedUnPackOp;
738  if (maybeUnPackOp) {
739  OpOperand &opOperand =
740  transposedLinalgOp->getOpOperand(packUseOperandNumber);
741  OpResult transposedResult = transposedLinalgOp.getTiedOpResult(&opOperand);
742  rewriter.setInsertionPoint(maybeUnPackOp);
743  transposedUnPackOp = maybeUnPackOp.createTransposedClone(
744  rewriter, loc, transposedResult, innerPerm, outerPerm);
745 
746  rewriter.replaceOp(maybeUnPackOp, transposedUnPackOp->getResults());
747  }
748 
749  // Step 4. Finally, replace packOp now that we don't need it anymore.
750  rewriter.replaceOp(packOp, transposedPackOp->getResults());
751 
752  return PackTransposeResult{transposedPackOp, transposedLinalgOp,
753  transposedUnPackOp};
754 }
755 
756 //===----------------------------------------------------------------------===//
757 // packMatmulGreedily transformation.
758 //===----------------------------------------------------------------------===//
759 
760 /// Pack a LinalgOp by greedily inferring matmul dimensions (m, n, k) where m
761 /// and n are proper parallel dimensions and k is a proper reduction
762 /// dimension. Packing occurs by rewriting the op as a linalg.generic and
763 /// calling linalg::pack by `mnkPackedSizes`. The order of the packed
764 /// dimensions is customizable: the `mnkOrder` is a permutation of {0, 1, 2}
765 /// to reorder {m, n, k} into one of the 8 possible forms. The outer
766 /// dimensions of the operands are not permuted at this time, this is left for
767 /// future work.
768 FailureOr<PackResult>
769 linalg::packMatmulGreedily(RewriterBase &rewriter, LinalgOp linalgOp,
770  ArrayRef<OpFoldResult> mnkPackedSizes,
771  ArrayRef<int64_t> mnkPaddedSizesNextMultipleOf,
772  ArrayRef<int64_t> mnkOrder) {
773  assert(mnkPackedSizes.size() == 3 && "unexpected num of packing sizes");
774  assert((mnkPaddedSizesNextMultipleOf.empty() ||
775  mnkPaddedSizesNextMultipleOf.size() == 3) &&
776  "num of packing sizes next multiple should be empty or of size 3");
777  assert(mnkOrder.size() == 3 && "unexpected mnkOrder size");
778  assert(isPermutationVector(mnkOrder) && "expected a permutation");
779 
780  int64_t numLoops = linalgOp.getNumLoops();
781  if (numLoops <= 2) {
782  LLVM_DEBUG(DBGS() << "need 3+ loops to find a matmul to pack, got "
783  << numLoops << "\nin: " << linalgOp << "\n");
784  return rewriter.notifyMatchFailure(
785  linalgOp, "need 3+ loops to find a matmul to pack");
786  }
787 
788  // Locally adjust the desired iterator position of mnk and packing sizes.
789  int64_t numPackedDims = mnkPackedSizes.size();
790  SmallVector<int64_t> mmnnkkPos(numPackedDims);
791  for (int64_t i = 0, e = numPackedDims; i < e; ++i)
792  mmnnkkPos[i] = numLoops - numPackedDims + mnkOrder[i];
793  SmallVector<OpFoldResult> packedSizes(numPackedDims);
794  for (int64_t i = 0, e = numPackedDims; i < e; ++i)
795  packedSizes[mnkOrder[i]] = mnkPackedSizes[i];
796  SmallVector<int64_t> paddedSizesNextMultipleOf(numPackedDims);
797  for (int64_t i = 0, e = numPackedDims; i < e; ++i) {
798  paddedSizesNextMultipleOf[mnkOrder[i]] =
799  mnkPaddedSizesNextMultipleOf.empty() ? 0
800  : mnkPaddedSizesNextMultipleOf[i];
801  }
802 
803  // 1. Infer dims that are important for matmul.
804  FailureOr<ContractionDimensions> maybeDimensions =
805  inferContractionDims(linalgOp);
806  if (failed(maybeDimensions)) {
807  LLVM_DEBUG(DBGS() << "couldn't infer matmul iterators in: " << linalgOp
808  << "\n");
809  return rewriter.notifyMatchFailure(linalgOp,
810  "couldn't infer matmul iterators");
811  }
812 
813  // 2. Normalize linalgOp to an kmn-matmul-like with [red, par, par] most
814  // minor iterators. In cases with multiple options for m, n, k bias towards
815  // the most minor embedding.
816  // If we wanted a different normalization order, this is where it would have
817  // to plug a heuristic.
818  int64_t mPos = maybeDimensions->m.back(), nPos = maybeDimensions->n.back(),
819  kPos = maybeDimensions->k.back();
820  LLVM_DEBUG(DBGSNL(); DBGSNL(); DBGSNL();
821  DBGS() << "Start packing generic op greedily with (m@" << mPos
822  << ", n@" << nPos << ", k@" << kPos << "): " << linalgOp
823  << "\n";);
824 
825  // 2.a. Rewrite as a generic.
826  auto genericOp = dyn_cast<GenericOp>(linalgOp.getOperation());
827  if (!genericOp) {
828  FailureOr<GenericOp> generalizeResult =
829  generalizeNamedOp(rewriter, linalgOp);
830  assert(succeeded(generalizeResult) && "unexpected failure generalizing op");
831  genericOp = *generalizeResult;
832  }
833 
834  // 2.b. Interchange to move the dimensions (k, m, n) as most-minor
835  // iterators. Note that this only normalized the iteration order and does
836  // not change the indexings of any operand.
837  SmallVector<int64_t> permutation =
838  computePermutationVector(numLoops, {mPos, nPos, kPos}, mmnnkkPos);
839  LLVM_DEBUG(llvm::interleaveComma(permutation, DBGS() << "perm: "); DBGSNL(););
840  // Sign .. unsigned pollution.
841  SmallVector<unsigned> unsignedPerm(permutation.begin(), permutation.end());
842  FailureOr<GenericOp> interchangeResult =
843  interchangeGenericOp(rewriter, genericOp, unsignedPerm);
844  assert(succeeded(interchangeResult) && "unexpected failure interchanging op");
845  genericOp = *interchangeResult;
846  LLVM_DEBUG(DBGS() << "Generalized Op to pack: " << genericOp << "\n";);
847 
848  // At this point, the op iterators are normalized to {leading, k, m, n}.
849  // The layouts induced by packing will always be:
850  // - LHS{leading_lhs, kk, mm}
851  // - RHS{leading_rhs, kk, nn}
852  // - RES{leading_res, mm, nn}
853  // If we wanted to change the packed order, we would reorder (k, m, n) to
854  // something else above.
855  //
856  // Additional permutations of the outer dims of the operands (i.e.
857  // leading_lhs, leading_rhs and leading_res) could follow by computing the
858  // desired outerPerm for each operand.
859  // This is left for future work.
860 
861  // TODO: this creates too much IR, go use reifyResultShapes.
862  SmallVector<Range, 4> loopRanges =
863  cast<LinalgOp>(genericOp.getOperation())
864  .createLoopRanges(rewriter, genericOp.getLoc());
865 
866  // Add leading zeros to match numLoops, we only pack the last 3 dimensions
867  // post interchange.
868  LLVM_DEBUG(llvm::interleaveComma(paddedSizesNextMultipleOf,
869  DBGS() << "paddedSizesNextMultipleOf: ");
870  DBGSNL(););
871  LLVM_DEBUG(llvm::interleaveComma(loopRanges, DBGS() << "loopRanges: ",
872  [](Range r) { llvm::dbgs() << r.size; });
873  DBGSNL(););
874  SmallVector<OpFoldResult> adjustedPackedSizes(numLoops - packedSizes.size(),
875  rewriter.getIndexAttr(0));
876  for (int64_t i = 0, e = numPackedDims; i < e; ++i) {
877  if (paddedSizesNextMultipleOf[i] == 0) {
878  adjustedPackedSizes.push_back(packedSizes[i]);
879  continue;
880  }
881  AffineExpr d0, s0;
882  bindDims(rewriter.getContext(), d0);
883  bindSymbols(rewriter.getContext(), s0);
884  adjustedPackedSizes.push_back(affine::makeComposedFoldedAffineApply(
885  rewriter, genericOp->getLoc(), d0.ceilDiv(s0) * s0,
886  {loopRanges[adjustedPackedSizes.size()].size,
887  rewriter.getIndexAttr(paddedSizesNextMultipleOf[i])}));
888  }
889  LLVM_DEBUG(llvm::interleaveComma(adjustedPackedSizes,
890  DBGS() << "adjustedPackedSizes: ");
891  DBGSNL(););
892 
893  // TODO: If we wanted to give the genericOp a name after packing, after
894  // calling `pack` would be a good time. One would still need to check that
895  // `containsMostMinorMatmul(packingRes->packedLinalgOp)` is true, since we
896  // also allow degenerate matmul cases (i.e. matvec, dot).
897  return pack(rewriter, genericOp, adjustedPackedSizes);
898 }
899 
900 //===----------------------------------------------------------------------===//
901 // Transformations exposed as rewrite patterns.
902 //===----------------------------------------------------------------------===//
903 
906  assert(!tileSizeComputationFunction && "tile sizes already set");
907  SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end());
908  tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) {
909  OpBuilder::InsertionGuard guard(b);
911  &op->getParentOfType<func::FuncOp>().getBody().front());
912  return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) {
913  Value v = b.create<arith::ConstantIndexOp>(op->getLoc(), s);
914  return v;
915  }));
916  };
917  return *this;
918 }
919 
921  memref::CopyOp copyOp, PatternRewriter &rewriter) const {
922  return vectorizeCopy(rewriter, copyOp);
923 }
924 
925 /// Filling `dest` using FillOp constant padding value if possible.
926 /// Otherwise, generate a tensor::GenerateOp.
928  RewriterBase &rewriter, tensor::PadOp padOp, Value dest,
929  const SmallVector<Value> &dynSizes) const {
930  auto padValue = padOp.getConstantPaddingValue();
931  if (padValue)
932  return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result();
933 
934  // Fill could not be optimized: Lower to tensor::GenerateOp with region.
935  auto generateOp = rewriter.create<tensor::GenerateOp>(
936  padOp.getLoc(), padOp.getResultType(), dynSizes);
937  // Copy region to new op.
938  IRMapping bvm;
939  padOp.getRegion().cloneInto(&generateOp.getRegion(), bvm);
940  return generateOp;
941 }
942 
943 LogicalResult
945  PatternRewriter &rewriter) const {
946  // Given an OpFoldResult, return an index-typed value.
947  auto getIdxValue = [&](OpFoldResult ofr) {
948  if (auto val = llvm::dyn_cast_if_present<Value>(ofr))
949  return val;
950  return rewriter
952  padOp.getLoc(), cast<IntegerAttr>(ofr.get<Attribute>()).getInt())
953  .getResult();
954  };
955 
956  auto resultType = padOp.getResultType();
957  // Compute size of EmptyOp. Any combination of static/dynamic is supported.
958  SmallVector<Value> dynSizes;
959  SmallVector<int64_t> staticSizes;
960  for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
961  if (resultType.isDynamicDim(dim)) {
962  auto srcSize = getIdxValue(tensor::getMixedSize(rewriter, padOp.getLoc(),
963  padOp.getSource(), dim));
964  // Add low and high padding value.
965  auto plusLow = rewriter.createOrFold<arith::AddIOp>(
966  padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
967  auto plusHigh = rewriter.createOrFold<arith::AddIOp>(
968  padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
969  dynSizes.push_back(plusHigh);
970  }
971  staticSizes.push_back(resultType.getDimSize(dim));
972  }
973 
974  // Init tensor and fill it with padding.
975  Value emptyTensor = rewriter.create<tensor::EmptyOp>(
976  padOp.getLoc(), staticSizes, resultType.getElementType(), dynSizes);
977  Value fill = createFillOrGenerateOp(rewriter, padOp, emptyTensor, dynSizes);
978 
979  // Try optimize the copy of source.
980  if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded())
981  return success();
982 
983  // tensor::PadOps cannot be optimized. Generate a InsertSliceOp instead
984  // for copying the PadOp source.
985  auto sourceType = padOp.getSourceType();
986  // Compute size of source of tensor::PadOp.
987  SmallVector<OpFoldResult> srcSizes =
988  tensor::getMixedSizes(rewriter, padOp.getLoc(), padOp.getSource());
989  // Strides of InsertSliceOp are all 1.
990  SmallVector<OpFoldResult> strides(sourceType.getRank(),
991  rewriter.getIndexAttr(1));
992  rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
993  padOp, padOp.getSource(), fill, padOp.getMixedLowPad(), srcSizes,
994  strides);
995 
996  return success();
997 }
998 
1000  tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
1001  if (!sliceOp.hasUnitStride())
1002  return failure();
1003 
1004  auto padOp = sliceOp.getSource().getDefiningOp<tensor::PadOp>();
1005  if (!padOp)
1006  return failure();
1007 
1008  bool zeroSliceGuard = true;
1009  if (controlFn) {
1010  if (std::optional<bool> control = controlFn(sliceOp))
1011  zeroSliceGuard = *control;
1012  else
1013  return failure();
1014  }
1015 
1016  FailureOr<TilingResult> tilingResult =
1017  tensor::bubbleUpPadSlice(rewriter, padOp, sliceOp.getMixedOffsets(),
1018  sliceOp.getMixedSizes(), zeroSliceGuard);
1019  if (failed(tilingResult))
1020  return failure();
1021  // All shapes are static and the data source is actually used. Rewrite into
1022  // pad(extract_slice(x)).
1023  rewriter.replaceOp(sliceOp, tilingResult->tiledValues);
1024  return success();
1025 }
1026 
1027 /// Returns a tensor.pad op if padding value is set. Otherwise, returns the
1028 /// source directly. The method assumes that the `packOp` has static shapes.
1030  tensor::PackOp packOp) {
1031  Value input = packOp.getSource();
1032  if (!packOp.getPaddingValue()) {
1033  return input;
1034  }
1035 
1036  Location loc = packOp.getLoc();
1037  ShapedType inputType = packOp.getSourceType();
1038  int64_t inputRank = inputType.getRank();
1039  assert(llvm::all_of(packOp.getDestType().getShape().take_front(inputRank),
1040  [](int64_t val) { return val == 1; }));
1041 
1042  SmallVector<int64_t> paddedShape;
1043  DenseMap<int64_t, OpFoldResult> tileAndPosMapping =
1044  packOp.getDimAndTileMapping();
1045  for (int64_t dim = 0; dim < inputRank; ++dim) {
1046  int64_t size = inputType.getDimSize(dim);
1047  if (!tileAndPosMapping.count(dim)) {
1048  paddedShape.push_back(size);
1049  continue;
1050  }
1051 
1052  // The size is less than or equal to tileSize because outer dims are all 1s.
1053  std::optional<int64_t> tileSize =
1054  getConstantIntValue(tileAndPosMapping.lookup(dim));
1055  assert(tileSize.has_value() && "dynamic inner tile size is not supported");
1056  paddedShape.push_back(tileSize.value());
1057  }
1058  auto resultType =
1059  RankedTensorType::get(paddedShape, inputType.getElementType());
1060  return tensor::createPadHighOp(resultType, input, packOp.getPaddingValue(),
1061  /*nofold=*/false, loc, builder);
1062 }
1063 
1064 // Normalizes a permutation on a higher rank space to its actual size, e.g.
1065 // perm = [1, 4, 2]
1066 // becomes
1067 // norm = [0, 2, 1]
1068 static SmallVector<int64_t>
1070  constexpr int64_t kNonTiledMarker = -1;
1071  SmallVector<int64_t> vec(rank, kNonTiledMarker);
1072  for (auto [index, value] : llvm::enumerate(perm))
1073  vec[value] = index;
1074  SmallVector<int64_t> normalizedPerm = llvm::to_vector(llvm::make_filter_range(
1075  vec, [&](int64_t v) { return v != kNonTiledMarker; }));
1076  // This inverts the permutation in addition to normalizing so invert back.
1077  return invertPermutationVector(normalizedPerm);
1078 }
1079 
1080 // Gets the normalized permutation implied by innerDimsPos and outerDimsPerm
1081 // assuming rank reduction of unit outer dims.
1082 static SmallVector<int64_t>
1084  ArrayRef<int64_t> innerDimsPos,
1085  ArrayRef<int64_t> outerDimsPerm) {
1086  SmallVector<int64_t> rankReducedOuterDimsPerm;
1087  SmallVector<int64_t> outerDims;
1088  SmallVector<int64_t> innerDims;
1089  int64_t dim = 0;
1090  int64_t unpackedRank = shape.size();
1091  for (auto i : llvm::seq<unsigned>(0, unpackedRank)) {
1092  if (llvm::is_contained(innerDimsPos, i)) {
1093  innerDims.push_back(dim++);
1094  continue;
1095  }
1096  if (shape[i] == 1)
1097  continue;
1098  outerDims.push_back(dim++);
1099  if (!outerDimsPerm.empty())
1100  rankReducedOuterDimsPerm.push_back(outerDimsPerm[i]);
1101  }
1102 
1103  // Get the position of the inner dims after permutation.
1104  SmallVector<int64_t> innerPerm =
1105  getPackUnpackNormalizedPerm(unpackedRank, innerDimsPos);
1106  applyPermutationToVector<int64_t>(innerDims, innerPerm);
1107 
1108  // Ditto for the outer dims.
1109  SmallVector<int64_t> perm = outerDims;
1110 
1111  rankReducedOuterDimsPerm =
1112  getPackUnpackNormalizedPerm(unpackedRank, rankReducedOuterDimsPerm);
1113  if (!rankReducedOuterDimsPerm.empty())
1114  applyPermutationToVector<int64_t>(perm, rankReducedOuterDimsPerm);
1115 
1116  // The tile always ends up as the inner most dims after packing.
1117  perm.append(innerDims);
1118 
1119  return perm;
1120 }
1121 
1123  tensor::PackOp packOp, PatternRewriter &rewriter) const {
1124  if (llvm::any_of(packOp.getMixedTiles(),
1125  [](OpFoldResult tile) { return tile.is<Value>(); })) {
1126  return rewriter.notifyMatchFailure(packOp,
1127  "require inner tile sizes being static");
1128  }
1129 
1130  // TODO: support the case that outer dimensions are not all 1s. A
1131  // tensor.expand_shape will be generated in this case.
1132  auto innerDimsPos = packOp.getInnerDimsPos();
1133  int64_t srcRank = packOp.getSourceRank();
1134  auto destShape = packOp.getDestType().getShape();
1135  if (llvm::any_of(innerDimsPos, [destShape](int64_t index) {
1136  return destShape[index] != 1;
1137  })) {
1138  return rewriter.notifyMatchFailure(
1139  packOp, "require the tiled outer dimensions of the result are all 1s");
1140  }
1141 
1142  // 1. Use rank-reduced tensor.extract_slice op to extract the tile and untiled
1143  // outer dims.
1144  Location loc = packOp.getLoc();
1145  Value input = getPackOpSourceOrPaddedSource(rewriter, packOp);
1146  auto inputShape = packOp.getSourceType().getShape();
1147  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1148  packOp.getDimAndTileMapping();
1149  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1150  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1151  SmallVector<OpFoldResult> readOffsets(srcRank, zeroIdxAttr);
1152  SmallVector<OpFoldResult> readStrides(srcRank, oneIdxAttr);
1153  SmallVector<OpFoldResult> readSizes;
1154  SmallVector<int64_t> readShape;
1155  for (auto i : llvm::seq<unsigned>(0, srcRank)) {
1156  if (dimAndTileMapping.count(i)) {
1157  readShape.push_back(getConstantIntValue(dimAndTileMapping[i])
1158  .value_or(ShapedType::kDynamic));
1159  readSizes.push_back(dimAndTileMapping[i]);
1160  continue;
1161  }
1162  if (ShapedType::isDynamic(inputShape[i])) {
1163  readSizes.push_back(
1164  rewriter.create<tensor::DimOp>(loc, input, i).getResult());
1165  } else {
1166  readSizes.push_back(rewriter.getIndexAttr(inputShape[i]));
1167  }
1168  if (inputShape[i] != 1)
1169  readShape.push_back(inputShape[i]);
1170  }
1171 
1172  Type elemType = packOp.getSourceType().getElementType();
1173  auto readType = RankedTensorType::get(readShape, elemType);
1174 
1175  Value tile = rewriter.create<tensor::ExtractSliceOp>(
1176  loc, readType, input, readOffsets, readSizes, readStrides);
1177 
1178  // 2. Transpose the tile to match the inner tile order.
1179 
1181  inputShape, innerDimsPos, packOp.getOuterDimsPerm());
1182 
1183  LLVM_DEBUG(DBGS() << "Pack permutation: " << packOp << "\n";
1184  llvm::interleaveComma(perm, DBGS() << "perm: "); DBGSNL(););
1185 
1186  SmallVector<int64_t> transpShape = readShape;
1187  applyPermutationToVector<int64_t>(transpShape, perm);
1188 
1189  Value empty = rewriter.create<tensor::EmptyOp>(loc, transpShape, elemType);
1190  auto transposedOp =
1191  rewriter.create<linalg::TransposeOp>(loc, tile, empty, perm);
1192 
1193  // 3. Insert the inner tile to the destination.
1194  int64_t destRank = packOp.getDestRank();
1195  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1196  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1197  SmallVector<OpFoldResult> writeSizes =
1198  tensor::getMixedSizes(rewriter, loc, packOp.getDest());
1199 
1200  auto insert = rewriter.create<tensor::InsertSliceOp>(
1201  loc, transposedOp.getResult()[0], packOp.getDest(), writeOffsets,
1202  writeSizes, writeStrides);
1203  rewriter.replaceOp(packOp, insert.getResult());
1204 
1205  return success();
1206 }
1207 
1209  tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const {
1210  int64_t srcRank = unpackOp.getSourceRank();
1211  int64_t destRank = unpackOp.getDestRank();
1212  ArrayRef<int64_t> srcShape = unpackOp.getSourceType().getShape();
1213  ArrayRef<int64_t> innerDimsPos = unpackOp.getInnerDimsPos();
1214  if (llvm::any_of(innerDimsPos, [srcShape](int64_t index) {
1215  return srcShape[index] != 1;
1216  })) {
1217  return rewriter.notifyMatchFailure(
1218  unpackOp,
1219  "require the tiled outer dimensions of the result are all 1s");
1220  }
1221 
1222  // 1. Use rank-reduced tensor.extract_slice op to extract the tile.
1223  Location loc = unpackOp.getLoc();
1224  Value source = unpackOp.getSource();
1225  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1226  unpackOp.getDimAndTileMapping();
1227  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1228  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1229  SmallVector<OpFoldResult> readOffsets(srcRank, zeroIdxAttr);
1230  SmallVector<OpFoldResult> readStrides(srcRank, oneIdxAttr);
1231  SmallVector<OpFoldResult> readSizes;
1232  SmallVector<int64_t> readShape;
1233  SmallVector<Value> dynamicDims;
1234  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1235  if (dimAndTileMapping.count(i)) {
1236  readSizes.push_back(oneIdxAttr);
1237  continue;
1238  }
1239 
1240  if (ShapedType::isDynamic(srcShape[i])) {
1241  Value dynamicDim =
1242  rewriter.create<tensor::DimOp>(loc, source, i).getResult();
1243  readSizes.push_back(dynamicDim);
1244  dynamicDims.push_back(dynamicDim);
1245  } else {
1246  readSizes.push_back(rewriter.getIndexAttr(srcShape[i]));
1247  }
1248  if (srcShape[i] != 1)
1249  readShape.push_back(srcShape[i]);
1250  }
1251  auto mixedTiles = unpackOp.getMixedTiles();
1252  readSizes.append(mixedTiles.begin(), mixedTiles.end());
1253 
1254  // Explicitly create the type for extract_slice op because the inner tile
1255  // size could be 1. We want to represent the whole inner tile in this case.
1256  auto tileShape = srcShape.drop_front(destRank);
1257  // Append the inner tile shape to the permuted and rank-reduced outer shape.
1258  readShape.append(tileShape.begin(), tileShape.end());
1259  Type elemType = unpackOp.getSourceType().getElementType();
1260  auto readType = RankedTensorType::get(readShape, elemType);
1261  Value innerTile = rewriter.create<tensor::ExtractSliceOp>(
1262  loc, readType, unpackOp.getSource(), readOffsets, readSizes, readStrides);
1263 
1264  // 2. Transpose the tile to match the outer corresponding tile order.
1266  srcShape.take_front(destRank), innerDimsPos, unpackOp.getOuterDimsPerm());
1267  // Unpack is a transition out of packed space so we invert the permutation.
1268  perm = invertPermutationVector(perm);
1269  SmallVector<int64_t> transpShape(readShape);
1270  applyPermutationToVector<int64_t>(transpShape, perm);
1271 
1272  Value empty =
1273  rewriter.create<tensor::EmptyOp>(loc, transpShape, elemType, dynamicDims);
1274  auto transposedOp =
1275  rewriter.create<linalg::TransposeOp>(loc, innerTile, empty, perm);
1276 
1277  // 3. Handle in-complete tiles if needed. It truncates trailing data from the
1278  // transposed tile.
1279  int numLoops = transpShape.size();
1280  SmallVector<OpFoldResult> tileStrides(numLoops, oneIdxAttr);
1281  SmallVector<OpFoldResult> tileOffsets(numLoops, zeroIdxAttr);
1282  SmallVector<OpFoldResult> tileSizes;
1283  ArrayRef<int64_t> destShape = unpackOp.getDestType().getShape();
1284  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1285  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1286  tileSizes.push_back(
1287  tensor::getMixedSize(rewriter, loc, unpackOp.getDest(), i));
1288  }
1289 
1290  auto partialTile = rewriter.create<tensor::ExtractSliceOp>(
1291  loc, transposedOp.getResult()[0], tileOffsets, tileSizes, tileStrides);
1292 
1293  // 4. Insert the result to the destination tensor.
1294  SmallVector<OpFoldResult> writeSizes;
1295  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1296  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1297  for (int i = 0, idx = 0; i < destRank; ++i) {
1298  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1299  writeSizes.push_back(tileSizes[idx++]);
1300  else
1301  writeSizes.push_back(oneIdxAttr);
1302  }
1303  auto insert = rewriter.create<tensor::InsertSliceOp>(
1304  loc, partialTile, unpackOp.getDest(), writeOffsets, writeSizes,
1305  writeStrides);
1306  rewriter.replaceOp(unpackOp, insert.getResult());
1307 
1308  return success();
1309 }
1310 
1311 // The following are patterns for downscaling convolution ops with size-1
1312 // window dimensions.
1313 //
1314 // Note that we'd eventually want to write such transformations in a generic
1315 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
1316 // and then turning back to named ops. But for now it's fine to have a few
1317 // patterns matching special ops to get started.
1318 
1319 template <typename Conv2DOp, typename Conv1DOp>
1321  returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const {
1322  if (convOp.hasPureBufferSemantics())
1323  return failure(); // To be implemented.
1324 
1325  Value input = convOp.getInputs().front();
1326  Value kernel = convOp.getInputs().back();
1327  Value output = convOp.getOutputs().front();
1328 
1329  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1330  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1331  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1332 
1333  auto kernelShape = kernelType.getShape();
1334  auto outputShape = outputType.getShape();
1335 
1336  // Get domain indices based on conv2D layout.
1337  auto [khIndex, kwIndex, ohIndex, owIndex] =
1339  convOp)
1340  .Case([&](linalg::Conv2DNhwcHwcfOp op) {
1341  return std::make_tuple(0, 1, 1, 2);
1342  })
1343  .Case([&](linalg::Conv2DNchwFchwOp op) {
1344  return std::make_tuple(2, 3, 2, 3);
1345  })
1346  .Case([&](linalg::PoolingNhwcSumOp op) {
1347  return std::make_tuple(0, 1, 1, 2);
1348  })
1349  .Case([&](linalg::PoolingNchwSumOp op) {
1350  return std::make_tuple(0, 1, 2, 3);
1351  })
1352  .Case([&](linalg::PoolingNhwcMaxOp op) {
1353  return std::make_tuple(0, 1, 1, 2);
1354  })
1355  .Case([&](linalg::PoolingNhwcMaxUnsignedOp op) {
1356  return std::make_tuple(0, 1, 1, 2);
1357  })
1358  .Case([&](linalg::PoolingNhwcMinOp op) {
1359  return std::make_tuple(0, 1, 1, 2);
1360  })
1361  .Case([&](linalg::PoolingNhwcMinUnsignedOp op) {
1362  return std::make_tuple(0, 1, 1, 2);
1363  })
1364  .Case([&](linalg::PoolingNchwMaxOp op) {
1365  return std::make_tuple(0, 1, 2, 3);
1366  })
1367  .Default([&](Operation *op) {
1368  llvm_unreachable("unexpected conv2d/pool2d operation.");
1369  return std::make_tuple(0, 0, 0, 0);
1370  });
1371 
1372  // Only handle the case where at least one of the window dimensions is
1373  // of size 1. Other cases can rely on tiling to reduce to such cases.
1374  int64_t khSize = kernelShape[khIndex], kwSize = kernelShape[kwIndex];
1375  int64_t ohSize = outputShape[ohIndex], owSize = outputShape[owIndex];
1376  bool removeH = (khSize == 1 && ohSize == 1);
1377  bool removeW = (kwSize == 1 && owSize == 1);
1378  if (!removeH && !removeW)
1379  return failure();
1380 
1381  // Get new shapes and types for all operands by removing the size-1
1382  // dimension.
1383  using RTTBuilder = RankedTensorType::Builder;
1384  RankedTensorType newInputType =
1385  RTTBuilder(inputType).dropDim((removeH ? ohIndex : owIndex));
1386  RankedTensorType newKernelType =
1387  RTTBuilder(kernelType).dropDim((removeH ? khIndex : kwIndex));
1388  RankedTensorType newOutputType =
1389  RTTBuilder(outputType).dropDim((removeH ? ohIndex : owIndex));
1390 
1391  // Rank-reduce operands.
1392  Location loc = convOp.getLoc();
1394  rewriter, loc, input, newInputType);
1396  rewriter, loc, kernel, newKernelType);
1398  rewriter, loc, output, newOutputType);
1399 
1400  // Rank-reduce strides and dilations too.
1401  // TODO: dropDim 1-liner helper.
1402  auto strides =
1403  llvm::to_vector<4>(convOp.getStrides().template getValues<int64_t>());
1404  strides.erase(strides.begin() + (removeH ? 0 : 1));
1405  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1406 
1407  auto dilations =
1408  llvm::to_vector<4>(convOp.getDilations().template getValues<int64_t>());
1409  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1410  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1411 
1412  auto conv1DOp = rewriter.create<Conv1DOp>(
1413  loc, newOutputType, ValueRange{newInput, newKernel},
1414  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1415 
1416  // Insert back.
1418  rewriter, loc, conv1DOp.getResult(0), output);
1419  rewriter.replaceOp(convOp, inserted);
1420 
1421  return conv1DOp;
1422 }
1423 
1424 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNhwcHwcfOp,
1425  Conv1DNwcWcfOp>;
1426 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNchwFchwOp,
1427  Conv1DNcwFcwOp>;
1428 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcSumOp,
1429  PoolingNwcSumOp>;
1430 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwSumOp,
1431  PoolingNcwSumOp>;
1432 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxOp,
1433  PoolingNwcMaxOp>;
1435  PoolingNhwcMaxUnsignedOp, PoolingNwcMaxUnsignedOp>;
1436 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinOp,
1437  PoolingNwcMinOp>;
1439  PoolingNhwcMinUnsignedOp, PoolingNwcMinUnsignedOp>;
1440 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwMaxOp,
1441  PoolingNcwMaxOp>;
1442 
1443 FailureOr<DepthwiseConv1DNwcWcOp>
1445  DepthwiseConv2DNhwcHwcOp convOp, PatternRewriter &rewriter) const {
1446  if (convOp.hasPureBufferSemantics())
1447  return failure(); // To be implemented.
1448 
1449  Value input = convOp.getInputs().front();
1450  Value kernel = convOp.getInputs().back();
1451  Value output = convOp.getOutputs().front();
1452 
1453  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1454  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1455  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1456 
1457  auto kernelShape = kernelType.getShape();
1458  auto outputShape = outputType.getShape();
1459 
1460  // Only handle the case where at least one of the window dimensions is
1461  // of size 1. Other cases can rely on tiling to reduce to such cases.
1462  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1463  int64_t ohSize = outputShape[1], owSize = outputShape[2];
1464  bool removeH = (khSize == 1 && ohSize == 1);
1465  bool removeW = (kwSize == 1 && owSize == 1);
1466  if (!removeH && !removeW)
1467  return failure();
1468 
1469  // Get new shapes and types for all operands by removing the size-1
1470  // dimension.
1471  using RTTBuilder = RankedTensorType::Builder;
1472  RankedTensorType newInputType =
1473  RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1474  RankedTensorType newKernelType =
1475  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1476  RankedTensorType newOutputType =
1477  RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1478 
1479  // Rank-reduce operands.
1480  Location loc = convOp.getLoc();
1482  rewriter, loc, input, newInputType);
1484  rewriter, loc, kernel, newKernelType);
1486  rewriter, loc, output, newOutputType);
1487 
1488  // Rank-reduce strides and dilations too.
1489  // TODO: dropDim 1-liner helper.
1490  auto strides = llvm::to_vector<4>(convOp.getStrides().getValues<int64_t>());
1491  strides.erase(strides.begin() + (removeH ? 0 : 1));
1492  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1493 
1494  auto dilations =
1495  llvm::to_vector<4>(convOp.getDilations().getValues<int64_t>());
1496  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1497  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1498 
1499  auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1500  loc, newOutputType, ValueRange{newInput, newKernel},
1501  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1502 
1503  // Insert back.
1505  rewriter, loc, conv1DOp.getResult(0), output);
1506  rewriter.replaceOp(convOp, inserted);
1507 
1508  return conv1DOp;
1509 }
1510 
1511 FailureOr<Conv1DOp>
1513  PatternRewriter &rewriter) const {
1514  if (convOp.hasPureBufferSemantics())
1515  return failure(); // To be implemented.
1516 
1517  Value input = convOp.getInputs().front();
1518  Value kernel = convOp.getInputs().back();
1519  Value output = convOp.getOutputs().front();
1520 
1521  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1522  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1523  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1524 
1525  auto kernelShape = kernelType.getShape();
1526  auto outputShape = outputType.getShape();
1527 
1528  // Only handle the case where at least one of the window dimensions is
1529  // of size 1. Other cases can rely on tiling to reduce to such cases.
1530  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1531  int64_t ohSize = outputShape[0], owSize = outputShape[1];
1532  bool removeH = (khSize == 1 && ohSize == 1);
1533  bool removeW = (kwSize == 1 && owSize == 1);
1534  if (!removeH && !removeW)
1535  return failure();
1536 
1537  // Get new shapes and types for all operands by removing the size-1
1538  // dimension.
1539  using RTTBuilder = RankedTensorType::Builder;
1540  RankedTensorType newInputType =
1541  RTTBuilder(inputType).dropDim((removeH ? 0 : 1));
1542  RankedTensorType newKernelType =
1543  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1544  RankedTensorType newOutputType =
1545  RTTBuilder(outputType).dropDim(removeH ? 0 : 1);
1546 
1547  // Rank-reduce operands.
1548  Location loc = convOp.getLoc();
1550  rewriter, loc, input, newInputType);
1552  rewriter, loc, kernel, newKernelType);
1554  rewriter, loc, output, newOutputType);
1555 
1556  auto conv1DOp = rewriter.create<Conv1DOp>(loc, newOutputType,
1557  ValueRange{newInput, newKernel},
1558  ValueRange{newOutput});
1559 
1560  // Insert back.
1562  rewriter, loc, conv1DOp.getResult(0), output);
1563  rewriter.replaceOp(convOp, inserted);
1564 
1565  return conv1DOp;
1566 }
1567 
1569  PatternBenefit benefit) {
1570  patterns.add<DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNhwcHwcfOp,
1571  Conv1DNwcWcfOp>,
1572  DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNchwFchwOp,
1573  Conv1DNcwFcwOp>,
1575  patterns.getContext(), benefit);
1576  patterns.add<
1580  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxUnsignedOp,
1581  PoolingNwcMaxUnsignedOp>,
1583  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinUnsignedOp,
1584  PoolingNwcMinUnsignedOp>,
1586  patterns.getContext(), benefit);
1587 }
static RankedTensorType permuteShape(RankedTensorType tensorType, ArrayRef< int64_t > permutationVector)
Return a copy of tensorType after permutation by permutationVector.
Definition: Transforms.cpp:620
static SmallVector< int64_t > getPackUnpackRankReducedPerm(ArrayRef< int64_t > shape, ArrayRef< int64_t > innerDimsPos, ArrayRef< int64_t > outerDimsPerm)
static std::optional< int64_t > getFirstResultIndexFunctionOf(AffineMap map, int64_t dim)
Return the index of the first result of map that is a function of AffineDimExpr(dim),...
Definition: Transforms.cpp:102
static FailureOr< SmallVector< std::optional< int64_t > > > packLinalgMetadataOnce(SmallVectorImpl< AffineMap > &indexingMaps, SmallVectorImpl< utils::IteratorType > &iteratorTypes, int64_t dim)
Perform one step of packing of a LinalgOp's metadata along dim into the newDim at iteratorTypes....
Definition: Transforms.cpp:149
static LinalgOp transposeOneLinalgOperandAndReplace(RewriterBase &rewriter, LinalgOp linalgOp, OpOperand &opOperand, ArrayRef< int64_t > permutation, Value transposedValue)
Return a new GenericOp obtained by transposing opOperand by the permutation vector:
Definition: Transforms.cpp:633
static Value getPackOpSourceOrPaddedSource(OpBuilder &builder, tensor::PackOp packOp)
Returns a tensor.pad op if padding value is set.
static bool hasAtMostOneResultFunctionOfDim(AffineMap map, int64_t dim)
Return true if map has 0 or 1 result function of AffineDimExpr(dim).
Definition: Transforms.cpp:87
static SmallVector< int64_t > getPackUnpackNormalizedPerm(int rank, ArrayRef< int64_t > perm)
#define DBGSNL()
Definition: Transforms.cpp:46
#define DBGS()
Definition: Transforms.cpp:45
Base type for affine expression.
Definition: AffineExpr.h:68
bool isFunctionOfDim(unsigned position) const
Return true if the affine expression involves AffineDimExpr position.
Definition: AffineExpr.cpp:315
AffineExpr ceilDiv(uint64_t v) const
Definition: AffineExpr.cpp:950
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
MLIRContext * getContext() const
Definition: AffineMap.cpp:330
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:259
AffineMap insertResult(AffineExpr expr, unsigned pos) const
Returns a new AffineMap with the same number of dims and symbols and an extra result inserted at pos.
Definition: AffineMap.h:307
unsigned getNumDims() const
Definition: AffineMap.cpp:381
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:394
unsigned getNumResults() const
Definition: AffineMap.cpp:389
AffineExpr getResult(unsigned idx) const
Definition: AffineMap.cpp:398
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Definition: AffineMap.cpp:251
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
Definition: AffineMap.cpp:543
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:50
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:124
TypedAttr getZeroAttr(Type type)
Definition: Builders.cpp:331
AffineExpr getAffineDimExpr(unsigned position)
Definition: Builders.cpp:371
MLIRContext * getContext() const
Definition: Builders.h:55
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:144
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:350
This class helps build Operations.
Definition: Builders.h:209
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:433
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:400
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition: Builders.h:522
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:464
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
This class represents an operand of an operation.
Definition: Value.h:267
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
Definition: Value.cpp:216
This is a value defined by a result of an operation.
Definition: Value.h:457
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:402
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition: Operation.h:238
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:682
result_range getResults()
Definition: Operation.h:410
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:785
This is a builder type that keeps local references to arguments.
Definition: BuiltinTypes.h:249
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
Definition: BuiltinTypes.h:276
Builder & setShape(ArrayRef< int64_t > newShape)
Definition: BuiltinTypes.h:260
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
Definition: Region.h:241
MLIRContext * getContext() const
Definition: PatternMatch.h:823
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:847
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
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:718
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
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:536
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
type_range getTypes() const
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:129
Specialization of arith.constant op that returns an integer of index type.
Definition: Arith.h:92
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
Definition: AffineOps.cpp:1192
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:285
FailureOr< GenericOp > generalizeNamedOp(RewriterBase &rewriter, LinalgOp namedOp)
Create a GenericOp from the given named operation namedOp and replace namedOp.
FailureOr< LowerUnPackOpResult > lowerUnPack(RewriterBase &rewriter, tensor::UnPackOp unPackOp)
Rewrite pack as empty + transpose + reshape + extract_slice.
Definition: Transforms.cpp:357
void peelLoops(RewriterBase &rewriter, ArrayRef< scf::ForOp > loops)
Peel 'loops' and applies affine_min/max bounds simplification on the fly where relevant.
Definition: Transforms.cpp:75
void populateDecomposeConvolutionPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Linalg decompose convolutions patterns.
LogicalResult vectorizeCopy(RewriterBase &builder, memref::CopyOp copyOp)
Emit a suitable vector form for a Copy op with fully static shape.
FailureOr< GenericOp > interchangeGenericOp(RewriterBase &rewriter, GenericOp genericOp, ArrayRef< unsigned > interchangeVector)
Interchange the iterator_types and iterator_maps dimensions and adapts the index accesses of op.
Definition: Interchange.cpp:50
FailureOr< ContractionDimensions > inferContractionDims(LinalgOp linalgOp)
Find at least 2 parallel (m and n) and 1 reduction (k) dimension candidates that form a matmul subcom...
FailureOr< PackResult > packMatmulGreedily(RewriterBase &rewriter, LinalgOp linalgOp, ArrayRef< OpFoldResult > mnkPackedSizes, ArrayRef< int64_t > mnkPaddedSizesNextMultipleOf, ArrayRef< int64_t > mnkOrder)
Pack a LinalgOp by greedily inferring matmul dimensions (m, n, k) where m and n are proper parallel d...
Definition: Transforms.cpp:769
FailureOr< PackResult > pack(RewriterBase &rewriter, linalg::LinalgOp linalgOp, ArrayRef< OpFoldResult > packedSizes)
Implement packing of a single LinalgOp by packedSizes.
Definition: Transforms.cpp:480
FailureOr< LowerPackResult > lowerPack(RewriterBase &rewriter, tensor::PackOp packOp)
Rewrite pack as pad + reshape + transpose.
Definition: Transforms.cpp:219
SmallVector< Value > peelLoop(RewriterBase &rewriter, Operation *op)
Try to peel and canonicalize loop op and return the new result.
Definition: Transforms.cpp:59
FailureOr< PackTransposeResult > packTranspose(RewriterBase &rewriter, tensor::PackOp packOp, linalg::LinalgOp linalgOp, tensor::UnPackOp maybeUnPackOp, ArrayRef< int64_t > outerPerm, ArrayRef< int64_t > innerPerm)
Transpose a single PackOp -> LinalgOp -> UnPackOp chain and return the transposed PackOp -> LinalgOp ...
Definition: Transforms.cpp:678
LogicalResult peelForLoopAndSimplifyBounds(RewriterBase &rewriter, ForOp forOp, scf::ForOp &partialIteration)
Rewrite a for loop with bounds/step that potentially do not divide evenly into a for loop where the s...
FailureOr< TilingResult > bubbleUpPadSlice(OpBuilder &b, tensor::PadOp padOp, ArrayRef< OpFoldResult > offsets, ArrayRef< OpFoldResult > sizes, bool generateZeroSliceGuard=true)
Bubbles up a slice of this pad by taking the slice first and then performing the padding.
SmallVector< int64_t > getUnPackInverseSrcPerm(tensor::UnPackOp unpackOp)
Shell function to compute the Source Permutation of unPackOp.
Value createCanonicalRankReducingInsertSliceOp(OpBuilder &b, Location loc, Value tensor, Value dest)
Create a rank-reducing InsertSliceOp @[0 .
Definition: TensorOps.cpp:2855
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
Definition: TensorOps.cpp:2475
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition: TensorOps.cpp:55
SmallVector< int64_t > getPackInverseDestPerm(tensor::PackOp packOp)
Shell function to compute the Destination Permutation of PackOp This function uses the helper functio...
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition: TensorOps.cpp:65
PadOp createPadHighOp(RankedTensorType type, Value source, Value pad, bool nofold, Location loc, OpBuilder &builder)
Definition: Utils.cpp:24
Include the generated interface declarations.
SliceVerificationResult
Enum that captures information related to verifier error conditions on slice insert/extract type of o...
Definition: BuiltinTypes.h:375
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition: AffineExpr.h:348
SmallVector< int64_t > computePermutationVector(int64_t permSize, ArrayRef< int64_t > positions, ArrayRef< int64_t > desiredPositions)
Return a permutation vector of size permSize that would result in moving positions into desiredPositi...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition: AffineExpr.h:362
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
Definition: Utils.cpp:1183
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
void applyPermutationToVector(SmallVector< T, N > &inVec, ArrayRef< int64_t > permutation)
Apply the permutation defined by permutation to inVec.
SliceVerificationResult isRankReducedType(ShapedType originalType, ShapedType candidateReducedType)
Check if originalType can be rank reduced to candidateReducedType type by dropping some dimensions wi...
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
LogicalResult matchAndRewrite(memref::CopyOp copyOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:920
FailureOr< Conv1DOp > returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const
Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh) dimensions into 1-D depthwise c...
Definition: Transforms.h:1372
FailureOr< DepthwiseConv1DNwcWcOp > returningMatchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp, PatternRewriter &rewriter) const
Rewrites 2-D convolution ops with size-1 window dimensions into 1-D convolution ops.
Definition: Transforms.h:1352
FailureOr< Conv1DOp > returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const
LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:999
LogicalResult matchAndRewrite(tensor::PackOp packOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::PadOp padOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:944
Value createFillOrGenerateOp(RewriterBase &rewriter, tensor::PadOp padOp, Value dest, const SmallVector< Value > &dynSizes) const
Filling dest using FillOp constant padding value if possible.
Definition: Transforms.cpp:927
LinalgTilingOptions & setTileSizes(const SmallVector< Value, 4 > &ts)
Set the tileSizeComputationFunction to return the values ts.
Definition: Transforms.h:202
Struct to hold the result of a pack call.
Definition: Transforms.h:1141
Struct to hold the result of a packTranspose call.
Definition: Transforms.h:1153