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,
53                              SmallPtrSetImpl<Operation *> &opsWithUsers,
54                              SmallPtrSetImpl<Operation *> &opsToHoist);
55 static bool isOpLoopInvariant(Operation &op, Value indVar,
56                               SmallPtrSetImpl<Operation *> &opsWithUsers,
57                               SmallPtrSetImpl<Operation *> &opsToHoist);
58 
59 static bool
60 areAllOpsInTheBlockListInvariant(Region &blockList, Value indVar,
61                                  SmallPtrSetImpl<Operation *> &opsWithUsers,
62                                  SmallPtrSetImpl<Operation *> &opsToHoist);
63 
64 // Returns true if the individual op is loop invariant.
65 bool isOpLoopInvariant(Operation &op, Value indVar,
66                        SmallPtrSetImpl<Operation *> &opsWithUsers,
67                        SmallPtrSetImpl<Operation *> &opsToHoist) {
68   LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;);
69 
70   if (isa<AffineIfOp>(op)) {
71     if (!checkInvarianceOfNestedIfOps(&op, indVar, opsWithUsers, opsToHoist)) {
72       return false;
73     }
74   } else if (isa<AffineForOp>(op)) {
75     // If the body of a predicated region has a for loop, we don't hoist the
76     // 'affine.if'.
77     return false;
78   } else if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
79     // TODO: Support DMA ops.
80     return false;
81   } else if (!isa<ConstantOp>(op)) {
82     // Register op in the set of ops that have users.
83     opsWithUsers.insert(&op);
84     if (isa<AffineMapAccessInterface>(op)) {
85       Value memref = isa<AffineReadOpInterface>(op)
86                          ? cast<AffineReadOpInterface>(op).getMemRef()
87                          : cast<AffineWriteOpInterface>(op).getMemRef();
88       for (auto *user : memref.getUsers()) {
89         // If this memref has a user that is a DMA, give up because these
90         // operations write to this memref.
91         if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
92           return false;
93         }
94         // If the memref used by the load/store is used in a store elsewhere in
95         // the loop nest, we do not hoist. Similarly, if the memref used in a
96         // load is also being stored too, we do not hoist the load.
97         if (isa<AffineWriteOpInterface>(user) ||
98             (isa<AffineReadOpInterface>(user) &&
99              isa<AffineWriteOpInterface>(op))) {
100           if (&op != user) {
101             SmallVector<AffineForOp, 8> userIVs;
102             getLoopIVs(*user, &userIVs);
103             // Check that userIVs don't contain the for loop around the op.
104             if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) {
105               return false;
106             }
107           }
108         }
109       }
110     }
111 
112     if (op.getNumOperands() == 0 && !isa<AffineYieldOp>(op)) {
113       LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n");
114       return false;
115     }
116     for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
117       auto *operandSrc = op.getOperand(i).getDefiningOp();
118 
119       LLVM_DEBUG(
120           op.getOperand(i).print(llvm::dbgs() << "\nIterating on operand\n"));
121 
122       // If the loop IV is the operand, this op isn't loop invariant.
123       if (indVar == op.getOperand(i)) {
124         LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
125         return false;
126       }
127 
128       if (operandSrc != nullptr) {
129         LLVM_DEBUG(llvm::dbgs()
130                    << *operandSrc << "\nIterating on operand src\n");
131 
132         // If the value was defined in the loop (outside of the
133         // if/else region), and that operation itself wasn't meant to
134         // be hoisted, then mark this operation loop dependent.
135         if (opsWithUsers.count(operandSrc) &&
136             opsToHoist.count(operandSrc) == 0) {
137           return false;
138         }
139       }
140     }
141   }
142 
143   // If no operand was loop variant, mark this op for motion.
144   opsToHoist.insert(&op);
145   return true;
146 }
147 
148 // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
149 bool areAllOpsInTheBlockListInvariant(
150     Region &blockList, Value indVar, SmallPtrSetImpl<Operation *> &opsWithUsers,
151     SmallPtrSetImpl<Operation *> &opsToHoist) {
152 
153   for (auto &b : blockList) {
154     for (auto &op : b) {
155       if (!isOpLoopInvariant(op, indVar, opsWithUsers, opsToHoist)) {
156         return false;
157       }
158     }
159   }
160 
161   return true;
162 }
163 
164 // Returns true if the affine.if op can be hoisted.
165 bool checkInvarianceOfNestedIfOps(Operation *op, Value indVar,
166                                   SmallPtrSetImpl<Operation *> &opsWithUsers,
167                                   SmallPtrSetImpl<Operation *> &opsToHoist) {
168   assert(isa<AffineIfOp>(op));
169   auto ifOp = cast<AffineIfOp>(op);
170 
171   if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, opsWithUsers,
172                                         opsToHoist)) {
173     return false;
174   }
175 
176   if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, opsWithUsers,
177                                         opsToHoist)) {
178     return false;
179   }
180 
181   return true;
182 }
183 
184 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
185   auto *loopBody = forOp.getBody();
186   auto indVar = forOp.getInductionVar();
187 
188   // This is the place where hoisted instructions would reside.
189   OpBuilder b(forOp.getOperation());
190 
191   SmallPtrSet<Operation *, 8> opsToHoist;
192   SmallVector<Operation *, 8> opsToMove;
193   SmallPtrSet<Operation *, 8> opsWithUsers;
194 
195   for (auto &op : *loopBody) {
196     // Register op in the set of ops that have users. This set is used
197     // to prevent hoisting ops that depend on these ops that are
198     // not being hoisted.
199     if (!op.use_empty())
200       opsWithUsers.insert(&op);
201     // We don't hoist for loops.
202     if (!isa<AffineForOp>(op)) {
203       if (!isa<AffineYieldOp>(op)) {
204         if (isOpLoopInvariant(op, indVar, opsWithUsers, opsToHoist)) {
205           opsToMove.push_back(&op);
206         }
207       }
208     }
209   }
210 
211   // For all instructions that we found to be invariant, place sequentially
212   // right before the for loop.
213   for (auto *op : opsToMove) {
214     op->moveBefore(forOp);
215   }
216 
217   LLVM_DEBUG(forOp->print(llvm::dbgs() << "Modified loop\n"));
218 }
219 
220 void LoopInvariantCodeMotion::runOnFunction() {
221   // Walk through all loops in a function in innermost-loop-first order.  This
222   // way, we first LICM from the inner loop, and place the ops in
223   // the outer loop, which in turn can be further LICM'ed.
224   getFunction().walk([&](AffineForOp op) {
225     LLVM_DEBUG(op->print(llvm::dbgs() << "\nOriginal loop\n"));
226     runOnAffineForOp(op);
227   });
228 }
229 
230 std::unique_ptr<OperationPass<FuncOp>>
231 mlir::createAffineLoopInvariantCodeMotionPass() {
232   return std::make_unique<LoopInvariantCodeMotion>();
233 }
234