MLIR  19.0.0git
ReshapeOpsUtils.h
Go to the documentation of this file.
1 //===- ReshapeOpsUtils.h - Utilities used by reshape ops --*- C++ -*------===//
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 header file defines utilities and common canonicalization patterns for
10 // reshape operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MLIR_DIALECT_UTILS_RESHAPEOPSUTILS_H
15 #define MLIR_DIALECT_UTILS_RESHAPEOPSUTILS_H
16 
19 #include "mlir/IR/PatternMatch.h"
20 #include "mlir/Support/LLVM.h"
21 #include "llvm/ADT/StringRef.h"
22 #include <optional>
23 
24 namespace mlir {
25 
29 
30 /// Attribute name for the ArrayAttr which encodes reassociation indices.
31 constexpr StringRef getReassociationAttrName() { return "reassociation"; }
32 
33 /// Compose reassociation maps that are used in pair of reshape ops where one
34 /// is a producer and other is the consumer. Only valid to use this method when
35 /// both the producer and consumer are collapsing dimensions or both are
36 /// expanding dimensions.
37 ///
38 /// For example,
39 /// producerReassociation = [[0, 1], [2], [3, 4]]
40 /// consumerReassociation = [[0, 1], [2]]
41 ///
42 /// is folded into
43 ///
44 /// result = [[0, 1, 2], [3, 4]].
45 std::optional<SmallVector<ReassociationIndices>> composeReassociationIndices(
46  ArrayRef<ReassociationIndices> producerReassociations,
47  ArrayRef<ReassociationIndices> consumerReassociations,
48  MLIRContext *context);
49 
50 /// Convert reassociation indices to affine expressions.
51 SmallVector<SmallVector<AffineExpr, 2>, 2> convertReassociationIndicesToExprs(
52  MLIRContext *context, ArrayRef<ReassociationIndices> reassociationIndices);
53 
54 /// Constructs affine maps out of Array<Array<AffineExpr>>.
55 SmallVector<AffineMap, 4>
56 getSymbolLessAffineMaps(ArrayRef<ReassociationExprs> reassociation);
57 
58 /// Wraps a list of reassociations in an ArrayAttr.
59 ArrayAttr
61  ArrayRef<ReassociationIndices> reassociation);
62 
63 /// Convert Array<Array<AffineExpr>> to Array<Array<int64_t>>.
64 SmallVector<ReassociationIndices, 2> convertReassociationMapsToIndices(
65  OpBuilder &b, ArrayRef<ReassociationExprs> reassociationExprs);
66 
67 /// Return the reassociations maps to use to reshape given the source type and
68 /// the target type when possible. Return std::nullopt when this computation
69 /// failed.
70 std::optional<SmallVector<ReassociationIndices>>
71 getReassociationIndicesForReshape(ShapedType sourceType, ShapedType targetType);
72 
73 /// Returns the reassociation maps to collapse `sourceShape` to `targetShape` if
74 /// possible.
75 std::optional<SmallVector<ReassociationIndices>>
76 getReassociationIndicesForCollapse(ArrayRef<int64_t> sourceShape,
77  ArrayRef<int64_t> targetShape);
78 
79 /// Return true if the reassociation specification is valid, false otherwise.
80 /// When false, the `invalidIndex` integer pointer is optionally filled with the
81 /// index of the offending reassociation map.
82 bool isReassociationValid(ArrayRef<AffineMap> reassociation,
83  int *invalidIndex = nullptr);
84 
85 template <typename ReshapeOpTy, typename InverseReshapeOpTy>
86 static OpFoldResult foldReshapeOp(ReshapeOpTy reshapeOp,
87  ArrayRef<Attribute> operands) {
88 
89  if (reshapeOp.getSrcType() == reshapeOp.getType())
90  return reshapeOp.getSrc();
91 
92  // Fold producer-consumer reshape ops where the operand type of the
93  // producer is same as the return type of the consumer.
94  auto reshapeSrcOp =
95  reshapeOp.getSrc().template getDefiningOp<InverseReshapeOpTy>();
96  if (reshapeSrcOp && reshapeSrcOp.getSrcType() == reshapeOp.getResultType())
97  return reshapeSrcOp.getSrc();
98 
99  // Reshape of a constant can be replaced with a new constant.
100  if (auto elements = dyn_cast_or_null<DenseElementsAttr>(operands.front()))
101  return elements.reshape(cast<ShapedType>(reshapeOp.getResult().getType()));
102 
103  return nullptr;
104 }
105 
106 /// Common verifier for reshape-like types. Fills `expandedType` and
107 ///`collapsedType` with the proper `src` or `result` type.
108 template <typename Op, typename T>
109 static LogicalResult verifyReshapeLikeTypes(Op op, T expandedType,
110  T collapsedType, bool isExpansion) {
111 
112  unsigned expandedRank = expandedType.getRank();
113  unsigned collapsedRank = collapsedType.getRank();
114  if (expandedRank < collapsedRank)
115  return op.emitOpError("expected the expanded type, ")
116  << expandedType << " to have a higher (or same) rank "
117  << "than the collapsed type, " << collapsedType << '.';
118 
119  if (collapsedRank != op.getReassociation().size())
120  return op.emitOpError("expected collapsed rank (")
121  << collapsedRank << ") to equal the number of reassociation maps ("
122  << op.getReassociation().size() << ").";
123 
124  auto maps = op.getReassociationMaps();
125  for (auto it : llvm::enumerate(maps))
126  if (it.value().getNumDims() != expandedRank)
127  return op.emitOpError("expected reassociation map #")
128  << it.index() << " to have size equal to the expanded rank ("
129  << expandedRank << "), but it is " << it.value().getNumDims()
130  << '.';
131 
132  int invalidIdx = 0;
133  if (!isReassociationValid(maps, &invalidIdx))
134  return op.emitOpError("expected reassociation map #")
135  << invalidIdx << " to be valid and contiguous.";
136 
138  [&](const Twine &msg) { return op->emitOpError(msg); },
139  collapsedType.getShape(), expandedType.getShape(),
140  op.getReassociationIndices(), isExpansion);
141 }
142 
143 /// Verify that shapes of the reshaped types using following rules
144 /// 1) if a dimension in the collapsed type is static, then the corresponding
145 /// dimensions in the expanded shape should be
146 /// a) static
147 /// b) the product should be same as the collaped shape.
148 /// 2) if a dimension in the collaped type is dynamic, one and only one of the
149 /// corresponding dimensions in the expanded type should be dynamic. This
150 /// rule is only needed with reshape operations that are expanding.
151 LogicalResult reshapeLikeShapesAreCompatible(
152  function_ref<LogicalResult(const Twine &)> emitError,
153  ArrayRef<int64_t> collapsedShape, ArrayRef<int64_t> expandedShape,
154  ArrayRef<ReassociationIndices> reassociationMaps, bool isExpandingReshape);
155 
156 /// Returns true iff the type is a MemRefType and has a non-identity layout.
157 bool hasNonIdentityLayout(Type type);
158 
159 /// Pattern to collapse producer/consumer reshape ops that are both collapsing
160 /// dimensions or are both expanding dimensions.
161 template <typename ReshapeOpTy>
162 struct ComposeReassociativeReshapeOps : public OpRewritePattern<ReshapeOpTy> {
164  LogicalResult matchAndRewrite(ReshapeOpTy reshapeOp,
165  PatternRewriter &rewriter) const override {
166  auto srcReshapeOp =
167  reshapeOp.getSrc().template getDefiningOp<ReshapeOpTy>();
168  if (!srcReshapeOp)
169  return failure();
170 
171  ShapedType resultType = reshapeOp.getResultType();
172 
173  if (hasNonIdentityLayout(srcReshapeOp.getSrc().getType()) ||
174  hasNonIdentityLayout(reshapeOp.getSrc().getType()) ||
175  hasNonIdentityLayout(reshapeOp.getResult().getType()))
176  return failure();
177 
178  std::optional<SmallVector<ReassociationIndices>> reassociationIndices =
179  composeReassociationIndices(srcReshapeOp.getReassociationIndices(),
180  reshapeOp.getReassociationIndices(),
181  rewriter.getContext());
182  if (!reassociationIndices)
183  return failure();
184  rewriter.replaceOpWithNewOp<ReshapeOpTy>(
185  reshapeOp, resultType, srcReshapeOp.getSrc(), *reassociationIndices);
186  return success();
187  }
188 };
189 
190 /// Pattern to compose
191 /// `collapse_shape(expand_shape(%src, reassociation_1), reassociation_2)`.
192 /// In that case both `srcType` and `resultType` can be expressed as a function
193 /// of `intermediateType`.
194 /// In order to demonstrate the approach, let's assume that `rank(srcType) >
195 /// `rank(resultType)`, i.e. the resulting operation should be `collapse_shape`.
196 /// In that case, we can iterate over every set of indices in `reassociation_2`
197 /// and try to find ids of sets of indices in `reassociation_1` that cover it
198 /// completely.
199 ///
200 /// Example:
201 ///
202 /// %0 = tensor.expand_shape %arg [[0], [1], [2, 3]]
203 /// : tensor<?x?x?xi64> into tensor<?x?x?x1xi64>
204 /// %1 = tensor.collapse_shape %0 [[0, 1], [2, 3]]
205 /// : tensor<?x?x?x1xi64> into tensor<?x?xi64>
206 ///
207 /// can be canonicalized into
208 ///
209 /// %0 = tensor.collapse_shape %arg [[0, 1], [2]]
210 /// : tensor<?x?x?xi64> into tensor<?x?xi64>
211 ///
212 /// because [0] and [1] from `expand_shape` reassociation cover completely
213 /// `[0, 1]` from `collapse_shape`. If it is impossible to find such union of
214 /// indices, then we fail.
215 //
216 /// When `rank(srcType) < rank(resultType)`, then we just swap `reassociation_1`
217 /// `reassociation_2` and produce `expand_shape`.
218 template <typename CollapseOpTy, typename ExpandOpTy, typename CastOpTy>
219 struct ComposeCollapseOfExpandOp : public OpRewritePattern<CollapseOpTy> {
221  LogicalResult matchAndRewrite(CollapseOpTy collapseOp,
222  PatternRewriter &rewriter) const override {
223  auto expandOp = collapseOp.getSrc().template getDefiningOp<ExpandOpTy>();
224  if (!expandOp)
225  return failure();
226 
227  ShapedType srcType = expandOp.getSrcType();
228  ShapedType resultType = collapseOp.getResultType();
229 
230  if (hasNonIdentityLayout(collapseOp.getSrc().getType()) ||
231  hasNonIdentityLayout(expandOp.getSrc().getType()) ||
232  hasNonIdentityLayout(expandOp.getResult().getType()))
233  return failure();
234 
235  int64_t srcRank = srcType.getRank();
236  int64_t resultRank = resultType.getRank();
237  if (srcType == resultType)
238  return failure();
239 
240  SmallVector<ReassociationIndices, 4> higherRankReassociation,
241  lowerRankReassociation;
242 
243  if (srcRank > resultRank) {
244  higherRankReassociation = expandOp.getReassociationIndices();
245  lowerRankReassociation = collapseOp.getReassociationIndices();
246  } else {
247  higherRankReassociation = collapseOp.getReassociationIndices();
248  lowerRankReassociation = expandOp.getReassociationIndices();
249  }
250 
251  size_t higherRankIndicesID = 0;
252  SmallVector<ReassociationIndices, 4> composedReassociation;
253  for (const auto &lowerRankIndices : lowerRankReassociation) {
254  ReassociationIndices composedIndices;
255  while (higherRankIndicesID < higherRankReassociation.size()) {
256  auto rightmostIndex =
257  higherRankReassociation[higherRankIndicesID].back();
258  if (rightmostIndex > lowerRankIndices.back())
259  return failure();
260  composedIndices.push_back(higherRankIndicesID++);
261  if (rightmostIndex == lowerRankIndices.back())
262  break;
263  }
264  composedReassociation.push_back(composedIndices);
265  }
266  if (srcRank > resultRank) {
267  rewriter.replaceOpWithNewOp<CollapseOpTy>(
268  collapseOp, resultType, expandOp.getSrc(), composedReassociation);
269  } else if (srcRank < resultRank) {
270  rewriter.replaceOpWithNewOp<ExpandOpTy>(
271  collapseOp, resultType, expandOp.getSrc(), composedReassociation);
272  } else {
273  // Collapses/expansions that do not change the rank are not allowed. Use
274  // a cast instead.
275  assert(llvm::equal(srcType.getShape(), resultType.getShape()) &&
276  "expected same shape");
277  rewriter.replaceOpWithNewOp<CastOpTy>(collapseOp, resultType,
278  expandOp.getSrc());
279  }
280  return success();
281  }
282 };
283 
284 template <typename ExpandOpTy, typename CollapseOpTy>
285 struct ComposeExpandOfCollapseOp : public OpRewritePattern<ExpandOpTy> {
287  LogicalResult matchAndRewrite(ExpandOpTy expandOp,
288  PatternRewriter &rewriter) const override {
289  auto collapseOp = expandOp.getSrc().template getDefiningOp<CollapseOpTy>();
290  if (!collapseOp)
291  return failure();
292 
293  ShapedType srcType = collapseOp.getSrcType();
294  ShapedType resultType = expandOp.getResultType();
295 
296  if (hasNonIdentityLayout(expandOp.getSrc().getType()) ||
297  hasNonIdentityLayout(collapseOp.getSrc().getType()) ||
298  hasNonIdentityLayout(collapseOp.getResult().getType()))
299  return failure();
300 
301  int64_t srcRank = srcType.getRank();
302  int64_t resultRank = resultType.getRank();
303  if (srcType == resultType)
304  return failure();
305 
306  auto srcReassociation = collapseOp.getReassociationIndices();
307  auto resultReassociation = expandOp.getReassociationIndices();
308  if (srcRank > resultRank) {
309  auto composedReassociation = findCollapsingReassociation(
310  srcReassociation, resultReassociation, srcType.getShape(),
311  resultType.getShape());
312  if (!composedReassociation)
313  return failure();
314 
315  rewriter.replaceOpWithNewOp<CollapseOpTy>(
316  expandOp, resultType, collapseOp.getSrc(), *composedReassociation);
317  return success();
318  }
319  auto composedReassociation =
320  findCollapsingReassociation(resultReassociation, srcReassociation,
321  resultType.getShape(), srcType.getShape());
322  if (!composedReassociation)
323  return failure();
324 
325  rewriter.replaceOpWithNewOp<ExpandOpTy>(
326  expandOp, resultType, collapseOp.getSrc(), *composedReassociation);
327  return success();
328  }
329 
330 private:
331  // Attempts to find a way to collapse `srcShape` to `resultShape` by
332  // collapsing subshapes defined by the reassociation indices.
333  std::optional<SmallVector<ReassociationIndices>> findCollapsingReassociation(
334  ArrayRef<ReassociationIndices> srcReassociation,
335  ArrayRef<ReassociationIndices> resultReassociation,
336  ArrayRef<int64_t> srcShape, ArrayRef<int64_t> resultShape) const {
337  SmallVector<ReassociationIndices, 4> composedReassociation;
338 
339  if (srcReassociation.empty())
340  return {getReassociationIndicesForCollapse(srcShape, resultShape)};
341 
342  for (auto item : llvm::zip(srcReassociation, resultReassociation)) {
343  auto &srcIndices = std::get<0>(item);
344  auto &resultIndices = std::get<1>(item);
345  auto srcSubShape = srcShape.slice(srcIndices.front(), srcIndices.size());
346  auto resultSubShape =
347  resultShape.slice(resultIndices.front(), resultIndices.size());
348 
349  if (srcSubShape.size() == resultSubShape.size()) {
350  if (srcSubShape == resultSubShape)
351  composedReassociation.push_back(srcIndices);
352  else
353  return std::nullopt;
354  }
355 
356  // Find reassociation to collapse `srcSubShape` into `resultSubShape`.
357  auto subShapeReassociation =
358  getReassociationIndicesForCollapse(srcSubShape, resultSubShape);
359  if (!subShapeReassociation)
360  return std::nullopt;
361 
362  // Remap the subshape indices back to the original srcShape.
363  for (auto &subshape_indices : *subShapeReassociation) {
364  ReassociationIndices shape_indices;
365  for (int64_t index : subshape_indices)
366  shape_indices.push_back(srcIndices.front() + index);
367  composedReassociation.push_back(shape_indices);
368  }
369  }
370  return {std::move(composedReassociation)};
371  }
372 };
373 
374 /// The input parameters `offsets`, `sizes`, `strides` specify a rectangular
375 /// non rank-reducing slice of the collapse_shape output. Try to find which
376 /// dimensions have been sliced and which dimensions are not sliced (offset = 0,
377 /// size = dim, size = 1). Note that this conservative as it cannot detect if a
378 /// dynamic size corresponds to the full tensor dimension or not.
379 llvm::SmallBitVector getSlicedDimensions(ArrayRef<OpFoldResult> sliceInputShape,
380  ArrayRef<Range> sliceParams);
381 
382 /// Determine which dimensions are linearized by a `tensor.collapse_shape` op by
383 /// inspecting its reassociation indices.
384 llvm::SmallBitVector
385 getLinearizedDimensions(ArrayRef<ReassociationIndices> reassociationIndices);
386 
387 /// Given the parameters for both operations in a `CollapseShape->ExtractSlice`
388 /// chain and reified source and result shapes of the CollapseShapeOp, this
389 /// class provides two functions that assist with directly forming the result
390 /// of the extract slice by "tiling the CollapseShapeOp by 1".
391 //// Example:
392 // clang-format off
393 /// ```
394 /// %0 = linalg.generic ... -> tensor<3x7x11x10xf32>
395 /// %1 = tensor.collapse_shape %0 [[0, 1, 2], [3]] : ... to tensor<341x10xf32>
396 /// %2 = tensor.extract_slice %1 [13, 0] [10, 10] [2, 1] : .... tensor<10x10xf32>
397 /// ```
398 /// This class helps build the below IR to replace %2:
399 /// ```
400 /// %dest = tensor.empty() : tensor<10x10xf32>
401 /// %2 = scf.for %iv = %c0 to %c10 step %c1 iter_args(%arg0) -> tensor<10x10xf32> {
402 /// %linear_index = affine.apply affine_map<(d0)[]->(d0*2 + 11)>(%iv)
403 /// %3:3 = arith.delinearize_index %iv into (3, 7, 11)
404 ///
405 /// // This function takes %3 (multiIndices) and the parameters for the slice below.
406 /// %4 = tensor.extract_slice %0 [%3#0, %3#1, %3#2, 0] [1, 1, 1, 10] [1, 1, 1, 1] :
407 /// tensor<3x7x11x10xf32> to tensor<1x1x1x10xf32>
408 ///
409 /// %5 = tensor.collapse_shape %4 [[0, 1, 2], [3]] :
410 /// tensor<1x1x1x10xf32> into tensor<1x10xf32>
411 /// %6 = tensor.insert_slice %5 into %arg0 [%iv, 0] [1, 10] [1, 1] :
412 /// tensor<1x10xf32> into tensor<10x10xf32>
413 /// scf.yield %6 : tensor<10x10xf32>
414 /// }
415 /// ```
416 // clang-format on
417 class SliceFromCollapseHelper {
418 public:
419  SliceFromCollapseHelper(ArrayRef<ReassociationIndices> reassociationIndices,
420  ArrayRef<OpFoldResult> collapseShapeInputShape,
421  ArrayRef<OpFoldResult> collapseShapeOutputShape,
422  ArrayRef<Range> extractSliceParams)
423  : reassociationIndices(reassociationIndices),
424  collapseShapeInputShape(collapseShapeInputShape),
425  collapseShapeOutputShape(collapseShapeOutputShape),
426  sliceParams(extractSliceParams),
427  linearizedDimensions(getLinearizedDimensions(reassociationIndices)),
428  slicedDimensions(getSlicedDimensions(collapseShapeOutputShape,
429  extractSliceParams)) {}
430 
431  /// This function takes multi-indices and maps them to ExtractSlice parameters
432  /// in the index space of the CollapseShape's source tensor. This function's
433  /// signature can be described by `(D_0, D_1,.. D_{n-1}) -> (offsets, sizes,
434  /// strides)` where `n` the number of "tiled dimensions", which are the
435  /// dimensions of the output that are linearized by the collapse shape op and
436  /// are also sliced. Each `D_i` is a tuple that must represent a valid
437  /// multi-index for the `i-th` tiled dimension. In the example above, there is
438  /// only one tiled dimension (D_0) and `arith.delinearize_index` produces the
439  /// multi-index (%3) that would be passed to this function to generate the
440  /// parameters for the `tensor.extract_slice` op (%4).
441  SmallVector<Range> getExtractSliceParams(MLIRContext *ctx,
442  ArrayRef<ValueRange> multiIndices);
443 
444  /// This function takes indices in the index space of the "tiled dimensions"
445  /// described above and returns a set of Range variables that describe how the
446  /// slice should be inserted into the destination. In the example above, `%iv`
447  /// would be passed to this function to generate the parameters for the
448  /// `tensor.insert_slice` op producing %6.
449  SmallVector<Range> getInsertSliceParams(MLIRContext *ctx,
450  ValueRange tileIndices);
451 
452 private:
453  SmallVector<ReassociationIndices> reassociationIndices;
454  SmallVector<OpFoldResult> collapseShapeInputShape;
455  SmallVector<OpFoldResult> collapseShapeOutputShape;
456  SmallVector<Range> sliceParams;
457  llvm::SmallBitVector linearizedDimensions;
458  llvm::SmallBitVector slicedDimensions;
459 };
460 
461 /// Parameters required to simplify a collapsing reshape op with a rank-reducing
462 /// slice operation. See `getSimplifyCollapseShapeWithRankReducingSliceInfo`.
463 struct CollapseShapeRankReducingSliceSimplificationInfo {
464  /// The shape of the output of the rank-reducing slice.
465  RankedTensorType sliceResultType;
466  /// The reassociation indices for the new collapse shape op, if required. If
467  /// `std::nullopt`, the slice should replace the collapse shape op.
468  std::optional<SmallVector<ReassociationIndices>> newReassociationIndices;
469 };
470 
471 /// A collapsing reshape operation can sometimes be simplified or eliminated by
472 /// inserting a single rank-reducing slice operation between it and the source
473 /// tensor. The slice op will either take the place of the source, allowing for
474 /// a new, simpler reshape op to replace the original, or the reshape op will be
475 /// completely replaced by the slice result.
476 ///
477 /// This function returns the parameters required to implement this pattern. If
478 /// the pattern is not applicable, then failure is returned.
479 ///
480 /// ### Example:
481 /// ```
482 /// %result = tensor.collapse_shape %0 [[0, 1], [2, 3]]
483 /// : tensor<?x1x30x10xf32> to tensor<?x300xf32>
484 /// ```
485 /// can be transformed to
486 /// ```
487 /// %tmp = tensor.extract_slice %0 [0, 0, 0, 0]
488 /// [0, %dim1, 30, 30]
489 /// [1, 1, 1 1]
490 /// : tensor<?x1x30x10xf32> to tensor<?x30x10xf32>
491 /// %result = tensor.collapse_shape %tmp [[0], [1, 2]]
492 /// : tensor<?x30x10xf32> to tensor<?x300xf32>
493 /// ```
494 ///
495 /// ### Example:
496 /// ```
497 /// %result = tensor.collapse_shape %1 [[0, 1], [2]]
498 /// : tensor<?x1x30xf32> to tensor<?x30xf32>
499 /// ```
500 /// can be transformed to
501 /// ```
502 /// %result = tensor.extract_slice %1 [0, 0, 0]
503 /// [%dim2, 1, 30]
504 /// [1, 1, 1]
505 /// : tensor<?x1x30xf32> to tensor<?x30xf32>
506 /// ```
507 FailureOr<CollapseShapeRankReducingSliceSimplificationInfo>
508 getSimplifyCollapseShapeWithRankReducingSliceInfo(
509  RankedTensorType sourceType,
510  ArrayRef<ReassociationIndices> reassociationIndices);
511 
512 struct PackingMetadata {
513  SmallVector<int64_t> insertPositions;
514  SmallVector<int64_t> outerPositions;
515  SmallVector<ReassociationIndices> reassociations;
516 };
517 
518 /// Given a vector of `positions` indices representing desired packing insertion
519 /// points into a target vector (i.e. pack/unpack.inner_dim_pos), compute the
520 /// final positions in the target shape as well as the reshape reassociations.
521 // Note: This should not be called with a large positions array (or the
522 // implementation needs to be updated to use an N.log N sort instead of
523 // repeated N^2 counts).
524 PackingMetadata computePackingMetadata(int64_t packedRank,
525  ArrayRef<int64_t> innerDimPos);
526 } // namespace mlir
527 
528 #endif // MLIR_DIALECT_UTILS_RESHAPEOPSUTILS_H
static RankedTensorType sliceResultType(Type operandType, MeshOp mesh, ArrayRef< MeshAxis > meshAxes, int64_t sliceAxis)
Definition: MeshOps.cpp:594
MLIRContext * getContext() const
Definition: Builders.h:55
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
This provides public APIs that all operations should have.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:671
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:785
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
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:285
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
llvm::function_ref< Fn > function_ref
Definition: LLVM.h:147
llvm::SmallBitVector getSlicedDimensions(ArrayRef< OpFoldResult > sliceInputShape, ArrayRef< Range > sliceParams)
The input parameters offsets, sizes, strides specify a rectangular non rank-reducing slice of the col...
constexpr StringRef getReassociationAttrName()
Attribute name for the ArrayAttr which encodes reassociation indices.
bool hasNonIdentityLayout(Type type)
Returns true iff the type is a MemRefType and has a non-identity layout.
static OpFoldResult foldReshapeOp(ReshapeOpTy reshapeOp, ArrayRef< Attribute > operands)
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
SmallVector< AffineMap, 4 > getSymbolLessAffineMaps(ArrayRef< ReassociationExprs > reassociation)
Constructs affine maps out of Array<Array<AffineExpr>>.
static LogicalResult verifyReshapeLikeTypes(Op op, T expandedType, T collapsedType, bool isExpansion)
Common verifier for reshape-like types.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
LogicalResult reshapeLikeShapesAreCompatible(function_ref< LogicalResult(const Twine &)> emitError, ArrayRef< int64_t > collapsedShape, ArrayRef< int64_t > expandedShape, ArrayRef< ReassociationIndices > reassociationMaps, bool isExpandingReshape)
Verify that shapes of the reshaped types using following rules 1) if a dimension in the collapsed typ...
std::optional< SmallVector< ReassociationIndices > > getReassociationIndicesForReshape(ShapedType sourceType, ShapedType targetType)
Return the reassociations maps to use to reshape given the source type and the target type when possi...
std::optional< SmallVector< ReassociationIndices > > getReassociationIndicesForCollapse(ArrayRef< int64_t > sourceShape, ArrayRef< int64_t > targetShape)
Returns the reassociation maps to collapse sourceShape to targetShape if possible.
ArrayRef< int64_t > ReassociationIndicesRef
ArrayAttr getReassociationIndicesAttribute(OpBuilder &b, ArrayRef< ReassociationIndices > reassociation)
Wraps a list of reassociations in an ArrayAttr.
SmallVector< SmallVector< AffineExpr, 2 >, 2 > convertReassociationIndicesToExprs(MLIRContext *context, ArrayRef< ReassociationIndices > reassociationIndices)
Convert reassociation indices to affine expressions.
bool isReassociationValid(ArrayRef< AffineMap > reassociation, int *invalidIndex=nullptr)
Return true if the reassociation specification is valid, false otherwise.
std::optional< SmallVector< ReassociationIndices > > composeReassociationIndices(ArrayRef< ReassociationIndices > producerReassociations, ArrayRef< ReassociationIndices > consumerReassociations, MLIRContext *context)
Compose reassociation maps that are used in pair of reshape ops where one is a producer and other is ...
SmallVector< int64_t, 2 > ReassociationIndices
llvm::SmallBitVector getLinearizedDimensions(ArrayRef< ReassociationIndices > reassociationIndices)
Determine which dimensions are linearized by a tensor.collapse_shape op by inspecting its reassociati...
SmallVector< ReassociationIndices, 2 > convertReassociationMapsToIndices(OpBuilder &b, ArrayRef< ReassociationExprs > reassociationExprs)
Convert Array<Array<AffineExpr>> to Array<Array<int64_t>>.
Pattern to compose collapse_shape(expand_shape(src, reassociation_1), reassociation_2).
LogicalResult matchAndRewrite(CollapseOpTy collapseOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(ExpandOpTy expandOp, PatternRewriter &rewriter) const override
Pattern to collapse producer/consumer reshape ops that are both collapsing dimensions or are both exp...
LogicalResult matchAndRewrite(ReshapeOpTy reshapeOp, PatternRewriter &rewriter) const override
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:358