MLIR 24.0.0git
AffineLoopInvariantCodeMotion.cpp
Go to the documentation of this file.
1//===- AffineLoopInvariantCodeMotion.cpp - Code to perform loop fusion-----===//
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 implements loop invariant code motion.
10//
11//===----------------------------------------------------------------------===//
12
14
20
21namespace mlir {
22namespace affine {
23#define GEN_PASS_DEF_AFFINELOOPINVARIANTCODEMOTION
24#include "mlir/Dialect/Affine/Transforms/Passes.h.inc"
25} // namespace affine
26} // namespace mlir
27
28#define DEBUG_TYPE "affine-licm"
29
30using namespace mlir;
31using namespace mlir::affine;
32
33namespace {
34
35/// Affine loop invariant code motion (LICM) pass.
36/// TODO: When compared to the other standard LICM pass, this pass
37/// has some special handling for affine read/write ops but such handling
38/// requires aliasing to be sound, and as such this pass is unsound. In
39/// addition, this handling is nothing particular to affine memory ops but would
40/// apply to any memory read/write effect ops. Either aliasing should be handled
41/// or this pass can be removed and the standard LICM can be used.
42struct LoopInvariantCodeMotion
44 LoopInvariantCodeMotion> {
45 void runOnOperation() override;
46 void runOnAffineForOp(AffineForOp forOp);
47};
48} // namespace
49
50static bool
51checkInvarianceOfNestedIfOps(AffineIfOp ifOp, AffineForOp loop,
52 SmallPtrSetImpl<Operation *> &opsWithUsers,
54static bool isOpLoopInvariant(Operation &op, AffineForOp loop,
55 SmallPtrSetImpl<Operation *> &opsWithUsers,
57
58static bool
59areAllOpsInTheBlockListInvariant(Region &blockList, AffineForOp loop,
60 SmallPtrSetImpl<Operation *> &opsWithUsers,
62
63/// Returns true if `op` is invariant on `loop`.
64static bool isOpLoopInvariant(Operation &op, AffineForOp loop,
65 SmallPtrSetImpl<Operation *> &opsWithUsers,
66 SmallPtrSetImpl<Operation *> &opsToHoist) {
67 Value iv = loop.getInductionVar();
68
69 if (auto ifOp = dyn_cast<AffineIfOp>(op)) {
70 if (!checkInvarianceOfNestedIfOps(ifOp, loop, opsWithUsers, opsToHoist))
71 return false;
72 } else if (auto forOp = dyn_cast<AffineForOp>(op)) {
73 if (!areAllOpsInTheBlockListInvariant(forOp.getRegion(), loop, opsWithUsers,
74 opsToHoist))
75 return false;
76 } else if (auto parOp = dyn_cast<AffineParallelOp>(op)) {
77 if (!areAllOpsInTheBlockListInvariant(parOp.getRegion(), loop, opsWithUsers,
78 opsToHoist))
79 return false;
80 } else if (!isMemoryEffectFree(&op) &&
81 !isa<AffineReadOpInterface, AffineWriteOpInterface>(&op)) {
82 // Check for side-effecting ops. Affine read/write ops are handled
83 // separately below.
84 return false;
85 } else if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op)) {
86 // Register op in the set of ops that have users.
87 opsWithUsers.insert(&op);
89 auto read = dyn_cast<AffineReadOpInterface>(op);
91 read ? read.getMemRef() : cast<AffineWriteOpInterface>(op).getMemRef();
92 for (auto *user : memref.getUsers()) {
93 // If the memref used by the load/store is used in a store elsewhere in
94 // the loop nest, we do not hoist. Similarly, if the memref used in a
95 // load is also being stored too, we do not hoist the load.
96 // FIXME: This is missing checking aliases.
97 if (&op == user)
98 continue;
101 isa<AffineWriteOpInterface>(op))) {
102 userIVs.clear();
103 getAffineForIVs(*user, &userIVs);
104 // Check that userIVs don't contain the for loop around the op.
105 if (llvm::is_contained(userIVs, loop))
106 return false;
107 }
108 }
109 }
110
111 // Check operands.
112 ValueRange iterArgs = loop.getRegionIterArgs();
113 for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
114 auto *operandSrc = op.getOperand(i).getDefiningOp();
115
116 // If the loop IV is the operand, this op isn't loop invariant.
117 if (iv == op.getOperand(i))
118 return false;
119
120 // If the one of the iter_args is the operand, this op isn't loop invariant.
121 if (llvm::is_contained(iterArgs, op.getOperand(i)))
122 return false;
123
124 if (operandSrc) {
125 // If the value was defined in the loop (outside of the if/else region),
126 // and that operation itself wasn't meant to be hoisted, then mark this
127 // operation loop dependent.
128 if (opsWithUsers.count(operandSrc) && opsToHoist.count(operandSrc) == 0)
129 return false;
130 }
131 }
132
133 // If no operand was loop variant, mark this op for motion.
134 opsToHoist.insert(&op);
135 return true;
136}
137
138// Checks if all ops in a region (i.e. list of blocks) are loop invariant.
139static bool
140areAllOpsInTheBlockListInvariant(Region &blockList, AffineForOp loop,
141 SmallPtrSetImpl<Operation *> &opsWithUsers,
142 SmallPtrSetImpl<Operation *> &opsToHoist) {
143
144 for (auto &b : blockList) {
145 for (auto &op : b) {
146 if (!isOpLoopInvariant(op, loop, opsWithUsers, opsToHoist))
147 return false;
148 }
149 }
150
151 return true;
152}
153
154// Returns true if the affine.if op can be hoisted.
155static bool
156checkInvarianceOfNestedIfOps(AffineIfOp ifOp, AffineForOp loop,
157 SmallPtrSetImpl<Operation *> &opsWithUsers,
158 SmallPtrSetImpl<Operation *> &opsToHoist) {
159 if (!areAllOpsInTheBlockListInvariant(ifOp.getThenRegion(), loop,
160 opsWithUsers, opsToHoist))
161 return false;
162
163 if (!areAllOpsInTheBlockListInvariant(ifOp.getElseRegion(), loop,
164 opsWithUsers, opsToHoist))
165 return false;
166
167 return true;
168}
169
170void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
171 // This is the place where hoisted instructions would reside.
172 OpBuilder b(forOp.getOperation());
173
174 SmallPtrSet<Operation *, 8> opsToHoist;
175 SmallVector<Operation *, 8> opsToMove;
176 SmallPtrSet<Operation *, 8> opsWithUsers;
177
178 // Only hoist side-effectful ops when the loop is statically known to execute
179 // at least once. For unknown (dynamic) or zero trip counts we cannot prove
180 // the body executes, so hoisting a side-effectful op would change observable
181 // program semantics. Pure (side-effect-free) ops may always be hoisted.
182 auto tripCount = forOp.getStaticTripCount();
183 bool guaranteedToExecute =
184 tripCount.has_value() && tripCount->getZExtValue() > 0;
185
186 for (Operation &op : *forOp.getBody()) {
187 // Register op in the set of ops that have users. This set is used
188 // to prevent hoisting ops that depend on these ops that are
189 // not being hoisted.
190 if (!op.use_empty())
191 opsWithUsers.insert(&op);
192 if (!isa<AffineYieldOp>(op)) {
193 // Do not hoist ops with side effects unless the loop is guaranteed to
194 // execute at least once.
195 if (!guaranteedToExecute && !isPure(&op))
196 continue;
197 if (isOpLoopInvariant(op, forOp, opsWithUsers, opsToHoist)) {
198 opsToMove.push_back(&op);
199 }
200 }
201 }
202
203 // For all instructions that we found to be invariant, place sequentially
204 // right before the for loop.
205 for (auto *op : opsToMove) {
206 op->moveBefore(forOp);
207 }
208
209 // Hoist invariant ops nested in control-flow ops that stay in the loop.
211}
212
213void LoopInvariantCodeMotion::runOnOperation() {
214 // Walk through all loops in a function in innermost-loop-first order. This
215 // way, we first LICM from the inner loop, and place the ops in
216 // the outer loop, which in turn can be further LICM'ed.
217 getOperation().walk([&](AffineForOp op) { runOnAffineForOp(op); });
218}
219
220std::unique_ptr<OperationPass<func::FuncOp>>
222 return std::make_unique<LoopInvariantCodeMotion>();
223}
static bool isOpLoopInvariant(Operation &op, AffineForOp loop, SmallPtrSetImpl< Operation * > &opsWithUsers, SmallPtrSetImpl< Operation * > &opsToHoist)
Returns true if op is invariant on loop.
static bool areAllOpsInTheBlockListInvariant(Region &blockList, AffineForOp loop, SmallPtrSetImpl< Operation * > &opsWithUsers, SmallPtrSetImpl< Operation * > &opsToHoist)
static bool checkInvarianceOfNestedIfOps(AffineIfOp ifOp, AffineForOp loop, SmallPtrSetImpl< Operation * > &opsWithUsers, SmallPtrSetImpl< Operation * > &opsToHoist)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
unsigned getNumOperands()
Definition Operation.h:373
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 provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
std::unique_ptr< OperationPass< func::FuncOp > > createAffineLoopInvariantCodeMotionPass()
Creates a loop invariant code motion pass that hoists loop invariant operations out of affine loops.
void getAffineForIVs(Operation &op, SmallVectorImpl< AffineForOp > *loops)
Populates 'loops' with IVs of the affine.for ops surrounding 'op' ordered from the outermost 'affine....
Definition Utils.cpp:866
Include the generated interface declarations.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
size_t moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike)
Move loop invariant code out of the control-flow regions nested in the body of a loop-like op,...
bool mightHaveEffect(Operation *op)
Returns "true" if op might have an effect of type EffectTy.