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// Fusion / Tiling utilities
107//===----------------------------------------------------------------------===//
108
109/// The type of loops to be generated during tiling.
115
116/// Computes tile offsets, given a list of loop `ivs` and `tileSizes`. In case
117/// a tile size is zero (i.e., no tiling), the corresponding offset is also
118/// zero.
121 ArrayRef<OpFoldResult> tileSizes);
122
123/// Computes tile sizes, given a list of `tileSizes` and dimension
124/// sizes (`sizeBounds`). In case a tile size is zero (i.e., no tiling), the
125/// corresponding result size is the corresponding value from `sizeBounds`.
126/// Note: The returned tile sizes are closed intervals.
128 ArrayRef<OpFoldResult> tileSizes,
129 ArrayRef<OpFoldResult> sizeBounds);
130
131/// Returns the list of tensor output types produced when the given structured
132/// operation `op` is applied to the given `operands`. Note that `operands`
133/// are not necessarily the actual operands of `op`.
135
136/// Creates `insert_slice` ops that insert `results` back into larger tensors
137/// they were originally extracted from with `extract_slice` before being
138/// passed as `operands` to the given structured operation `op` or its clone.
139/// Note that `operands` are not necessarily the actual operands of `op`, the
140/// operation serves only as metadata container for operand types and
141/// positions.
143 LinalgOp op, ValueRange operands,
144 ValueRange results);
145
146/// A struct containg offsets-sizes-strides arguments of the tiled shape.
152
153/// Computes SliceParameters for a single `valueToTile` assuming that its user
154/// is being tiled with the given loop bounds `lbs` and `ubs` and the tile
155/// sizes `tileSizes`.
156///
157/// `omitPartialTileCheck` controls whether to omit the partial/boundary tile
158/// condition check in cases where we statically know that it is unnecessary.
160computeSliceParameters(OpBuilder &builder, Location loc, Value valueToTile,
161 ArrayRef<OpFoldResult> tileSizes, AffineMap map,
163 ArrayRef<OpFoldResult> subShapeSizes,
164 bool omitPartialTileCheck);
165
166/// Computes SliceParamaters for all `valuesToTile` of the given `linalgOp`,
167/// assuming `linalgOp` is being fused into a loop nest. Calls
168/// `computeSliceParameters` for every individual value.
169///
170/// Note that a constant zero in `tileSizes` means no tiling at that implicit
171/// loop. The number of non-zero values in `tileSizes` should be equal to the
172/// number of values in `ivs`.
173///
174/// Some of the `valuesToTile` won't be affected by tiling. For these values,
175/// std::nullopt will be returned.
177computeAllSliceParameters(OpBuilder &builder, Location loc, LinalgOp linalgOp,
178 ValueRange valuesToTile, ArrayRef<OpFoldResult> ivs,
179 ArrayRef<OpFoldResult> tileSizes,
180 ArrayRef<OpFoldResult> sizeBounds,
181 bool omitPartialTileCheck);
182
183/// Creates an extract_slice/subview op for a single `valueToTile` with
184/// `builder`. This new operation extracts a tile of `valueToTile`, starting
185/// at offsets `lbs` and with sizes `subShapeSizes`. `omitPartialTileCheck`
186/// controls whether to omit the partial/boundary tile condition check in
187/// cases where we statically know that it is unnecessary.
188Operation *makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile,
189 ArrayRef<OpFoldResult> tileSizes, AffineMap map,
192 ArrayRef<OpFoldResult> subShapeSizes,
193 bool omitPartialTileCheck);
194
195/// Creates extract_slice/subview ops for all `valuesToTile` of the given
196/// `linalgOp` with `builder`, assuming `linalgOp` is being fused into a loop
197/// nest for tiling with the given induction variables `ivs` and tile sizes
198/// `tileSizes`. `sizeBounds` are the iteration space bounds for *all* the
199/// implicit loops in `linalgOp`. `omitPartialTileCheck` controls whether to
200/// omit the partial/boundary tile condition check in cases where we
201/// statically know that it is unnecessary.
202///
203/// Note that a constant zero in `tileSizes` means no tiling at that implicit
204/// loop. The number of non-zero values in `tileSizes` should be equal to the
205/// number of values in `ivs`.
207 LinalgOp linalgOp, ValueRange valuesToTile,
209 ArrayRef<OpFoldResult> tileSizes,
210 ArrayRef<OpFoldResult> sizeBounds,
211 bool omitPartialTileCheck);
212
213/// Add the specified offsets to any `linalg.index` ops contained in the given
214/// `linalgOp`. The offsets are provided in the same order as iteration space
215/// dimensions. Null offests are assumed to be zero.
216void offsetIndices(OpBuilder &b, LinalgOp linalgOp,
217 ArrayRef<OpFoldResult> offests);
218void offsetIndices(RewriterBase &b, LinalgOp linalgOp,
219 ArrayRef<OpFoldResult> offests);
220
221/// A struct containing the Linalg producer before and after fusion.
222/// When operating on tensors, `fusedProducer` may feed into a `tensor.cast`
223/// op before the consumer Linalg op, until enough canonicalizations have
224/// applied.
228};
229
230/// This implements the fusion part of the "tileAndFuse on tensors"
231/// transformation and thus requires the `consumerOpOperand` to be a
232/// `extract_slice` op (generally obtained by applying the tiling
233/// transformation).
234FailureOr<FusionInfo> fuseProducerOfTensor(OpBuilder &b,
235 OpOperand &consumerOpOperand);
236
237/// This implements the fusion part of the "tileAndFuse on tensors"
238/// transformation and thus requires the `consumerOpOperand` to be a
239/// `extract_slice` op (generally obtained by applying the tiling
240/// transformation). Assumes `producerOfTensor` is a Linalg op that produces
241/// `consumerOpOperand`.
242FailureOr<FusionInfo> fuseProducerOfTensor(OpBuilder &b,
243 OpResult producerOpResult,
244 OpOperand &consumerOpOperand);
245
246//===----------------------------------------------------------------------===//
247// Distribution utilities
248//===----------------------------------------------------------------------===//
249
250/// Scheme used to distribute loops to processors.
252 /// Cyclic distribution where no assumption is made about the dynamic
253 /// relationship between number of processors and number of iterations of
254 /// the
255 /// distributed loop. Distributes the following loop
256 ///
257 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
258 ///
259 /// to
260 ///
261 /// scf.parallel(%iv)= (%lb + %procId * %step) to (%ub) step (%step *
262 /// %nprocs)
264
265 /// Cyclic distribution where the number of processors can be assumed to be
266 /// more than or equal to the number of iterations of the distributed loop.
267 /// In
268 /// such cases, a simple in-bounds check is enough (instead of materializing
269 /// a
270 /// loop). Distributes the following loop
271 ///
272 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
273 ///
274 /// to
275 ///
276 /// %iv = %lb + %procId * %step
277 /// %cond = arith.cmpi "slt", %iv, %ub
278 /// scf.if %cond {
279 /// ...
280 /// }
282
283 /// Cyclic distribution where the number of processors can be assumed to be
284 /// equal to the number of iterations of the distributed loop. In such
285 /// cases,
286 /// no bounds check is needed. Distributes the following loop
287 ///
288 /// scf.parallel (%iv) = (%lb) to (%ub) step (%step)
289 ///
290 /// to
291 ///
292 /// %iv = %lb + %procId * %step
294
295 /// No Distribution.
297};
298
299/// Callback function type used to get processor ID, and number of processors
300/// used for distribution for all parallel loops generated.
306using ProcInfoCallBackFn = std::function<SmallVector<ProcInfo>(
307 OpBuilder &b, Location loc, ArrayRef<Range> parallelLoopRanges)>;
308
309/// Options that allow distribution of loops generated in Linalg transforms to
310/// processors while generating the loops.
312 /// Callback function that returns the Values for processor ID (`procId`),
313 /// and number of processors (`nprocs`) used to execute the parallel loops.
314 /// The number of `{procId, nprocs}` pairs returned must be equal to the
315 /// number of `parallelLoopRanges` passed into the callback. The
316 /// `parallelLoopRanges` are ranges of the outer parallel loops of the
317 /// operation that do have non-zero tile sizes specified.
319};
320
321/// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and
322/// `step`.
324 Value procId, Value nprocs, Value &lb,
325 Value &ub, Value &step);
326
327//===----------------------------------------------------------------------===//
328// Fusion on tensor utilities
329//===----------------------------------------------------------------------===//
330
331//===----------------------------------------------------------------------===//
332// Generic op region utilities
333//===----------------------------------------------------------------------===//
334
335/// A struct containing common matchers over linalg op's region.
337 enum class BinaryOpKind {
339 };
340
341 /// Matches the given linalg op if its body is performing binary operation
342 /// on int or float scalar values and returns the binary op kind.
343 ///
344 /// The linalg op's region is expected to be
345 /// ```
346 /// {
347 /// ^bb(%a: <scalar-type>, %b: <scalar-type>):
348 /// %0 = <binary-op> %a, %b: <scalar-type>
349 /// linalg.yield %0: <scalar-type>
350 /// }
351 /// ```
352 static std::optional<BinaryOpKind> matchAsScalarBinaryOp(GenericOp op);
353};
354
355//===----------------------------------------------------------------------===//
356// Loop nest utilities
357//===----------------------------------------------------------------------===//
358
359/// Utility class used to generate nested loops with ranges described by
360/// `loopRanges` and loop type described by the `iteratorTypes`.
361/// `bodyBuilderFn` is used to generate the body of the innermost loop. It is
362/// passed a range of loop induction variables and a range of operand values
363/// to use.
364template <typename LoopTy>
366 static void doit(OpBuilder &b, Location loc, ArrayRef<Range> loopRanges,
367 LinalgOp linalgOp,
368 ArrayRef<utils::IteratorType> iteratorTypes,
371 bodyBuilderFn,
372 ArrayRef<linalg::ProcInfo> procInfo = {});
373};
374
375/// Returns an attribute list that excludes pre-defined attributes.
376template <typename OpTy>
378 auto elidedAttrs = llvm::to_vector(op.getAttributeNames());
379 if (isa<linalg::LinalgOp>(op.getOperation()))
380 elidedAttrs.push_back(LinalgDialect::kMemoizedIndexingMapsAttrName);
381 return getPrunedAttributeList(op, elidedAttrs);
382}
383
384} // namespace linalg
385} // namespace mlir
386
387#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:855
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:750
GenericOp makeMemRefCopyOp(OpBuilder &b, Location loc, Value from, Value to)
Returns GenericOp that copies an n-D memref.
Definition Utils.cpp:306
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:736
LinalgTilingLoopType
The type of loops to be generated during tiling.
Definition Utils.h:110
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:913
DistributionMethod
Scheme used to distribute loops to processors.
Definition Utils.h:251
@ None
No Distribution.
Definition Utils.h:296
@ CyclicNumProcsGeNumIters
Cyclic distribution where the number of processors can be assumed to be more than or equal to the num...
Definition Utils.h:281
@ Cyclic
Cyclic distribution where no assumption is made about the dynamic relationship between number of proc...
Definition Utils.h:263
@ CyclicNumProcsEqNumIters
Cyclic distribution where the number of processors can be assumed to be equal to the number of iterat...
Definition Utils.h:293
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:775
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:877
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:804
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:606
std::function< SmallVector< ProcInfo >( OpBuilder &b, Location loc, ArrayRef< Range > parallelLoopRanges)> ProcInfoCallBackFn
Definition Utils.h:306
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:238
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:405
SmallVector< NamedAttribute > getPrunedAttributeList(OpTy op)
Returns an attribute list that excludes pre-defined attributes.
Definition Utils.h:377
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:766
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:619
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:225
LinalgOp originalProducer
Definition Utils.h:226
Utility class used to generate nested loops with ranges described by loopRanges and loop type describ...
Definition Utils.h:365
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:311
ProcInfoCallBackFn procInfo
Callback function that returns the Values for processor ID (procId), and number of processors (nprocs...
Definition Utils.h:318
Callback function type used to get processor ID, and number of processors used for distribution for a...
Definition Utils.h:301
DistributionMethod distributionMethod
Definition Utils.h:304
A struct containing common matchers over linalg op's region.
Definition Utils.h:336
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:147
SmallVector< OpFoldResult > strides
Definition Utils.h:150
SmallVector< OpFoldResult > sizes
Definition Utils.h:149
SmallVector< OpFoldResult > offsets
Definition Utils.h:148