MLIR 22.0.0git
Utils.h
Go to the documentation of this file.
1//===- Utils.h - Utilities to support the Linalg dialect --------*- 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#ifndef MLIR_DIALECT_LINALG_UTILS_UTILS_H
10#define MLIR_DIALECT_LINALG_UTILS_UTILS_H
11
15#include "llvm/ADT/StringSet.h"
16#include <optional>
17
18namespace mlir {
19class AffineExpr;
20class AffineMap;
21class PatternRewriter;
22
23namespace affine {
24class AffineForOp;
25} // namespace affine
26
27namespace tensor {
28class ExtractSliceOp;
29} // namespace tensor
30
31namespace linalg {
32
33//===----------------------------------------------------------------------===//
34// Utilities for inferring various semantics properties of Linalg ops.
35//===----------------------------------------------------------------------===//
36
37/// Compute inverse permutation for the destination tensor (i.e. in the packed
38/// domain).
40 PackingMetadata &metadata);
41
42/// Compute inverse permutation for the source tensor (i.e. in the packed
43/// domain).
45 PackingMetadata &metadata);
46
47//===----------------------------------------------------------------------===//
48// General utilities
49//===----------------------------------------------------------------------===//
50
51/// Check if all indexing maps are projected permutations.
53
54/// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
56
57/// Check if a LinalgOp is an element-wise operation.
58bool isElementwise(LinalgOp op);
59
60/// Check if iterator type has "parallel" semantics.
61bool isParallelIterator(utils::IteratorType iteratorType);
62
63/// Check if iterator type has "reduction" semantics.
64bool isReductionIterator(utils::IteratorType iteratorType);
65
66/// Create a tensor::PadOp that pads `source` to the shape of `type` whose sizes
67/// are assumed to be greater than the dynamic `source` size. If `typeDynDims`
68/// is specified, then it must contain the sizes of all the dynamic dimensions
69/// in order of appearance in `type`, otherwise the function will pad those
70/// values to `0`. The padding introduces trailing `pad` values until the target
71/// size is met. If `source` is defined by one or more LinalgOps that have been
72/// padded with the same value and sizes, return their padded result instead of
73/// creating a tensor::PadOp.
74///
75/// Example:
76/// ```
77/// %0 = tensor.extract_slice %arg0 [%iv0, %iv1] [%sz0, %sz1]
78/// %1 = tensor.pad %0 low[0, 0] high[...] { tensor.yield %cst }
79/// %2 = linalg.matmul ins(...) outs(%1)
80/// %3 = tensor.extract_slice %2 [0, 0] [%sz0, %sz1]
81/// ```
82/// makeComposedPadHighOp(source=%3, pad=%cst) returns %2
83/// makeComposedPadHighOp(source=%3, pad=%other_cst) returns %4
84/// ```
85/// %4 = tensor.pad %3 low[0, 0] high[...] { tensor.yield %other_cst }
86/// ```
87Value makeComposedPadHighOp(OpBuilder &b, Location loc, RankedTensorType type,
88 Value source, Value padding, bool nofold,
89 ValueRange typeDynDims = {});
90
91/// Returns GenericOp that copies an n-D memref. Unlike the current
92/// implementation of memref::CopyOp, this op can further tile, lower to loops
93/// or vectorize.
94GenericOp makeMemRefCopyOp(OpBuilder &b, Location loc, Value from, Value to);
95
96/// Get the reassociation maps to fold the result of a extract_slice (or
97/// source of a insert_slice) operation with given offsets, and sizes to its
98/// rank-reduced version. This is only done for the cases where the size is 1
99/// and offset is 0. Strictly speaking the offset 0 is not required in
100/// general, but non-zero offsets are not handled by SPIR-V backend at this
101/// point (and potentially cannot be handled).
102std::optional<SmallVector<ReassociationIndices>>
104
105//===----------------------------------------------------------------------===//
106// Convolution matcher utility
107//===----------------------------------------------------------------------===//
108
109/// Given a linalg `op` this function returns true if it is a convolution op of
110/// type `ConvOpTy` and populates `dilations` and `strides` with values inferred
111/// from the indexing maps.
112template <typename ConvOpTy>
113bool isaConvolutionOpOfType(LinalgOp op, SmallVector<int64_t> *dilations,
114 SmallVector<int64_t> *strides);
115
116//===----------------------------------------------------------------------===//
117// Fusion / Tiling utilities
118//===----------------------------------------------------------------------===//
119
120/// The type of loops to be generated during tiling.
126
127/// Computes tile offsets, given a list of loop `ivs` and `tileSizes`. In case
128/// a tile size is zero (i.e., no tiling), the corresponding offset is also
129/// zero.
132 ArrayRef<OpFoldResult> tileSizes);
133
134/// Computes tile sizes, given a list of `tileSizes` and dimension
135/// sizes (`sizeBounds`). In case a tile size is zero (i.e., no tiling), the
136/// corresponding result size is the corresponding value from `sizeBounds`.
137/// Note: The returned tile sizes are closed intervals.
139 ArrayRef<OpFoldResult> tileSizes,
140 ArrayRef<OpFoldResult> sizeBounds);
141
142/// Returns the list of tensor output types produced when the given structured
143/// operation `op` is applied to the given `operands`. Note that `operands`
144/// are not necessarily the actual operands of `op`.
146
147/// Creates `insert_slice` ops that insert `results` back into larger tensors
148/// they were originally extracted from with `extract_slice` before being
149/// passed as `operands` to the given structured operation `op` or its clone.
150/// Note that `operands` are not necessarily the actual operands of `op`, the
151/// operation serves only as metadata container for operand types and
152/// positions.
154 LinalgOp op, ValueRange operands,
155 ValueRange results);
156
157/// A struct containg offsets-sizes-strides arguments of the tiled shape.
163
164/// Computes SliceParameters for a single `valueToTile` assuming that its user
165/// is being tiled with the given loop bounds `lbs` and `ubs` and the tile
166/// sizes `tileSizes`.
167///
168/// `omitPartialTileCheck` controls whether to omit the partial/boundary tile
169/// condition check in cases where we statically know that it is unnecessary.
171computeSliceParameters(OpBuilder &builder, Location loc, Value valueToTile,
172 ArrayRef<OpFoldResult> tileSizes, AffineMap map,
174 ArrayRef<OpFoldResult> subShapeSizes,
175 bool omitPartialTileCheck);
176
177/// Computes SliceParamaters for all `valuesToTile` of the given `linalgOp`,
178/// assuming `linalgOp` is being fused into a loop nest. Calls
179/// `computeSliceParameters` for every individual value.
180///
181/// Note that a constant zero in `tileSizes` means no tiling at that implicit
182/// loop. The number of non-zero values in `tileSizes` should be equal to the
183/// number of values in `ivs`.
184///
185/// Some of the `valuesToTile` won't be affected by tiling. For these values,
186/// std::nullopt will be returned.
188computeAllSliceParameters(OpBuilder &builder, Location loc, LinalgOp linalgOp,
189 ValueRange valuesToTile, ArrayRef<OpFoldResult> ivs,
190 ArrayRef<OpFoldResult> tileSizes,
191 ArrayRef<OpFoldResult> sizeBounds,
192 bool omitPartialTileCheck);
193
194/// Creates an extract_slice/subview op for a single `valueToTile` with
195/// `builder`. This new operation extracts a tile of `valueToTile`, starting
196/// at offsets `lbs` and with sizes `subShapeSizes`. `omitPartialTileCheck`
197/// controls whether to omit the partial/boundary tile condition check in
198/// cases where we statically know that it is unnecessary.
199Operation *makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile,
200 ArrayRef<OpFoldResult> tileSizes, AffineMap map,
203 ArrayRef<OpFoldResult> subShapeSizes,
204 bool omitPartialTileCheck);
205
206/// Creates extract_slice/subview ops for all `valuesToTile` of the given
207/// `linalgOp` with `builder`, assuming `linalgOp` is being fused into a loop
208/// nest for tiling with the given induction variables `ivs` and tile sizes
209/// `tileSizes`. `sizeBounds` are the iteration space bounds for *all* the
210/// implicit loops in `linalgOp`. `omitPartialTileCheck` controls whether to
211/// omit the partial/boundary tile condition check in cases where we
212/// statically know that it is unnecessary.
213///
214/// Note that a constant zero in `tileSizes` means no tiling at that implicit
215/// loop. The number of non-zero values in `tileSizes` should be equal to the
216/// number of values in `ivs`.
218 LinalgOp linalgOp, ValueRange valuesToTile,
220 ArrayRef<OpFoldResult> tileSizes,
221 ArrayRef<OpFoldResult> sizeBounds,
222 bool omitPartialTileCheck);
223
224/// Add the specified offsets to any `linalg.index` ops contained in the given
225/// `linalgOp`. The offsets are provided in the same order as iteration space
226/// dimensions. Null offests are assumed to be zero.
227void offsetIndices(OpBuilder &b, LinalgOp linalgOp,
228 ArrayRef<OpFoldResult> offests);
229void offsetIndices(RewriterBase &b, LinalgOp linalgOp,
230 ArrayRef<OpFoldResult> offests);
231
232/// A struct containing the Linalg producer before and after fusion.
233/// When operating on tensors, `fusedProducer` may feed into a `tensor.cast`
234/// op before the consumer Linalg op, until enough canonicalizations have
235/// applied.
239};
240
241/// This implements the fusion part of the "tileAndFuse on tensors"
242/// transformation and thus requires the `consumerOpOperand` to be a
243/// `extract_slice` op (generally obtained by applying the tiling
244/// transformation).
245FailureOr<FusionInfo> fuseProducerOfTensor(OpBuilder &b,
246 OpOperand &consumerOpOperand);
247
248/// This implements the fusion part of the "tileAndFuse on tensors"
249/// transformation and thus requires the `consumerOpOperand` to be a
250/// `extract_slice` op (generally obtained by applying the tiling
251/// transformation). Assumes `producerOfTensor` is a Linalg op that produces
252/// `consumerOpOperand`.
253FailureOr<FusionInfo> fuseProducerOfTensor(OpBuilder &b,
254 OpResult producerOpResult,
255 OpOperand &consumerOpOperand);
256
257//===----------------------------------------------------------------------===//
258// Distribution utilities
259//===----------------------------------------------------------------------===//
260
261/// Scheme used to distribute loops to processors.
263 /// Cyclic distribution where no assumption is made about the dynamic
264 /// relationship between number of processors and number of iterations of
265 /// the
266 /// distributed loop. Distributes the following loop
267 ///
268 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
269 ///
270 /// to
271 ///
272 /// scf.parallel(%iv)= (%lb + %procId * %step) to (%ub) step (%step *
273 /// %nprocs)
275
276 /// Cyclic distribution where the number of processors can be assumed to be
277 /// more than or equal to the number of iterations of the distributed loop.
278 /// In
279 /// such cases, a simple in-bounds check is enough (instead of materializing
280 /// a
281 /// loop). Distributes the following loop
282 ///
283 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
284 ///
285 /// to
286 ///
287 /// %iv = %lb + %procId * %step
288 /// %cond = arith.cmpi "slt", %iv, %ub
289 /// scf.if %cond {
290 /// ...
291 /// }
293
294 /// Cyclic distribution where the number of processors can be assumed to be
295 /// equal to the number of iterations of the distributed loop. In such
296 /// cases,
297 /// no bounds check is needed. Distributes the following loop
298 ///
299 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
300 ///
301 /// to
302 ///
303 /// %iv = %lb + %procId * %step
305
306 /// No Distribution.
308};
309
310/// Callback function type used to get processor ID, and number of processors
311/// used for distribution for all parallel loops generated.
317using ProcInfoCallBackFn = std::function<SmallVector<ProcInfo>(
318 OpBuilder &b, Location loc, ArrayRef<Range> parallelLoopRanges)>;
319
320/// Options that allow distribution of loops generated in Linalg transforms to
321/// processors while generating the loops.
323 /// Callback function that returns the Values for processor ID (`procId`),
324 /// and number of processors (`nprocs`) used to execute the parallel loops.
325 /// The number of `{procId, nprocs}` pairs returned must be equal to the
326 /// number of `parallelLoopRanges` passed into the callback. The
327 /// `parallelLoopRanges` are ranges of the outer parallel loops of the
328 /// operation that do have non-zero tile sizes specified.
330};
331
332/// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and
333/// `step`.
335 Value procId, Value nprocs, Value &lb,
336 Value &ub, Value &step);
337
338//===----------------------------------------------------------------------===//
339// Fusion on tensor utilities
340//===----------------------------------------------------------------------===//
341
342//===----------------------------------------------------------------------===//
343// Generic op region utilities
344//===----------------------------------------------------------------------===//
345
346/// A struct containing common matchers over linalg op's region.
348 enum class BinaryOpKind {
350 };
351
352 /// Matches the given linalg op if its body is performing binary operation
353 /// on int or float scalar values and returns the binary op kind.
354 ///
355 /// The linalg op's region is expected to be
356 /// ```
357 /// {
358 /// ^bb(%a: <scalar-type>, %b: <scalar-type>):
359 /// %0 = <binary-op> %a, %b: <scalar-type>
360 /// linalg.yield %0: <scalar-type>
361 /// }
362 /// ```
363 static std::optional<BinaryOpKind> matchAsScalarBinaryOp(GenericOp op);
364};
365
366//===----------------------------------------------------------------------===//
367// Loop nest utilities
368//===----------------------------------------------------------------------===//
369
370/// Utility class used to generate nested loops with ranges described by
371/// `loopRanges` and loop type described by the `iteratorTypes`.
372/// `bodyBuilderFn` is used to generate the body of the innermost loop. It is
373/// passed a range of loop induction variables and a range of operand values
374/// to use.
375template <typename LoopTy>
377 static void doit(OpBuilder &b, Location loc, ArrayRef<Range> loopRanges,
378 LinalgOp linalgOp,
379 ArrayRef<utils::IteratorType> iteratorTypes,
382 bodyBuilderFn,
383 ArrayRef<linalg::ProcInfo> procInfo = {});
384};
385
386/// Returns an attribute list that excludes pre-defined attributes.
387template <typename OpTy>
389 auto elidedAttrs = llvm::to_vector(op.getAttributeNames());
390 if (isa<linalg::LinalgOp>(op.getOperation()))
391 elidedAttrs.push_back(LinalgDialect::kMemoizedIndexingMapsAttrName);
392 return getPrunedAttributeList(op, elidedAttrs);
393}
394
395} // namespace linalg
396} // namespace mlir
397
398#endif // MLIR_DIALECT_LINALG_UTILS_UTILS_H
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:207
This class represents an operand of an operation.
Definition Value.h:257
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
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
FailureOr< FusionInfo > fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand)
This implements the fusion part of the "tileAndFuse on tensors" transformation and thus requires the ...
Definition Fusion.cpp:217
SmallVector< int64_t > getUnPackInverseSrcPerm(linalg::UnPackOp, PackingMetadata &metadata)
Compute inverse permutation for the source tensor (i.e.
SmallVector< Value > makeTiledShapes(OpBuilder &builder, Location loc, LinalgOp linalgOp, ValueRange valuesToTile, ArrayRef< OpFoldResult > ivs, ArrayRef< OpFoldResult > tileSizes, ArrayRef< OpFoldResult > sizeBounds, bool omitPartialTileCheck)
Creates extract_slice/subview ops for all valuesToTile of the given linalgOp with builder,...
Definition Utils.cpp:1732
bool allIndexingsAreProjectedPermutation(LinalgOp op)
Check if all indexing maps are projected permutations.
Definition Utils.cpp:195
bool isParallelIterator(utils::IteratorType iteratorType)
Check if iterator type has "parallel" semantics.
Definition Utils.cpp:230
SmallVector< OpFoldResult > computeTileSizes(OpBuilder &b, Location loc, ArrayRef< OpFoldResult > tileSizes, ArrayRef< OpFoldResult > sizeBounds)
Computes tile sizes, given a list of tileSizes and dimension sizes (sizeBounds).
Definition Utils.cpp:1627
GenericOp makeMemRefCopyOp(OpBuilder &b, Location loc, Value from, Value to)
Returns GenericOp that copies an n-D memref.
Definition Utils.cpp:1183
SmallVector< OpFoldResult > computeTileOffsets(OpBuilder &b, Location loc, ArrayRef< OpFoldResult > ivs, ArrayRef< OpFoldResult > tileSizes)
Computes tile offsets, given a list of loop ivs and tileSizes.
Definition Utils.cpp:1613
LinalgTilingLoopType
The type of loops to be generated during tiling.
Definition Utils.h:121
bool isReductionIterator(utils::IteratorType iteratorType)
Check if iterator type has "reduction" semantics.
Definition Utils.cpp:234
bool hasOnlyScalarElementwiseOp(Region &r)
Detect whether r has only ConstantOp, ElementwiseMappable and YieldOp.
Definition Utils.cpp:201
std::optional< SmallVector< ReassociationIndices > > getReassociationMapForFoldingUnitDims(ArrayRef< OpFoldResult > mixedSizes)
Get the reassociation maps to fold the result of a extract_slice (or source of a insert_slice) operat...
Definition Utils.cpp:1790
DistributionMethod
Scheme used to distribute loops to processors.
Definition Utils.h:262
@ None
No Distribution.
Definition Utils.h:307
@ CyclicNumProcsGeNumIters
Cyclic distribution where the number of processors can be assumed to be more than or equal to the num...
Definition Utils.h:292
@ Cyclic
Cyclic distribution where no assumption is made about the dynamic relationship between number of proc...
Definition Utils.h:274
@ CyclicNumProcsEqNumIters
Cyclic distribution where the number of processors can be assumed to be equal to the number of iterat...
Definition Utils.h:304
SmallVector< Value > insertSlicesBack(OpBuilder &builder, Location loc, LinalgOp op, ValueRange operands, ValueRange results)
Creates insert_slice ops that insert results back into larger tensors they were originally extracted ...
Definition Utils.cpp:1652
bool isElementwise(LinalgOp op)
Check if a LinalgOp is an element-wise operation.
Definition Utils.cpp:215
void offsetIndices(OpBuilder &b, LinalgOp linalgOp, ArrayRef< OpFoldResult > offests)
Add the specified offsets to any linalg.index ops contained in the given linalgOp.
Definition Utils.cpp:1754
SmallVector< int64_t > getPackInverseDestPerm(linalg::PackOp packOp, PackingMetadata &metadata)
Compute inverse permutation for the destination tensor (i.e.
SmallVector< std::optional< SliceParameters > > computeAllSliceParameters(OpBuilder &builder, Location loc, LinalgOp linalgOp, ValueRange valuesToTile, ArrayRef< OpFoldResult > ivs, ArrayRef< OpFoldResult > tileSizes, ArrayRef< OpFoldResult > sizeBounds, bool omitPartialTileCheck)
Computes SliceParamaters for all valuesToTile of the given linalgOp, assuming linalgOp is being fused...
Definition Utils.cpp:1681
Operation * makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile, ArrayRef< OpFoldResult > tileSizes, AffineMap map, ArrayRef< OpFoldResult > lbs, ArrayRef< OpFoldResult > ubs, ArrayRef< OpFoldResult > subShapeSizes, bool omitPartialTileCheck)
Creates an extract_slice/subview op for a single valueToTile with builder.
Definition Utils.cpp:1483
std::function< SmallVector< ProcInfo >( OpBuilder &b, Location loc, ArrayRef< Range > parallelLoopRanges)> ProcInfoCallBackFn
Definition Utils.h:317
Value makeComposedPadHighOp(OpBuilder &b, Location loc, RankedTensorType type, Value source, Value padding, bool nofold, ValueRange typeDynDims={})
Create a tensor::PadOp that pads source to the shape of type whose sizes are assumed to be greater th...
Definition Utils.cpp:1115
bool isaConvolutionOpOfType(LinalgOp op, SmallVector< int64_t > *dilations, SmallVector< int64_t > *strides)
Given a linalg op this function returns true if it is a convolution op of type ConvOpTy and populates...
void updateBoundsForCyclicDistribution(OpBuilder &builder, Location loc, Value procId, Value nprocs, Value &lb, Value &ub, Value &step)
Update the lb, ub and step to get per processor lb, ub and step.
Definition Utils.cpp:1282
SmallVector< NamedAttribute > getPrunedAttributeList(OpTy op)
Returns an attribute list that excludes pre-defined attributes.
Definition Utils.h:388
SmallVector< Type > getTensorOutputTypes(LinalgOp op, ValueRange operands)
Returns the list of tensor output types produced when the given structured operation op is applied to...
Definition Utils.cpp:1643
SliceParameters computeSliceParameters(OpBuilder &builder, Location loc, Value valueToTile, ArrayRef< OpFoldResult > tileSizes, AffineMap map, ArrayRef< OpFoldResult > lbs, ArrayRef< OpFoldResult > ubs, ArrayRef< OpFoldResult > subShapeSizes, bool omitPartialTileCheck)
Computes SliceParameters for a single valueToTile assuming that its user is being tiled with the give...
Definition Utils.cpp:1496
SmallVector< Value > ValueVector
An owning vector of values, handy to return from functions.
Definition SCF.h:64
Include the generated interface declarations.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:152
A struct containing the Linalg producer before and after fusion.
Definition Utils.h:236
LinalgOp originalProducer
Definition Utils.h:237
Utility class used to generate nested loops with ranges described by loopRanges and loop type describ...
Definition Utils.h:376
static void doit(OpBuilder &b, Location loc, ArrayRef< Range > loopRanges, LinalgOp linalgOp, ArrayRef< utils::IteratorType > iteratorTypes, function_ref< scf::ValueVector(OpBuilder &, Location, ValueRange, ValueRange)> bodyBuilderFn, ArrayRef< linalg::ProcInfo > procInfo={})
Options that allow distribution of loops generated in Linalg transforms to processors while generatin...
Definition Utils.h:322
ProcInfoCallBackFn procInfo
Callback function that returns the Values for processor ID (procId), and number of processors (nprocs...
Definition Utils.h:329
Callback function type used to get processor ID, and number of processors used for distribution for a...
Definition Utils.h:312
DistributionMethod distributionMethod
Definition Utils.h:315
A struct containing common matchers over linalg op's region.
Definition Utils.h:347
static std::optional< BinaryOpKind > matchAsScalarBinaryOp(GenericOp op)
Matches the given linalg op if its body is performing binary operation on int or float scalar values ...
Definition Utils.cpp:93
A struct containg offsets-sizes-strides arguments of the tiled shape.
Definition Utils.h:158
SmallVector< OpFoldResult > strides
Definition Utils.h:161
SmallVector< OpFoldResult > sizes
Definition Utils.h:160
SmallVector< OpFoldResult > offsets
Definition Utils.h:159