1 //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===// 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 mlir::applyPatternsAndFoldGreedily. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 14 #include "mlir/Interfaces/SideEffectInterfaces.h" 15 #include "mlir/Rewrite/PatternApplicator.h" 16 #include "mlir/Transforms/FoldUtils.h" 17 #include "mlir/Transforms/RegionUtils.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 23 using namespace mlir; 24 25 #define DEBUG_TYPE "pattern-matcher" 26 27 /// The max number of iterations scanning for pattern match. 28 static unsigned maxPatternMatchIterations = 10; 29 30 //===----------------------------------------------------------------------===// 31 // GreedyPatternRewriteDriver 32 //===----------------------------------------------------------------------===// 33 34 namespace { 35 /// This is a worklist-driven driver for the PatternMatcher, which repeatedly 36 /// applies the locally optimal patterns in a roughly "bottom up" way. 37 class GreedyPatternRewriteDriver : public PatternRewriter { 38 public: 39 explicit GreedyPatternRewriteDriver(MLIRContext *ctx, 40 const FrozenRewritePatternList &patterns) 41 : PatternRewriter(ctx), matcher(patterns), folder(ctx) { 42 worklist.reserve(64); 43 44 // Apply a simple cost model based solely on pattern benefit. 45 matcher.applyDefaultCostModel(); 46 } 47 48 bool simplify(MutableArrayRef<Region> regions, int maxIterations); 49 50 void addToWorklist(Operation *op) { 51 // Check to see if the worklist already contains this op. 52 if (worklistMap.count(op)) 53 return; 54 55 worklistMap[op] = worklist.size(); 56 worklist.push_back(op); 57 } 58 59 Operation *popFromWorklist() { 60 auto *op = worklist.back(); 61 worklist.pop_back(); 62 63 // This operation is no longer in the worklist, keep worklistMap up to date. 64 if (op) 65 worklistMap.erase(op); 66 return op; 67 } 68 69 /// If the specified operation is in the worklist, remove it. If not, this is 70 /// a no-op. 71 void removeFromWorklist(Operation *op) { 72 auto it = worklistMap.find(op); 73 if (it != worklistMap.end()) { 74 assert(worklist[it->second] == op && "malformed worklist data structure"); 75 worklist[it->second] = nullptr; 76 worklistMap.erase(it); 77 } 78 } 79 80 // These are hooks implemented for PatternRewriter. 81 protected: 82 // Implement the hook for inserting operations, and make sure that newly 83 // inserted ops are added to the worklist for processing. 84 void notifyOperationInserted(Operation *op) override { addToWorklist(op); } 85 86 // If an operation is about to be removed, make sure it is not in our 87 // worklist anymore because we'd get dangling references to it. 88 void notifyOperationRemoved(Operation *op) override { 89 addToWorklist(op->getOperands()); 90 op->walk([this](Operation *operation) { 91 removeFromWorklist(operation); 92 folder.notifyRemoval(operation); 93 }); 94 } 95 96 // When the root of a pattern is about to be replaced, it can trigger 97 // simplifications to its users - make sure to add them to the worklist 98 // before the root is changed. 99 void notifyRootReplaced(Operation *op) override { 100 for (auto result : op->getResults()) 101 for (auto *user : result.getUsers()) 102 addToWorklist(user); 103 } 104 105 private: 106 // Look over the provided operands for any defining operations that should 107 // be re-added to the worklist. This function should be called when an 108 // operation is modified or removed, as it may trigger further 109 // simplifications. 110 template <typename Operands> void addToWorklist(Operands &&operands) { 111 for (Value operand : operands) { 112 // If the use count of this operand is now < 2, we re-add the defining 113 // operation to the worklist. 114 // TODO: This is based on the fact that zero use operations 115 // may be deleted, and that single use values often have more 116 // canonicalization opportunities. 117 if (!operand.use_empty() && !operand.hasOneUse()) 118 continue; 119 if (auto *defInst = operand.getDefiningOp()) 120 addToWorklist(defInst); 121 } 122 } 123 124 /// The low-level pattern applicator. 125 PatternApplicator matcher; 126 127 /// The worklist for this transformation keeps track of the operations that 128 /// need to be revisited, plus their index in the worklist. This allows us to 129 /// efficiently remove operations from the worklist when they are erased, even 130 /// if they aren't the root of a pattern. 131 std::vector<Operation *> worklist; 132 DenseMap<Operation *, unsigned> worklistMap; 133 134 /// Non-pattern based folder for operations. 135 OperationFolder folder; 136 }; 137 } // end anonymous namespace 138 139 /// Performs the rewrites while folding and erasing any dead ops. Returns true 140 /// if the rewrite converges in `maxIterations`. 141 bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions, 142 int maxIterations) { 143 // Add the given operation to the worklist. 144 auto collectOps = [this](Operation *op) { addToWorklist(op); }; 145 146 bool changed = false; 147 int i = 0; 148 do { 149 // Add all nested operations to the worklist. 150 for (auto ®ion : regions) 151 region.walk(collectOps); 152 153 // These are scratch vectors used in the folding loop below. 154 SmallVector<Value, 8> originalOperands, resultValues; 155 156 changed = false; 157 while (!worklist.empty()) { 158 auto *op = popFromWorklist(); 159 160 // Nulls get added to the worklist when operations are removed, ignore 161 // them. 162 if (op == nullptr) 163 continue; 164 165 // If the operation is trivially dead - remove it. 166 if (isOpTriviallyDead(op)) { 167 notifyOperationRemoved(op); 168 op->erase(); 169 changed = true; 170 continue; 171 } 172 173 // Collects all the operands and result uses of the given `op` into work 174 // list. Also remove `op` and nested ops from worklist. 175 originalOperands.assign(op->operand_begin(), op->operand_end()); 176 auto preReplaceAction = [&](Operation *op) { 177 // Add the operands to the worklist for visitation. 178 addToWorklist(originalOperands); 179 180 // Add all the users of the result to the worklist so we make sure 181 // to revisit them. 182 for (auto result : op->getResults()) 183 for (auto *userOp : result.getUsers()) 184 addToWorklist(userOp); 185 186 notifyOperationRemoved(op); 187 }; 188 189 // Try to fold this op. 190 bool inPlaceUpdate; 191 if ((succeeded(folder.tryToFold(op, collectOps, preReplaceAction, 192 &inPlaceUpdate)))) { 193 changed = true; 194 if (!inPlaceUpdate) 195 continue; 196 } 197 198 // Try to match one of the patterns. The rewriter is automatically 199 // notified of any necessary changes, so there is nothing else to do here. 200 changed |= succeeded(matcher.matchAndRewrite(op, *this)); 201 } 202 203 // After applying patterns, make sure that the CFG of each of the regions is 204 // kept up to date. 205 if (succeeded(simplifyRegions(regions))) { 206 folder.clear(); 207 changed = true; 208 } 209 } while (changed && ++i < maxIterations); 210 // Whether the rewrite converges, i.e. wasn't changed in the last iteration. 211 return !changed; 212 } 213 214 /// Rewrite the regions of the specified operation, which must be isolated from 215 /// above, by repeatedly applying the highest benefit patterns in a greedy 216 /// work-list driven manner. Return success if no more patterns can be matched 217 /// in the result operation regions. Note: This does not apply patterns to the 218 /// top-level operation itself. 219 /// 220 LogicalResult 221 mlir::applyPatternsAndFoldGreedily(Operation *op, 222 const FrozenRewritePatternList &patterns) { 223 return applyPatternsAndFoldGreedily(op->getRegions(), patterns); 224 } 225 /// Rewrite the given regions, which must be isolated from above. 226 LogicalResult 227 mlir::applyPatternsAndFoldGreedily(MutableArrayRef<Region> regions, 228 const FrozenRewritePatternList &patterns) { 229 if (regions.empty()) 230 return success(); 231 232 // The top-level operation must be known to be isolated from above to 233 // prevent performing canonicalizations on operations defined at or above 234 // the region containing 'op'. 235 auto regionIsIsolated = [](Region ®ion) { 236 return region.getParentOp()->isKnownIsolatedFromAbove(); 237 }; 238 (void)regionIsIsolated; 239 assert(llvm::all_of(regions, regionIsIsolated) && 240 "patterns can only be applied to operations IsolatedFromAbove"); 241 242 // Start the pattern driver. 243 GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns); 244 bool converged = driver.simplify(regions, maxPatternMatchIterations); 245 LLVM_DEBUG(if (!converged) { 246 llvm::dbgs() << "The pattern rewrite doesn't converge after scanning " 247 << maxPatternMatchIterations << " times"; 248 }); 249 return success(converged); 250 } 251 252 //===----------------------------------------------------------------------===// 253 // OpPatternRewriteDriver 254 //===----------------------------------------------------------------------===// 255 256 namespace { 257 /// This is a simple driver for the PatternMatcher to apply patterns and perform 258 /// folding on a single op. It repeatedly applies locally optimal patterns. 259 class OpPatternRewriteDriver : public PatternRewriter { 260 public: 261 explicit OpPatternRewriteDriver(MLIRContext *ctx, 262 const FrozenRewritePatternList &patterns) 263 : PatternRewriter(ctx), matcher(patterns), folder(ctx) { 264 // Apply a simple cost model based solely on pattern benefit. 265 matcher.applyDefaultCostModel(); 266 } 267 268 /// Performs the rewrites and folding only on `op`. The simplification 269 /// converges if the op is erased as a result of being folded, replaced, or 270 /// dead, or no more changes happen in an iteration. Returns success if the 271 /// rewrite converges in `maxIterations`. `erased` is set to true if `op` gets 272 /// erased. 273 LogicalResult simplifyLocally(Operation *op, int maxIterations, bool &erased); 274 275 // These are hooks implemented for PatternRewriter. 276 protected: 277 /// If an operation is about to be removed, mark it so that we can let clients 278 /// know. 279 void notifyOperationRemoved(Operation *op) override { 280 opErasedViaPatternRewrites = true; 281 } 282 283 // When a root is going to be replaced, its removal will be notified as well. 284 // So there is nothing to do here. 285 void notifyRootReplaced(Operation *op) override {} 286 287 private: 288 /// The low-level pattern applicator. 289 PatternApplicator matcher; 290 291 /// Non-pattern based folder for operations. 292 OperationFolder folder; 293 294 /// Set to true if the operation has been erased via pattern rewrites. 295 bool opErasedViaPatternRewrites = false; 296 }; 297 298 } // anonymous namespace 299 300 LogicalResult OpPatternRewriteDriver::simplifyLocally(Operation *op, 301 int maxIterations, 302 bool &erased) { 303 bool changed = false; 304 erased = false; 305 opErasedViaPatternRewrites = false; 306 int i = 0; 307 // Iterate until convergence or until maxIterations. Deletion of the op as 308 // a result of being dead or folded is convergence. 309 do { 310 changed = false; 311 312 // If the operation is trivially dead - remove it. 313 if (isOpTriviallyDead(op)) { 314 op->erase(); 315 erased = true; 316 return success(); 317 } 318 319 // Try to fold this op. 320 bool inPlaceUpdate; 321 if (succeeded(folder.tryToFold(op, /*processGeneratedConstants=*/nullptr, 322 /*preReplaceAction=*/nullptr, 323 &inPlaceUpdate))) { 324 changed = true; 325 if (!inPlaceUpdate) { 326 erased = true; 327 return success(); 328 } 329 } 330 331 // Try to match one of the patterns. The rewriter is automatically 332 // notified of any necessary changes, so there is nothing else to do here. 333 changed |= succeeded(matcher.matchAndRewrite(op, *this)); 334 if ((erased = opErasedViaPatternRewrites)) 335 return success(); 336 } while (changed && ++i < maxIterations); 337 338 // Whether the rewrite converges, i.e. wasn't changed in the last iteration. 339 return failure(changed); 340 } 341 342 /// Rewrites only `op` using the supplied canonicalization patterns and 343 /// folding. `erased` is set to true if the op is erased as a result of being 344 /// folded, replaced, or dead. 345 LogicalResult mlir::applyOpPatternsAndFold( 346 Operation *op, const FrozenRewritePatternList &patterns, bool *erased) { 347 // Start the pattern driver. 348 OpPatternRewriteDriver driver(op->getContext(), patterns); 349 bool opErased; 350 LogicalResult converged = 351 driver.simplifyLocally(op, maxPatternMatchIterations, opErased); 352 if (erased) 353 *erased = opErased; 354 LLVM_DEBUG(if (failed(converged)) { 355 llvm::dbgs() << "The pattern rewrite doesn't converge after scanning " 356 << maxPatternMatchIterations << " times"; 357 }); 358 return converged; 359 } 360