MLIR 24.0.0git
LoopInvariantCodeMotionUtils.cpp
Go to the documentation of this file.
1//===- LoopInvariantCodeMotionUtils.cpp - LICM Utils ------------*- 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 file contains the implementation of the core LICM algorithm.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "mlir/IR/Operation.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/DebugLog.h"
26#include <queue>
27
28#define DEBUG_TYPE "licm"
29
30using namespace mlir;
31
32/// Checks whether the given op can be hoisted by checking that
33/// - the op and none of its contained operations depend on values inside of the
34/// loop (by means of calling definedOutside).
35/// - the op has no side-effects.
36static bool canBeHoisted(Operation *op,
37 function_ref<bool(OpOperand &)> condition) {
38 // Do not move terminators.
40 return false;
41
42 // Walk the nested operations and check that all used values are either
43 // defined outside of the loop or in a nested region, but not at the level of
44 // the loop body.
45 auto walkFn = [&](Operation *child) {
46 for (OpOperand &operand : child->getOpOperands()) {
47 // Ignore values defined in a nested region.
48 if (op->isAncestor(operand.get().getParentRegion()->getParentOp()))
49 continue;
50 if (!condition(operand))
51 return WalkResult::interrupt();
52 }
53 return WalkResult::advance();
54 };
55 return !op->walk(walkFn).wasInterrupted();
56}
57
58static bool canBeHoisted(Operation *op,
59 function_ref<bool(Value)> definedOutside) {
60 return canBeHoisted(
61 op, [&](OpOperand &operand) { return definedOutside(operand.get()); });
62}
63
65 ArrayRef<Region *> regions,
66 function_ref<bool(Value, Region *)> isDefinedOutsideRegion,
67 function_ref<bool(Operation *, Region *)> shouldMoveOutOfRegion,
68 function_ref<void(Operation *, Region *)> moveOutOfRegion) {
69 size_t numMoved = 0;
70
71 for (Region *region : regions) {
72 LDBG() << "Original loop:\n"
73 << OpWithFlags(region->getParentOp(),
74 OpPrintingFlags().skipRegions());
75
76 std::queue<Operation *> worklist;
77 // Add top-level operations in the loop body to the worklist.
78 for (Operation &op : region->getOps())
79 worklist.push(&op);
80
81 auto definedOutside = [&](Value value) {
82 return isDefinedOutsideRegion(value, region);
83 };
84
85 while (!worklist.empty()) {
86 Operation *op = worklist.front();
87 worklist.pop();
88 // Skip ops that have already been moved. Check if the op can be hoisted.
89 if (op->getParentRegion() != region)
90 continue;
91
92 LDBG() << "Checking op: "
93 << OpWithFlags(op, OpPrintingFlags().skipRegions());
94 if (!shouldMoveOutOfRegion(op, region) ||
95 !canBeHoisted(op, definedOutside))
96 continue;
97
98 LDBG() << "Moving loop-invariant op: "
99 << OpWithFlags(op, OpPrintingFlags().skipRegions());
100 moveOutOfRegion(op, region);
101 ++numMoved;
102
103 // Since the op has been moved, we need to check its users within the
104 // top-level of the loop body.
105 for (Operation *user : op->getUsers())
106 if (user->getParentRegion() == region)
107 worklist.push(user);
108 }
109 }
110
111 return numMoved;
112}
113
114size_t mlir::moveLoopInvariantCode(LoopLikeOpInterface loopLike) {
115 size_t numMoved = moveLoopInvariantCode(
116 loopLike.getLoopRegions(),
117 [&](Value value, Region *) {
118 return loopLike.isDefinedOutsideOfLoop(value);
119 },
120 [&](Operation *op, Region *) { return isPure(op); },
121 [&](Operation *op, Region *) { loopLike.moveOutOfLoop(op); });
122 return numMoved + moveLoopInvariantCodeFromNestedRegions(loopLike);
123}
124
125/// Hoists pure loop-invariant ops out of the control-flow regions nested in
126/// `region`, which is part of the body of `loopLike`. Ops directly in `region`
127/// are hoisted only if `isNested` is set, i.e., if `region` is not a region of
128/// the loop itself. Returns the number of ops moved.
129static size_t hoistFromNestedRegions(Region &region,
130 LoopLikeOpInterface loopLike,
131 bool isNested) {
132 if (region.empty())
133 return 0;
134 size_t numMoved = 0;
135 auto definedOutside = [&](Value value) {
136 return loopLike.isDefinedOutsideOfLoop(value);
137 };
138 // Unreachable blocks are skipped: dominance is not verified there. Reachable
139 // blocks are visited in an order in which definitions precede their uses.
140 for (Block *block : llvm::depth_first(&region.front())) {
141 for (Operation &op : llvm::make_early_inc_range(*block)) {
142 if (isNested && isPure(&op) && canBeHoisted(&op, definedOutside)) {
143 LDBG() << "Moving loop-invariant op: "
144 << OpWithFlags(&op, OpPrintingFlags().skipRegions());
145 loopLike.moveOutOfLoop(&op);
146 ++numMoved;
147 continue;
148 }
149 // Descend into control-flow ops only: ops in other regions may depend on
150 // the enclosing op, and nested loops are processed on their own.
151 if (!isa<RegionBranchOpInterface>(op) || isa<LoopLikeOpInterface>(op))
152 continue;
153 for (Region &nested : op.getRegions())
154 numMoved += hoistFromNestedRegions(nested, loopLike, /*isNested=*/true);
155 }
156 }
157 return numMoved;
158}
159
160size_t
161mlir::moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike) {
162 size_t numMoved = 0;
163 for (Region *region : loopLike.getLoopRegions())
164 numMoved += hoistFromNestedRegions(*region, loopLike, /*isNested=*/false);
165 return numMoved;
166}
167
168namespace {
169/// Helper data structure that keeps track of equivalent/disjoint subset ops.
170class MatchingSubsets {
171public:
172 /// Insert a subset op.
173 void insert(SubsetOpInterface op, bool collectHoistableOps = true) {
174 allSubsetOps.push_back(op);
175 if (!collectHoistableOps)
176 return;
177 if (auto extractionOp =
178 dyn_cast<SubsetExtractionOpInterface>(op.getOperation()))
179 insertExtractionOp(extractionOp);
180 if (auto insertionOp =
181 dyn_cast<SubsetInsertionOpInterface>(op.getOperation()))
182 insertInsertionOp(insertionOp);
183 }
184
185 /// Return a range of matching extraction-insertion subset ops. If there is no
186 /// matching extraction/insertion op, the respective value is empty. Ops are
187 /// skipped if there are other subset ops that are not guaranteed to operate
188 /// on disjoint subsets.
189 auto getHoistableSubsetOps() {
190 return llvm::make_filter_range(
191 llvm::zip(extractions, insertions), [&](auto pair) {
192 auto [extractionOp, insertionOp] = pair;
193 // Hoist only if the extracted and inserted values have the same type.
194 if (extractionOp && insertionOp &&
195 extractionOp->getResult(0).getType() !=
196 insertionOp.getSourceOperand().get().getType())
197 return false;
198 // Hoist only if there are no conflicting subset ops.
199 return allDisjoint(extractionOp, insertionOp);
200 });
201 }
202
203 /// Populate subset ops starting from the given region iter_arg. Return
204 /// "failure" if non-subset ops are found along the path to the loop yielding
205 /// op or if there is no single path to the tied yielded operand. If
206 /// `collectHoistableOps` is set to "false", subset ops are gathered
207 /// throughout the traversal, but not enumerated by `getHoistableSubsetOps`.
208 LogicalResult populateSubsetOpsAtIterArg(LoopLikeOpInterface loopLike,
209 BlockArgument iterArg,
210 bool collectHoistableOps = true);
211
212private:
213 /// Helper function for equivalence of tensor values. Since only insertion
214 /// subset ops (that are also destination style ops) are followed when
215 /// traversing the SSA use-def chain, all tensor values are equivalent.
216 static bool isEquivalent(Value v1, Value v2) { return true; }
217
218 /// Return "true" if the subsets of the given extraction and insertion ops
219 /// are operating disjoint from the subsets that all other known subset ops
220 /// are operating on.
221 bool allDisjoint(SubsetExtractionOpInterface extractionOp,
222 SubsetInsertionOpInterface insertionOp) const {
223 for (SubsetOpInterface other : allSubsetOps) {
224 if (other == extractionOp || other == insertionOp)
225 continue;
226 if (extractionOp &&
227 !other.operatesOnDisjointSubset(extractionOp, isEquivalent))
228 return false;
229 if (insertionOp &&
230 !other.operatesOnDisjointSubset(insertionOp, isEquivalent))
231 return false;
232 }
233 return true;
234 }
235
236 /// Insert a subset extraction op. If the subset is equivalent to an existing
237 /// subset insertion op, pair them up. (If there is already a paired up subset
238 /// extraction op, overwrite the subset extraction op.)
239 void insertExtractionOp(SubsetExtractionOpInterface extractionOp) {
240 for (auto it : llvm::enumerate(insertions)) {
241 if (!it.value())
242 continue;
243 auto other = cast<SubsetOpInterface>(it.value().getOperation());
244 if (other.operatesOnEquivalentSubset(extractionOp, isEquivalent)) {
245 extractions[it.index()] = extractionOp;
246 return;
247 }
248 }
249 // There is no known equivalent insertion op. Create a new entry.
250 extractions.push_back(extractionOp);
251 insertions.push_back({});
252 }
253
254 /// Insert a subset insertion op. If the subset is equivalent to an existing
255 /// subset extraction op, pair them up. (If there is already a paired up
256 /// subset insertion op, overwrite the subset insertion op.)
257 void insertInsertionOp(SubsetInsertionOpInterface insertionOp) {
258 for (auto it : llvm::enumerate(extractions)) {
259 if (!it.value())
260 continue;
261 auto other = cast<SubsetOpInterface>(it.value().getOperation());
262 if (other.operatesOnEquivalentSubset(insertionOp, isEquivalent)) {
263 insertions[it.index()] = insertionOp;
264 return;
265 }
266 }
267 // There is no known equivalent extraction op. Create a new entry.
268 extractions.push_back({});
269 insertions.push_back(insertionOp);
270 }
271
272 SmallVector<SubsetExtractionOpInterface> extractions;
273 SmallVector<SubsetInsertionOpInterface> insertions;
274 SmallVector<SubsetOpInterface> allSubsetOps;
275};
276} // namespace
277
278/// If the given value has a single use by an op that is a terminator, return
279/// that use. Otherwise, return nullptr.
281 if (!value.hasOneUse())
282 return nullptr;
283 OpOperand &use = *value.getUses().begin();
285 return &use;
286 return nullptr;
287}
288
289LogicalResult
290MatchingSubsets::populateSubsetOpsAtIterArg(LoopLikeOpInterface loopLike,
291 BlockArgument iterArg,
292 bool collectHoistableOps) {
293 assert(iterArg.getOwner()->getParentOp() == loopLike && "invalid iter_arg");
294 Value value = iterArg;
295
296 // Traverse use-def chain. Subset ops can be hoisted only if all ops along the
297 // use-def chain starting from the region iter_arg are subset extraction or
298 // subset insertion ops. The chain must terminate at the corresponding yield
299 // operand (e.g., no swapping of iter_args).
300 OpOperand *yieldedOperand = nullptr;
301 // Iterate until the single use of the current SSA value is a terminator,
302 // which is expected to be the yielding operation of the loop.
303 while (!(yieldedOperand = getSingleTerminatorUse(value))) {
304 Value nextValue = {};
305
306 for (OpOperand &use : value.getUses()) {
307 if (auto nestedLoop = dyn_cast<LoopLikeOpInterface>(use.getOwner())) {
308 // Subset ops in nested loops are collected to check if there are only
309 // disjoint subset ops, but such subset ops are not subject to hoisting.
310 // To hoist subset ops from nested loops, the hoisting transformation
311 // should be run on the nested loop.
312 auto nestedIterArg = nestedLoop.getTiedLoopRegionIterArg(&use);
313 if (!nestedIterArg)
314 return failure();
315 // Note: `populateSubsetOpsAtIterArg` fails if there is no single SSA
316 // use-def chain starting at `nestedIterArg` and terminating in the
317 // tied, yielding operand.
318 if (failed(populateSubsetOpsAtIterArg(nestedLoop, nestedIterArg,
319 /*collectHoistableOps=*/false)))
320 return failure();
321 // There must be a single use-def chain. Bail if there are multiple
322 // nested loops using this value.
323 if (nextValue)
324 return failure();
325 nextValue = nestedLoop.getTiedLoopResult(&use);
326 continue;
327 }
328
329 auto subsetOp = dyn_cast<SubsetOpInterface>(use.getOwner());
330 if (!subsetOp)
331 return failure();
332 insert(subsetOp, collectHoistableOps);
333
334 if (auto insertionOp =
335 dyn_cast<SubsetInsertionOpInterface>(use.getOwner())) {
336 // Current implementation expects that the insertionOp implement
337 // the DestinationStyleOpInterface and with pure tensor semantics
338 // as well. Abort if that is not the case.
339 auto dstOp = dyn_cast<DestinationStyleOpInterface>(use.getOwner());
340 if (!dstOp || !dstOp.hasPureTensorSemantics())
341 return failure();
342
343 // The value must be used as a destination. (In case of a source, the
344 // entire tensor would be read, which would prevent any hoisting.)
345 if (&use != &insertionOp.getDestinationOperand())
346 return failure();
347 // There must be a single use-def chain from the region iter_arg to the
348 // terminator. I.e., only one insertion op. Branches are not supported.
349 if (nextValue)
350 return failure();
351 nextValue = insertionOp.getUpdatedDestination();
352 }
353 }
354
355 // Nothing can be hoisted if the chain does not continue with loop yielding
356 // op or a subset insertion op.
357 if (!nextValue)
358 return failure();
359 value = nextValue;
360 }
361
362 // Hoist only if the SSA use-def chain ends in the yielding terminator of the
363 // loop and the yielded value is the `idx`-th operand. (I.e., there is no
364 // swapping yield.)
365 if (loopLike.getTiedLoopYieldedValue(iterArg) != yieldedOperand)
366 return failure();
367
368 return success();
369}
370
371/// Hoist all subset ops that operate on the idx-th region iter_arg of the given
372/// loop-like op and index into loop-invariant subset locations. Return the
373/// newly created loop op (that has extra iter_args) or the original loop op if
374/// nothing was hoisted.
375static LoopLikeOpInterface hoistSubsetAtIterArg(RewriterBase &rewriter,
376 LoopLikeOpInterface loopLike,
377 BlockArgument iterArg) {
378 assert(iterArg.getOwner()->getParentOp() == loopLike && "invalid iter_arg");
379 BlockArgument *it = llvm::find(loopLike.getRegionIterArgs(), iterArg);
380 int64_t iterArgIdx = std::distance(loopLike.getRegionIterArgs().begin(), it);
381 MatchingSubsets subsets;
382 if (failed(subsets.populateSubsetOpsAtIterArg(loopLike, iterArg)))
383 return loopLike;
384
385 // Hoist all matching extraction-insertion pairs one-by-one.
386 for (auto it : subsets.getHoistableSubsetOps()) {
387 auto extractionOp = std::get<0>(it);
388 auto insertionOp = std::get<1>(it);
389
390 // Ops cannot be hoisted if they depend on loop-variant values.
391 if (extractionOp) {
392 if (!canBeHoisted(extractionOp, [&](OpOperand &operand) {
393 return loopLike.isDefinedOutsideOfLoop(operand.get()) ||
394 &operand == &extractionOp.getSourceOperand();
395 }))
396 extractionOp = {};
397 }
398 if (insertionOp) {
399 if (!canBeHoisted(insertionOp, [&](OpOperand &operand) {
400 return loopLike.isDefinedOutsideOfLoop(operand.get()) ||
401 &operand == &insertionOp.getSourceOperand() ||
402 &operand == &insertionOp.getDestinationOperand();
403 }))
404 insertionOp = {};
405 }
406
407 // Only hoist extraction-insertion pairs for now. Standalone extractions/
408 // insertions that are loop-invariant could be hoisted, but there may be
409 // easier ways to canonicalize the IR.
410 if (extractionOp && insertionOp) {
411 // Create a new loop with an additional iter_arg.
412 NewYieldValuesFn newYieldValuesFn =
413 [&](OpBuilder &b, Location loc,
415 return {insertionOp.getSourceOperand().get()};
416 };
417 FailureOr<LoopLikeOpInterface> newLoop =
418 loopLike.replaceWithAdditionalYields(
419 rewriter, extractionOp.getResult(),
420 /*replaceInitOperandUsesInLoop=*/true, newYieldValuesFn);
421 if (failed(newLoop))
422 return loopLike;
423 loopLike = *newLoop;
424
425 // Hoist the extraction/insertion ops.
426 iterArg = loopLike.getRegionIterArgs()[iterArgIdx];
427 OpResult loopResult = loopLike.getTiedLoopResult(iterArg);
428 OpResult newLoopResult = loopLike.getLoopResults()->back();
429 rewriter.moveOpBefore(extractionOp, loopLike);
430 rewriter.moveOpAfter(insertionOp, loopLike);
431 rewriter.replaceAllUsesWith(insertionOp.getUpdatedDestination(),
432 insertionOp.getDestinationOperand().get());
433 extractionOp.getSourceOperand().set(
434 loopLike.getTiedLoopInit(iterArg)->get());
435 rewriter.replaceAllUsesWith(loopResult,
436 insertionOp.getUpdatedDestination());
437 insertionOp.getSourceOperand().set(newLoopResult);
438 insertionOp.getDestinationOperand().set(loopResult);
439 }
440 }
441
442 return loopLike;
443}
444
445LoopLikeOpInterface
447 LoopLikeOpInterface loopLike) {
448 // Note: As subset ops are getting hoisted, the number of region iter_args
449 // increases. This can enable further hoisting opportunities on the new
450 // iter_args.
451 for (int64_t i = 0;
452 i < static_cast<int64_t>(loopLike.getRegionIterArgs().size()); ++i) {
453 loopLike = hoistSubsetAtIterArg(rewriter, loopLike,
454 loopLike.getRegionIterArgs()[i]);
455 }
456 return loopLike;
457}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static OpOperand * getSingleTerminatorUse(Value value)
If the given value has a single use by an op that is a terminator, return that use.
static LoopLikeOpInterface hoistSubsetAtIterArg(RewriterBase &rewriter, LoopLikeOpInterface loopLike, BlockArgument iterArg)
Hoist all subset ops that operate on the idx-th region iter_arg of the given loop-like op and index i...
static size_t hoistFromNestedRegions(Region &region, LoopLikeOpInterface loopLike, bool isNested)
Hoists pure loop-invariant ops out of the control-flow regions nested in region, which is part of the...
static bool canBeHoisted(Operation *op, function_ref< bool(OpOperand &)> condition)
Checks whether the given op can be hoisted by checking that.
static bool canBeHoisted(Operation *op, function_ref< bool(Value)> definedOutside)
Helper to know if an op can be hoisted out of the region.
This class represents an argument of a Block.
Definition Value.h:308
Block * getOwner() const
Returns the block that owns this argument.
Definition Value.h:317
Block represents an ordered list of Operations.
Definition Block.h:34
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
IRValueT get() const
Return the current value being used by this operand.
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:210
This class represents an operand of an operation.
Definition Value.h:256
Set of flags used to control the behavior of the various IR print methods (e.g.
This is a value defined by a result of an operation.
Definition Value.h:456
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
void moveOpBefore(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
void moveOpAfter(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right after existingOp which may be in the...
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
LoopLikeOpInterface hoistLoopInvariantSubsets(RewriterBase &rewriter, LoopLikeOpInterface loopLike)
Hoist loop-invariant tensor subsets (subset extraction and subset insertion ops) from loop-like ops.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
size_t moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike)
Move loop invariant code out of the control-flow regions nested in the body of a loop-like op,...
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
size_t moveLoopInvariantCode(ArrayRef< Region * > regions, function_ref< bool(Value, Region *)> isDefinedOutsideRegion, function_ref< bool(Operation *, Region *)> shouldMoveOutOfRegion, function_ref< void(Operation *, Region *)> moveOutOfRegion)
Given a list of regions, perform loop-invariant code motion.