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 *> &definedOps,
54                              SmallPtrSetImpl<Operation *> &opsToHoist);
55 static bool isOpLoopInvariant(Operation &op, Value indVar,
56                               SmallPtrSetImpl<Operation *> &definedOps,
57                               SmallPtrSetImpl<Operation *> &opsToHoist);
58 
59 static bool
60 areAllOpsInTheBlockListInvariant(Region &blockList, Value indVar,
61                                  SmallPtrSetImpl<Operation *> &definedOps,
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 *> &definedOps,
67                        SmallPtrSetImpl<Operation *> &opsToHoist) {
68   LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;);
69 
70   if (isa<AffineIfOp>(op)) {
71     if (!checkInvarianceOfNestedIfOps(&op, indVar, definedOps, 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 defined inside the loop. This set is used
83     // to prevent hoisting ops that depend on other ops defined inside the loop
84     // which are themselves not being hoisted.
85     definedOps.insert(&op);
86 
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     for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
120       auto *operandSrc = op.getOperand(i).getDefiningOp();
121 
122       LLVM_DEBUG(
123           op.getOperand(i).print(llvm::dbgs() << "\nIterating on operand\n"));
124 
125       // If the loop IV is the operand, this op isn't loop invariant.
126       if (indVar == op.getOperand(i)) {
127         LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
128         return false;
129       }
130 
131       if (operandSrc != nullptr) {
132         LLVM_DEBUG(llvm::dbgs()
133                    << *operandSrc << "\nIterating on operand src\n");
134 
135         // If the value was defined in the loop (outside of the
136         // if/else region), and that operation itself wasn't meant to
137         // be hoisted, then mark this operation loop dependent.
138         if (definedOps.count(operandSrc) && opsToHoist.count(operandSrc) == 0) {
139           return false;
140         }
141       }
142     }
143   }
144 
145   // If no operand was loop variant, mark this op for motion.
146   opsToHoist.insert(&op);
147   return true;
148 }
149 
150 // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
151 bool areAllOpsInTheBlockListInvariant(
152     Region &blockList, Value indVar, SmallPtrSetImpl<Operation *> &definedOps,
153     SmallPtrSetImpl<Operation *> &opsToHoist) {
154 
155   for (auto &b : blockList) {
156     for (auto &op : b) {
157       if (!isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
158         return false;
159       }
160     }
161   }
162 
163   return true;
164 }
165 
166 // Returns true if the affine.if op can be hoisted.
167 bool checkInvarianceOfNestedIfOps(Operation *op, Value indVar,
168                                   SmallPtrSetImpl<Operation *> &definedOps,
169                                   SmallPtrSetImpl<Operation *> &opsToHoist) {
170   assert(isa<AffineIfOp>(op));
171   auto ifOp = cast<AffineIfOp>(op);
172 
173   if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, definedOps,
174                                         opsToHoist)) {
175     return false;
176   }
177 
178   if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, definedOps,
179                                         opsToHoist)) {
180     return false;
181   }
182 
183   return true;
184 }
185 
186 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
187   auto *loopBody = forOp.getBody();
188   auto indVar = forOp.getInductionVar();
189 
190   SmallPtrSet<Operation *, 8> definedOps;
191   // This is the place where hoisted instructions would reside.
192   OpBuilder b(forOp.getOperation());
193 
194   SmallPtrSet<Operation *, 8> opsToHoist;
195   SmallVector<Operation *, 8> opsToMove;
196 
197   for (auto &op : *loopBody) {
198     // We don't hoist for loops.
199     if (!isa<AffineForOp>(op)) {
200       if (!isa<AffineYieldOp>(op)) {
201         if (isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
202           opsToMove.push_back(&op);
203         }
204       }
205     }
206   }
207 
208   // For all instructions that we found to be invariant, place sequentially
209   // right before the for loop.
210   for (auto *op : opsToMove) {
211     op->moveBefore(forOp);
212   }
213 
214   LLVM_DEBUG(forOp->print(llvm::dbgs() << "Modified loop\n"));
215 }
216 
217 void LoopInvariantCodeMotion::runOnFunction() {
218   // Walk through all loops in a function in innermost-loop-first order.  This
219   // way, we first LICM from the inner loop, and place the ops in
220   // the outer loop, which in turn can be further LICM'ed.
221   getFunction().walk([&](AffineForOp op) {
222     LLVM_DEBUG(op->print(llvm::dbgs() << "\nOriginal loop\n"));
223     runOnAffineForOp(op);
224   });
225 }
226 
227 std::unique_ptr<OperationPass<FuncOp>>
228 mlir::createAffineLoopInvariantCodeMotionPass() {
229   return std::make_unique<LoopInvariantCodeMotion>();
230 }
231