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