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