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