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
13 #include "PassDetail.h"
14 #include "mlir/Analysis/AffineAnalysis.h"
15 #include "mlir/Analysis/AffineStructures.h"
16 #include "mlir/Analysis/LoopAnalysis.h"
17 #include "mlir/Analysis/SliceAnalysis.h"
18 #include "mlir/Analysis/Utils.h"
19 #include "mlir/Dialect/Affine/IR/AffineOps.h"
20 #include "mlir/Dialect/Affine/Passes.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/AffineMap.h"
23 #include "mlir/IR/Builders.h"
24 #include "mlir/Transforms/LoopUtils.h"
25 #include "mlir/Transforms/Utils.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32
33 #define DEBUG_TYPE "licm"
34
35 using namespace mlir;
36
37 namespace {
38
39 /// Loop invariant code motion (LICM) pass.
40 /// TODO: The pass is missing zero-trip tests.
41 /// TODO: Check for the presence of side effects before hoisting.
42 /// TODO: This code should be removed once the new LICM pass can handle its
43 /// uses.
44 struct LoopInvariantCodeMotion
45 : public AffineLoopInvariantCodeMotionBase<LoopInvariantCodeMotion> {
46 void runOnFunction() override;
47 void runOnAffineForOp(AffineForOp forOp);
48 };
49 } // end anonymous namespace
50
51 static bool
52 checkInvarianceOfNestedIfOps(Operation *op, Value indVar, ValueRange iterArgs,
53 SmallPtrSetImpl<Operation *> &opsWithUsers,
54 SmallPtrSetImpl<Operation *> &opsToHoist);
55 static bool isOpLoopInvariant(Operation &op, Value indVar, ValueRange iterArgs,
56 SmallPtrSetImpl<Operation *> &opsWithUsers,
57 SmallPtrSetImpl<Operation *> &opsToHoist);
58
59 static bool
60 areAllOpsInTheBlockListInvariant(Region &blockList, Value indVar,
61 ValueRange iterArgs,
62 SmallPtrSetImpl<Operation *> &opsWithUsers,
63 SmallPtrSetImpl<Operation *> &opsToHoist);
64
65 // Returns true if the individual op is loop invariant.
isOpLoopInvariant(Operation & op,Value indVar,ValueRange iterArgs,SmallPtrSetImpl<Operation * > & opsWithUsers,SmallPtrSetImpl<Operation * > & opsToHoist)66 bool isOpLoopInvariant(Operation &op, Value indVar, ValueRange iterArgs,
67 SmallPtrSetImpl<Operation *> &opsWithUsers,
68 SmallPtrSetImpl<Operation *> &opsToHoist) {
69 LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;);
70
71 if (isa<AffineIfOp>(op)) {
72 if (!checkInvarianceOfNestedIfOps(&op, indVar, iterArgs, opsWithUsers,
73 opsToHoist)) {
74 return false;
75 }
76 } else if (auto forOp = dyn_cast<AffineForOp>(op)) {
77 if (!areAllOpsInTheBlockListInvariant(forOp.getLoopBody(), indVar, iterArgs,
78 opsWithUsers, opsToHoist)) {
79 return false;
80 }
81 } else if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
82 // TODO: Support DMA ops.
83 return false;
84 } else if (!isa<ConstantOp>(op)) {
85 // Register op in the set of ops that have users.
86 opsWithUsers.insert(&op);
87 if (isa<AffineMapAccessInterface>(op)) {
88 Value memref = isa<AffineReadOpInterface>(op)
89 ? cast<AffineReadOpInterface>(op).getMemRef()
90 : cast<AffineWriteOpInterface>(op).getMemRef();
91 for (auto *user : memref.getUsers()) {
92 // If this memref has a user that is a DMA, give up because these
93 // operations write to this memref.
94 if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
95 return false;
96 }
97 // If the memref used by the load/store is used in a store elsewhere in
98 // the loop nest, we do not hoist. Similarly, if the memref used in a
99 // load is also being stored too, we do not hoist the load.
100 if (isa<AffineWriteOpInterface>(user) ||
101 (isa<AffineReadOpInterface>(user) &&
102 isa<AffineWriteOpInterface>(op))) {
103 if (&op != user) {
104 SmallVector<AffineForOp, 8> userIVs;
105 getLoopIVs(*user, &userIVs);
106 // Check that userIVs don't contain the for loop around the op.
107 if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) {
108 return false;
109 }
110 }
111 }
112 }
113 }
114
115 if (op.getNumOperands() == 0 && !isa<AffineYieldOp>(op)) {
116 LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n");
117 return false;
118 }
119 }
120
121 // Check operands.
122 for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
123 auto *operandSrc = op.getOperand(i).getDefiningOp();
124
125 LLVM_DEBUG(
126 op.getOperand(i).print(llvm::dbgs() << "\nIterating on operand\n"));
127
128 // If the loop IV is the operand, this op isn't loop invariant.
129 if (indVar == op.getOperand(i)) {
130 LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
131 return false;
132 }
133
134 // If the one of the iter_args is the operand, this op isn't loop invariant.
135 if (llvm::is_contained(iterArgs, op.getOperand(i))) {
136 LLVM_DEBUG(llvm::dbgs() << "\nOne of the iter_args is the operand\n");
137 return false;
138 }
139
140 if (operandSrc != nullptr) {
141 LLVM_DEBUG(llvm::dbgs() << *operandSrc << "\nIterating on operand src\n");
142
143 // If the value was defined in the loop (outside of the
144 // if/else region), and that operation itself wasn't meant to
145 // be hoisted, then mark this operation loop dependent.
146 if (opsWithUsers.count(operandSrc) && opsToHoist.count(operandSrc) == 0) {
147 return false;
148 }
149 }
150 }
151
152 // If no operand was loop variant, mark this op for motion.
153 opsToHoist.insert(&op);
154 return true;
155 }
156
157 // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
areAllOpsInTheBlockListInvariant(Region & blockList,Value indVar,ValueRange iterArgs,SmallPtrSetImpl<Operation * > & opsWithUsers,SmallPtrSetImpl<Operation * > & opsToHoist)158 bool areAllOpsInTheBlockListInvariant(
159 Region &blockList, Value indVar, ValueRange iterArgs,
160 SmallPtrSetImpl<Operation *> &opsWithUsers,
161 SmallPtrSetImpl<Operation *> &opsToHoist) {
162
163 for (auto &b : blockList) {
164 for (auto &op : b) {
165 if (!isOpLoopInvariant(op, indVar, iterArgs, opsWithUsers, opsToHoist)) {
166 return false;
167 }
168 }
169 }
170
171 return true;
172 }
173
174 // Returns true if the affine.if op can be hoisted.
checkInvarianceOfNestedIfOps(Operation * op,Value indVar,ValueRange iterArgs,SmallPtrSetImpl<Operation * > & opsWithUsers,SmallPtrSetImpl<Operation * > & opsToHoist)175 bool checkInvarianceOfNestedIfOps(Operation *op, Value indVar,
176 ValueRange iterArgs,
177 SmallPtrSetImpl<Operation *> &opsWithUsers,
178 SmallPtrSetImpl<Operation *> &opsToHoist) {
179 assert(isa<AffineIfOp>(op));
180 auto ifOp = cast<AffineIfOp>(op);
181
182 if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, iterArgs,
183 opsWithUsers, opsToHoist)) {
184 return false;
185 }
186
187 if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, iterArgs,
188 opsWithUsers, opsToHoist)) {
189 return false;
190 }
191
192 return true;
193 }
194
runOnAffineForOp(AffineForOp forOp)195 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
196 auto *loopBody = forOp.getBody();
197 auto indVar = forOp.getInductionVar();
198 ValueRange iterArgs = forOp.getIterOperands();
199
200 // This is the place where hoisted instructions would reside.
201 OpBuilder b(forOp.getOperation());
202
203 SmallPtrSet<Operation *, 8> opsToHoist;
204 SmallVector<Operation *, 8> opsToMove;
205 SmallPtrSet<Operation *, 8> opsWithUsers;
206
207 for (auto &op : *loopBody) {
208 // Register op in the set of ops that have users. This set is used
209 // to prevent hoisting ops that depend on these ops that are
210 // not being hoisted.
211 if (!op.use_empty())
212 opsWithUsers.insert(&op);
213 if (!isa<AffineYieldOp>(op)) {
214 if (isOpLoopInvariant(op, indVar, iterArgs, opsWithUsers, opsToHoist)) {
215 opsToMove.push_back(&op);
216 }
217 }
218 }
219
220 // For all instructions that we found to be invariant, place sequentially
221 // right before the for loop.
222 for (auto *op : opsToMove) {
223 op->moveBefore(forOp);
224 }
225
226 LLVM_DEBUG(forOp->print(llvm::dbgs() << "Modified loop\n"));
227 }
228
runOnFunction()229 void LoopInvariantCodeMotion::runOnFunction() {
230 // Walk through all loops in a function in innermost-loop-first order. This
231 // way, we first LICM from the inner loop, and place the ops in
232 // the outer loop, which in turn can be further LICM'ed.
233 getFunction().walk([&](AffineForOp op) {
234 LLVM_DEBUG(op->print(llvm::dbgs() << "\nOriginal loop\n"));
235 runOnAffineForOp(op);
236 });
237 }
238
239 std::unique_ptr<OperationPass<FuncOp>>
createAffineLoopInvariantCodeMotionPass()240 mlir::createAffineLoopInvariantCodeMotionPass() {
241 return std::make_unique<LoopInvariantCodeMotion>();
242 }
243