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