MLIR 22.0.0git
Utils.h
Go to the documentation of this file.
1//===- Utils.h - SCF dialect utilities --------------------------*- 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 prototypes for various SCF utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_DIALECT_SCF_UTILS_UTILS_H_
14#define MLIR_DIALECT_SCF_UTILS_UTILS_H_
15
18#include "mlir/Support/LLVM.h"
19#include "llvm/ADT/STLExtras.h"
20#include <optional>
21
22namespace mlir {
23class Location;
24class Operation;
25class OpBuilder;
26class Region;
27class RewriterBase;
28class ValueRange;
29class Value;
30
31namespace func {
32class CallOp;
33class FuncOp;
34} // namespace func
35
36/// Update a perfectly nested loop nest to yield new values from the innermost
37/// loop and propagating it up through the loop nest. This function
38/// - Expects `loopNest` to be a perfectly nested loop with outer most loop
39/// first and innermost loop last.
40/// - `newIterOperands` are the initialization values to be used for the
41/// outermost loop
42/// - `newYielValueFn` is the callback that generates the new values to be
43/// yielded from within the innermost loop.
44/// - The original loops are not erased, but are left in a "no-op" state where
45/// the body of the loop just yields the basic block arguments that correspond
46/// to the initialization values of a loop. The original loops are dead after
47/// this method.
48/// - If `replaceIterOperandsUsesInLoop` is true, all uses of the
49/// `newIterOperands` within the generated new loop are replaced with the
50/// corresponding `BlockArgument` in the loop body.
52 RewriterBase &rewriter, MutableArrayRef<scf::ForOp> loopNest,
53 ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn,
54 bool replaceIterOperandsUsesInLoop = true);
55
56/// Outline a region with a single block into a new FuncOp.
57/// Assumes the FuncOp result types is the type of the yielded operands of the
58/// single block. This constraint makes it easy to determine the result.
59/// This method also clones the `arith::ConstantIndexOp` at the start of
60/// `outlinedFuncBody` to alloc simple canonicalizations.
61/// Creates a new FuncOp and thus cannot be used in a FuncOp pass.
62/// The client is responsible for providing a unique `funcName` that will not
63/// collide with another FuncOp name. If `callOp` is provided, it will be set
64/// to point to the operation that calls the outlined function.
65// TODO: support more than single-block regions.
66// TODO: more flexible constant handling.
67FailureOr<func::FuncOp>
69 StringRef funcName, func::CallOp *callOp = nullptr);
70
71/// Outline the then and/or else regions of `ifOp` as follows:
72/// - if `thenFn` is not null, `thenFnName` must be specified and the `then`
73/// region is inlined into a new FuncOp that is captured by the pointer.
74/// - if `elseFn` is not null, `elseFnName` must be specified and the `else`
75/// region is inlined into a new FuncOp that is captured by the pointer.
76/// Creates new FuncOps and thus cannot be used in a FuncOp pass.
77/// The client is responsible for providing a unique `thenFnName`/`elseFnName`
78/// that will not collide with another FuncOp name.
79LogicalResult outlineIfOp(RewriterBase &b, scf::IfOp ifOp, func::FuncOp *thenFn,
80 StringRef thenFnName, func::FuncOp *elseFn,
81 StringRef elseFnName);
82
83/// Get a list of innermost parallel loops contained in `rootOp`. Innermost
84/// parallel loops are those that do not contain further parallel loops
85/// themselves.
88
89/// Return the min/max expressions for `value` if it is an induction variable
90/// from scf.for or scf.parallel loop.
91/// if `loopFilter` is passed, the filter determines which loop to consider.
92/// Other induction variables are ignored.
93std::optional<std::pair<AffineExpr, AffineExpr>>
96 llvm::function_ref<bool(Operation *)> loopFilter = nullptr);
97
98/// Replace a perfect nest of "for" loops with a single linearized loop. Assumes
99/// `loops` contains a list of perfectly nested loops with bounds and steps
100/// independent of any loop induction variable involved in the nest.
101LogicalResult coalesceLoops(MutableArrayRef<scf::ForOp> loops);
102LogicalResult coalesceLoops(RewriterBase &rewriter,
104
105/// Walk an affine.for to find a band to coalesce.
106LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op);
107
108/// Take the ParallelLoop and for each set of dimension indices, combine them
109/// into a single dimension. combinedDimensions must contain each index into
110/// loops exactly once.
111void collapseParallelLoops(RewriterBase &rewriter, scf::ParallelOp loops,
112 ArrayRef<std::vector<unsigned>> combinedDimensions);
113
115 std::optional<scf::ForOp> mainLoopOp = std::nullopt;
116 std::optional<scf::ForOp> epilogueLoopOp = std::nullopt;
117};
118
119/// Unrolls this for operation by the specified unroll factor. Returns the
120/// unrolled main loop and the epilogue loop, if the loop is unrolled. Otherwise
121/// returns failure if the loop cannot be unrolled either due to restrictions or
122/// due to invalid unroll factors. Requires positive loop bounds and step. If
123/// specified, annotates the Ops in each unrolled iteration by applying
124/// `annotateFn`.
125FailureOr<UnrolledLoopInfo> loopUnrollByFactor(
126 scf::ForOp forOp, uint64_t unrollFactor,
127 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn = nullptr);
128
129/// Unrolls this loop completely.
130LogicalResult loopUnrollFull(scf::ForOp forOp);
131
132/// Unrolls and jams this `scf.for` operation by the specified unroll factor.
133/// Returns failure if the loop cannot be unrolled either due to restrictions or
134/// due to invalid unroll factors. In case of unroll factor of 1, the function
135/// bails out without doing anything (returns success). Currently, only constant
136/// trip count that are divided by the unroll factor is supported. Currently,
137/// for operations with results are not supported.
138LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor);
139
140/// Materialize bounds and step of a zero-based and unit-step loop derived by
141/// normalizing the specified bounds and step.
144 OpFoldResult step);
145
146/// Get back the original induction variable values after loop normalization.
148 Value normalizedIv, OpFoldResult origLb,
149 OpFoldResult origStep);
150
151/// Tile a nest of standard for loops rooted at `rootForOp` by finding such
152/// parametric tile sizes that the outer loops have a fixed number of iterations
153/// as defined in `sizes`.
155using TileLoops = std::pair<Loops, Loops>;
156TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef<int64_t> sizes);
157
158/// Performs tiling fo imperfectly nested loops (with interchange) by
159/// strip-mining the `forOps` by `sizes` and sinking them, in their order of
160/// occurrence in `forOps`, under each of the `targets`.
161/// Returns the new AffineForOps, one per each of (`forOps`, `targets`) pair,
162/// nested immediately under each of `targets`.
164 ArrayRef<scf::ForOp> targets);
165
166/// Performs tiling (with interchange) by strip-mining the `forOps` by `sizes`
167/// and sinking them, in their order of occurrence in `forOps`, under `target`.
168/// Returns the new AffineForOps, one per `forOps`, nested immediately under
169/// `target`.
171 scf::ForOp target);
172
173/// Tile a nest of scf::ForOp loops rooted at `rootForOp` with the given
174/// (parametric) sizes. Sizes are expected to be strictly positive values at
175/// runtime. If more sizes than loops are provided, discard the trailing values
176/// in sizes. Assumes the loop nest is permutable.
177/// Returns the newly created intra-tile loops.
178Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef<Value> sizes);
179
180/// Get perfectly nested sequence of loops starting at root of loop nest
181/// (the first op being another AffineFor, and the second op - a terminator).
182/// A loop is perfectly nested iff: the first op in the loop's body is another
183/// AffineForOp, and the second op is a terminator).
185 scf::ForOp root);
186
187/// Given two scf.forall loops, `target` and `source`, fuses `target` into
188/// `source`. Assumes that the given loops are siblings and are independent of
189/// each other.
190///
191/// This function does not perform any legality checks and simply fuses the
192/// loops. The caller is responsible for ensuring that the loops are legal to
193/// fuse.
194scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target,
195 scf::ForallOp source,
196 RewriterBase &rewriter);
197
198/// Given two scf.for loops, `target` and `source`, fuses `target` into
199/// `source`. Assumes that the given loops are siblings and are independent of
200/// each other.
201///
202/// This function does not perform any legality checks and simply fuses the
203/// loops. The caller is responsible for ensuring that the loops are legal to
204/// fuse.
205scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source,
206 RewriterBase &rewriter);
207
208/// Normalize an `scf.forall` operation. Returns `failure()`if normalization
209/// fails.
210// On `success()` returns the
211/// newly created operation with all uses of the original operation replaced
212/// with results of the new operation.
213FailureOr<scf::ForallOp> normalizeForallOp(RewriterBase &rewriter,
214 scf::ForallOp forallOp);
215
216/// Check if the provided loops are perfectly nested for-loops. Perfect nesting
217/// means:
218/// 1. All loops are scf.for operations
219/// 2. Each outer loop's region iter args match the inner loop's init args
220/// 3. Each outer loop's yields match the inner loop's results
221/// 4. Each region iter arg and result has exactly one use
223
224/// Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs'
225/// and 'yieldedValues' as the block arguments and yielded values of the loop.
226/// The content of the loop body is replicated 'unrollFactor' times, calling
227/// 'ivRemapFn' to remap 'iv' for each unrolled body. If specified, annotates
228/// the Ops in each unrolled iteration using annotateFn. If provided,
229/// 'clonedToSrcOpsMap' is populated with the mappings from the cloned ops to
230/// the original op.
232 Block *loopBodyBlock, Value iv, uint64_t unrollFactor,
233 function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
234 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
235 ValueRange iterArgs, ValueRange yieldedValues,
236 IRMapping *clonedToSrcOpsMap = nullptr);
237
238/// Unroll this scf::Parallel loop by the specified unroll factors. Returns the
239/// unrolled loop if the unroll succeded; otherwise returns failure if the loop
240/// cannot be unrolled either due to restrictions or to invalid unroll factors.
241/// Requires positive loop bounds and step. If specified, annotates the Ops in
242/// each unrolled iteration by applying `annotateFn`.
243/// If provided, 'clonedToSrcOpsMap' is populated with the mappings from the
244/// cloned ops to the original op.
245FailureOr<scf::ParallelOp> parallelLoopUnrollByFactors(
246 scf::ParallelOp op, ArrayRef<uint64_t> unrollFactors,
247 RewriterBase &rewriter,
248 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn = nullptr,
249 IRMapping *clonedToSrcOpsMap = nullptr);
250
251/// Get constant trip counts for each of the induction variables of the given
252/// loop operation. If any of the loop's trip counts is not constant, return an
253/// empty vector.
255getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp);
256
257} // namespace mlir
258
259#endif // MLIR_DIALECT_SCF_UTILS_UTILS_H_
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Block represents an ordered list of Operations.
Definition Block.h:33
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
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 a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
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
Include the generated interface declarations.
void getPerfectlyNestedLoops(SmallVectorImpl< scf::ForOp > &nestedLoops, scf::ForOp root)
Get perfectly nested sequence of loops starting at root of loop nest (the first op being another Affi...
Definition Utils.cpp:1326
bool isPerfectlyNestedForLoops(MutableArrayRef< LoopLikeOpInterface > loops)
Check if the provided loops are perfectly nested for-loops.
Definition Utils.cpp:1524
LogicalResult outlineIfOp(RewriterBase &b, scf::IfOp ifOp, func::FuncOp *thenFn, StringRef thenFnName, func::FuncOp *elseFn, StringRef elseFnName)
Outline the then and/or else regions of ifOp as follows:
Definition Utils.cpp:217
SmallVector< scf::ForOp > replaceLoopNestWithNewYields(RewriterBase &rewriter, MutableArrayRef< scf::ForOp > loopNest, ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn, bool replaceIterOperandsUsesInLoop=true)
Update a perfectly nested loop nest to yield new values from the innermost loop and propagating it up...
Definition Utils.cpp:35
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op)
Walk an affine.for to find a band to coalesce.
Definition Utils.cpp:994
void generateUnrolledLoop(Block *loopBodyBlock, Value iv, uint64_t unrollFactor, function_ref< Value(unsigned, Value, OpBuilder)> ivRemapFn, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn, ValueRange iterArgs, ValueRange yieldedValues, IRMapping *clonedToSrcOpsMap=nullptr)
Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs' and 'yieldedValues' as the...
Definition Utils.cpp:294
llvm::SmallVector< int64_t > getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp)
Get constant trip counts for each of the induction variables of the given loop operation.
Definition Utils.cpp:1563
LogicalResult loopUnrollFull(scf::ForOp forOp)
Unrolls this loop completely.
Definition Utils.cpp:495
std::pair< Loops, Loops > TileLoops
Definition Utils.h:155
void collapseParallelLoops(RewriterBase &rewriter, scf::ParallelOp loops, ArrayRef< std::vector< unsigned > > combinedDimensions)
Take the ParallelLoop and for each set of dimension indices, combine them into a single dimension.
Definition Utils.cpp:1069
Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef< Value > sizes)
Tile a nest of scf::ForOp loops rooted at rootForOp with the given (parametric) sizes.
Definition Utils.cpp:1314
FailureOr< UnrolledLoopInfo > loopUnrollByFactor(scf::ForOp forOp, uint64_t unrollFactor, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr)
Unrolls this for operation by the specified unroll factor.
Definition Utils.cpp:367
LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor)
Unrolls and jams this scf.for operation by the specified unroll factor.
Definition Utils.cpp:523
bool getInnermostParallelLoops(Operation *rootOp, SmallVectorImpl< scf::ParallelOp > &result)
Get a list of innermost parallel loops contained in rootOp.
Definition Utils.cpp:240
FailureOr< scf::ParallelOp > parallelLoopUnrollByFactors(scf::ParallelOp op, ArrayRef< uint64_t > unrollFactors, RewriterBase &rewriter, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, IRMapping *clonedToSrcOpsMap=nullptr)
Unroll this scf::Parallel loop by the specified unroll factors.
Definition Utils.cpp:1580
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:1293
FailureOr< func::FuncOp > outlineSingleBlockRegion(RewriterBase &rewriter, Location loc, Region &region, StringRef funcName, func::CallOp *callOp=nullptr)
Outline a region with a single block into a new FuncOp.
Definition Utils.cpp:114
void denormalizeInductionVariable(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
Get back the original induction variable values after loop normalization.
Definition Utils.cpp:774
std::optional< std::pair< AffineExpr, AffineExpr > > getSCFMinMaxExpr(Value value, SmallVectorImpl< Value > &dims, SmallVectorImpl< Value > &symbols, llvm::function_ref< bool(Operation *)> loopFilter=nullptr)
Return the min/max expressions for value if it is an induction variable from scf.for or scf....
scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target, scf::ForallOp source, RewriterBase &rewriter)
Given two scf.forall loops, target and source, fuses target into source.
Definition Utils.cpp:1373
LogicalResult coalesceLoops(MutableArrayRef< scf::ForOp > loops)
Replace a perfect nest of "for" loops with a single linearized loop.
Definition Utils.cpp:986
scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source, RewriterBase &rewriter)
Given two scf.for loops, target and source, fuses target into source.
Definition Utils.cpp:1426
llvm::function_ref< Fn > function_ref
Definition LLVM.h:152
TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef< int64_t > sizes)
Definition Utils.cpp:1331
Range emitNormalizedLoopBounds(RewriterBase &rewriter, Location loc, OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
Materialize bounds and step of a zero-based and unit-step loop derived by normalizing the specified b...
Definition Utils.cpp:703
SmallVector< scf::ForOp, 8 > Loops
Tile a nest of standard for loops rooted at rootForOp by finding such parametric tile sizes that the ...
Definition Utils.h:154
FailureOr< scf::ForallOp > normalizeForallOp(RewriterBase &rewriter, scf::ForallOp forallOp)
Normalize an scf.forall operation.
Definition Utils.cpp:1479
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
std::optional< scf::ForOp > epilogueLoopOp
Definition Utils.h:116
std::optional< scf::ForOp > mainLoopOp
Definition Utils.h:115