MLIR  19.0.0git
Transforms.h
Go to the documentation of this file.
1 //===- Transforms.h - SCF dialect transformation 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 transformations on SCF operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
14 #define MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
15 
17 #include "mlir/Support/LLVM.h"
18 #include "llvm/ADT/ArrayRef.h"
19 
20 namespace mlir {
21 
22 struct LogicalResult;
23 class Region;
24 class RewriterBase;
25 class Operation;
26 class Value;
27 
28 namespace scf {
29 
30 class IfOp;
31 class ForallOp;
32 class ForOp;
33 class ParallelOp;
34 class WhileOp;
35 
36 /// Try converting scf.forall into a set of nested scf.for loops.
37 /// The newly created scf.for ops will be returned through the `results`
38 /// vector if provided.
39 LogicalResult forallToForLoop(RewriterBase &rewriter, ForallOp forallOp,
40  SmallVectorImpl<Operation *> *results = nullptr);
41 
42 /// Fuses all adjacent scf.parallel operations with identical bounds and step
43 /// into one scf.parallel operations. Uses a naive aliasing and dependency
44 /// analysis.
45 /// User can additionally customize alias checking with `mayAlias` hook.
46 /// `mayAlias` must return false if 2 values are guaranteed to not alias.
47 void naivelyFuseParallelOps(Region &region,
49 
50 /// Rewrite a for loop with bounds/step that potentially do not divide evenly
51 /// into a for loop where the step divides the iteration space evenly, followed
52 /// by another scf.for for the last (partial) iteration (if any; returned via
53 /// `partialIteration`). This transformation is called "loop peeling".
54 ///
55 /// This transformation is beneficial for a wide range of transformations such
56 /// as vectorization or loop tiling: It enables additional canonicalizations
57 /// inside the peeled loop body such as rewriting masked loads into unmaked
58 /// loads.
59 ///
60 /// E.g., assuming a lower bound of 0 (for illustration purposes):
61 /// ```
62 /// scf.for %iv = %c0 to %ub step %c4 {
63 /// (loop body)
64 /// }
65 /// ```
66 /// is rewritten into the following pseudo IR:
67 /// ```
68 /// %newUb = %ub - (%ub mod %c4)
69 /// scf.for %iv = %c0 to %newUb step %c4 {
70 /// (loop body)
71 /// }
72 /// scf.for %iv2 = %newUb to %ub {
73 /// (loop body)
74 /// }
75 /// ```
76 ///
77 /// After loop peeling, this function tries to simplify affine.min and
78 /// affine.max ops in the body of the peeled loop and in the body of the partial
79 /// iteration loop, taking advantage of the fact that the peeled loop has only
80 /// "full" iterations. This simplification is expected to enable further
81 /// canonicalization opportunities through other patterns.
82 ///
83 /// The return value indicates whether the loop was rewritten or not. Loops are
84 /// not rewritten if:
85 /// * Loop step size is 1 or
86 /// * Loop bounds and step size are static, and step already divides the
87 /// iteration space evenly.
88 ///
89 /// Note: This function rewrites the given scf.for loop in-place and creates a
90 /// new scf.for operation for the last iteration. It replaces all uses of the
91 /// unpeeled loop with the results of the newly generated scf.for.
93  scf::ForOp &partialIteration);
94 
95 /// Peel the first iteration out of the scf.for loop. If there is only one
96 /// iteration, return the original loop.
98  scf::ForOp &partialIteration);
99 
100 /// Tile a parallel loop of the form
101 /// scf.parallel (%i0, %i1) = (%arg0, %arg1) to (%arg2, %arg3)
102 /// step (%arg4, %arg5)
103 ///
104 /// into
105 /// scf.parallel (%i0, %i1) = (%arg0, %arg1) to (%arg2, %arg3)
106 /// step (%arg4*tileSize[0],
107 /// %arg5*tileSize[1])
108 /// scf.parallel (%j0, %j1) = (0, 0) to (min(tileSize[0], %arg2-%j0)
109 /// min(tileSize[1], %arg3-%j1))
110 /// step (%arg4, %arg5)
111 /// The old loop is replaced with the new one.
112 ///
113 /// The function returns the resulting ParallelOps, i.e. {outer_loop_op,
114 /// inner_loop_op}.
115 std::pair<ParallelOp, ParallelOp>
116 tileParallelLoop(ParallelOp op, llvm::ArrayRef<int64_t> tileSizes,
117  bool noMinMaxBounds);
118 
119 /// Options to dictate how loops should be pipelined.
121  /// Lambda returning all the operation in the forOp, with their stage, in the
122  /// order picked for the pipelined loop.
123  using GetScheduleFnType = std::function<void(
124  scf::ForOp, std::vector<std::pair<Operation *, unsigned>> &)>;
126  enum class PipelinerPart {
127  Prologue,
128  Kernel,
129  Epilogue,
130  };
131  /// Lambda called by the pipeliner to allow the user to annotate the IR while
132  /// it is generated.
133  /// The callback passes the operation created along with the part of the
134  /// pipeline and the iteration index. The iteration index is always 0 for the
135  /// kernel. For the prologue and epilogue, it corresponds to the iteration
136  /// peeled out of the loop in the range [0, maxStage[.
138  std::function<void(Operation *, PipelinerPart, unsigned)>;
140 
141  /// Control whether the epilogue should be peeled out of the loop or
142  /// operations should be predicated to skip the early stages in the last loop
143  /// iterations. If the epilogue is predicated; the user needs to provide a
144  /// lambda to generate the predicated version of operations.
145  bool peelEpilogue = true;
146 
147  /// Control whether the transformation checks that the number of iterations is
148  /// greater or equal to the number of stages and skip the transformation if
149  /// this is not the case. If the loop is dynamic and this is set to true and
150  /// the loop bounds are not static the pipeliner will have to predicate
151  /// operations in the the prologue/epilogue.
152  bool supportDynamicLoops = false;
153 
154  // Callback to predicate operations when the prologue or epilogue are not
155  // peeled. This takes the original operation, an i1 predicate value and the
156  // pattern rewriter. It is expected to replace the given operation with
157  // the predicated equivalent and return it, or return nullptr if the
158  // predication is impossible. In the latter case, pipelining will fail and
159  // may leave IR in a partially transformed state.
161  std::function<Operation *(RewriterBase &, Operation *, Value)>;
163 
164  // TODO: add option to decide if the prologue should be peeled.
165 };
166 
167 /// Generate a pipelined version of the scf.for loop based on the schedule given
168 /// as option. This applies the mechanical transformation of changing the loop
169 /// and generating the prologue/epilogue for the pipelining and doesn't make any
170 /// decision regarding the schedule.
171 /// Based on the options the loop is split into several stages.
172 /// The transformation assumes that the scheduling given by user is valid.
173 /// For example if we break a loop into 3 stages named S0, S1, S2 we would
174 /// generate the following code with the number in parenthesis as the iteration
175 /// index:
176 ///
177 /// S0(0) // Prologue
178 /// S0(1) S1(0) // Prologue
179 /// scf.for %I = %C0 to %N - 2 {
180 /// S0(I+2) S1(I+1) S2(I) // Pipelined kernel
181 /// }
182 /// S1(N) S2(N-1) // Epilogue
183 /// S2(N) // Epilogue
184 ///
185 /// If `modifiedIR` is provided, it will be set to a value that indicates
186 /// whether pipelining modified the IR before failing, signaling to the caller
187 /// whether they can proceed with different transformations.
188 FailureOr<ForOp> pipelineForLoop(RewriterBase &rewriter, ForOp forOp,
189  const PipeliningOption &options,
190  bool *modifiedIR = nullptr);
191 
192 /// Create zero-trip-check around a `while` op and return the new loop op in the
193 /// check. The while loop is rotated to avoid evaluating the condition twice
194 ///
195 /// By default the check won't be created for do-while loop as it is not
196 /// required. `forceCreateCheck` can force the creation.
197 ///
198 /// It turns:
199 ///
200 /// scf.while (%arg0 = %init) : (i32) -> i64 {
201 /// %val = .., %arg0 : i64
202 /// %cond = arith.cmpi .., %arg0 : i32
203 /// scf.condition(%cond) %val : i64
204 /// } do {
205 /// ^bb0(%arg1: i64):
206 /// %next = .., %arg1 : i32
207 /// scf.yield %next : i32
208 /// }
209 ///
210 /// into:
211 ///
212 /// %pre_val = .., %init : i64
213 /// %pre_cond = arith.cmpi .., %init : i32
214 /// scf.if %pre_cond -> i64 {
215 /// %res = scf.while (%arg1 = %va0) : (i64) -> i64 {
216 /// %next = .., %arg1 : i32
217 /// %val = .., %next : i64
218 /// %cond = arith.cmpi .., %next : i32
219 /// scf.condition(%cond) %val : i64
220 /// } do {
221 /// ^bb0(%arg2: i64):
222 /// %scf.yield %arg2 : i32
223 /// }
224 /// scf.yield %res : i64
225 /// } else {
226 /// scf.yield %pre_val : i64
227 /// }
229  RewriterBase &rewriter,
230  bool forceCreateCheck = false);
231 
232 /// Try to uplift `scf.while` op to `scf.for`.
233 /// Uplifitng expects a specific ops pattern:
234 /// * `before` block consisting of single arith.cmp op
235 /// * `after` block containing arith.addi
237 
238 } // namespace scf
239 } // namespace mlir
240 
241 #endif // MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
static bool mayAlias(Value first, Value second)
Returns true if two values may be referencing aliasing memory.
static llvm::ManagedStatic< PassManagerOptions > options
This class provides support for representing a failure result, or a valid value of type T.
Definition: LogicalResult.h:78
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...
Definition: PatternMatch.h:400
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
FailureOr< ForOp > upliftWhileToForLoop(RewriterBase &rewriter, WhileOp loop)
Try to uplift scf.while op to scf.for.
void naivelyFuseParallelOps(Region &region, llvm::function_ref< bool(Value, Value)> mayAlias)
Fuses all adjacent scf.parallel operations with identical bounds and step into one scf....
std::pair< ParallelOp, ParallelOp > tileParallelLoop(ParallelOp op, llvm::ArrayRef< int64_t > tileSizes, bool noMinMaxBounds)
Tile a parallel loop of the form scf.parallel (i0, i1) = (arg0, arg1) to (arg2, arg3) step (arg4,...
LogicalResult peelForLoopAndSimplifyBounds(RewriterBase &rewriter, ForOp forOp, scf::ForOp &partialIteration)
Rewrite a for loop with bounds/step that potentially do not divide evenly into a for loop where the s...
LogicalResult forallToForLoop(RewriterBase &rewriter, ForallOp forallOp, SmallVectorImpl< Operation * > *results=nullptr)
Try converting scf.forall into a set of nested scf.for loops.
LogicalResult peelForLoopFirstIteration(RewriterBase &rewriter, ForOp forOp, scf::ForOp &partialIteration)
Peel the first iteration out of the scf.for loop.
FailureOr< WhileOp > wrapWhileLoopInZeroTripCheck(WhileOp whileOp, RewriterBase &rewriter, bool forceCreateCheck=false)
Create zero-trip-check around a while op and return the new loop op in the check.
FailureOr< ForOp > pipelineForLoop(RewriterBase &rewriter, ForOp forOp, const PipeliningOption &options, bool *modifiedIR=nullptr)
Generate a pipelined version of the scf.for loop based on the schedule given as option.
Include the generated interface declarations.
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
Options to dictate how loops should be pipelined.
Definition: Transforms.h:120
std::function< void(scf::ForOp, std::vector< std::pair< Operation *, unsigned > > &)> GetScheduleFnType
Lambda returning all the operation in the forOp, with their stage, in the order picked for the pipeli...
Definition: Transforms.h:124
GetScheduleFnType getScheduleFn
Definition: Transforms.h:125
std::function< void(Operation *, PipelinerPart, unsigned)> AnnotationlFnType
Lambda called by the pipeliner to allow the user to annotate the IR while it is generated.
Definition: Transforms.h:138
bool peelEpilogue
Control whether the epilogue should be peeled out of the loop or operations should be predicated to s...
Definition: Transforms.h:145
AnnotationlFnType annotateFn
Definition: Transforms.h:139
bool supportDynamicLoops
Control whether the transformation checks that the number of iterations is greater or equal to the nu...
Definition: Transforms.h:152
std::function< Operation *(RewriterBase &, Operation *, Value)> PredicateOpFn
Definition: Transforms.h:161