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/IR/PatternMatch.h" 14 #include "mlir/Interfaces/SideEffects.h" 15 #include "mlir/Transforms/FoldUtils.h" 16 #include "mlir/Transforms/RegionUtils.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/raw_ostream.h" 21 22 using namespace mlir; 23 24 #define DEBUG_TYPE "pattern-matcher" 25 26 /// The max number of iterations scanning for pattern match. 27 static unsigned maxPatternMatchIterations = 10; 28 29 //===----------------------------------------------------------------------===// 30 // GreedyPatternRewriteDriver 31 //===----------------------------------------------------------------------===// 32 33 namespace { 34 /// This is a worklist-driven driver for the PatternMatcher, which repeatedly 35 /// applies the locally optimal patterns in a roughly "bottom up" way. 36 class GreedyPatternRewriteDriver : public PatternRewriter { 37 public: 38 explicit GreedyPatternRewriteDriver(MLIRContext *ctx, 39 const OwningRewritePatternList &patterns) 40 : PatternRewriter(ctx), matcher(patterns), folder(ctx) { 41 worklist.reserve(64); 42 } 43 44 bool simplify(MutableArrayRef<Region> regions, int maxIterations); 45 46 void addToWorklist(Operation *op) { 47 // Check to see if the worklist already contains this op. 48 if (worklistMap.count(op)) 49 return; 50 51 worklistMap[op] = worklist.size(); 52 worklist.push_back(op); 53 } 54 55 Operation *popFromWorklist() { 56 auto *op = worklist.back(); 57 worklist.pop_back(); 58 59 // This operation is no longer in the worklist, keep worklistMap up to date. 60 if (op) 61 worklistMap.erase(op); 62 return op; 63 } 64 65 /// If the specified operation is in the worklist, remove it. If not, this is 66 /// a no-op. 67 void removeFromWorklist(Operation *op) { 68 auto it = worklistMap.find(op); 69 if (it != worklistMap.end()) { 70 assert(worklist[it->second] == op && "malformed worklist data structure"); 71 worklist[it->second] = nullptr; 72 worklistMap.erase(it); 73 } 74 } 75 76 // These are hooks implemented for PatternRewriter. 77 protected: 78 // Implement the hook for inserting operations, and make sure that newly 79 // inserted ops are added to the worklist for processing. 80 Operation *insert(Operation *op) override { 81 addToWorklist(op); 82 return OpBuilder::insert(op); 83 } 84 85 // If an operation is about to be removed, make sure it is not in our 86 // worklist anymore because we'd get dangling references to it. 87 void notifyOperationRemoved(Operation *op) override { 88 addToWorklist(op->getOperands()); 89 op->walk([this](Operation *operation) { 90 removeFromWorklist(operation); 91 folder.notifyRemoval(operation); 92 }); 93 } 94 95 // When the root of a pattern is about to be replaced, it can trigger 96 // simplifications to its users - make sure to add them to the worklist 97 // before the root is changed. 98 void notifyRootReplaced(Operation *op) override { 99 for (auto result : op->getResults()) 100 for (auto *user : result.getUsers()) 101 addToWorklist(user); 102 } 103 104 private: 105 // Look over the provided operands for any defining operations that should 106 // be re-added to the worklist. This function should be called when an 107 // operation is modified or removed, as it may trigger further 108 // simplifications. 109 template <typename Operands> 110 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(riverriddle) 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 matcher. 125 RewritePatternMatcher 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 // Make sure that any new operations are inserted at this point. 199 setInsertionPoint(op); 200 201 // Try to match one of the patterns. The rewriter is automatically 202 // notified of any necessary changes, so there is nothing else to do here. 203 changed |= matcher.matchAndRewrite(op, *this); 204 } 205 206 // After applying patterns, make sure that the CFG of each of the regions is 207 // kept up to date. 208 if (succeeded(simplifyRegions(regions))) { 209 folder.clear(); 210 changed = true; 211 } 212 } while (changed && ++i < maxIterations); 213 // Whether the rewrite converges, i.e. wasn't changed in the last iteration. 214 return !changed; 215 } 216 217 /// Rewrite the regions of the specified operation, which must be isolated from 218 /// above, by repeatedly applying the highest benefit patterns in a greedy 219 /// work-list driven manner. Return true if no more patterns can be matched in 220 /// the result operation regions. 221 /// Note: This does not apply patterns to the top-level operation itself. 222 /// 223 bool mlir::applyPatternsAndFoldGreedily( 224 Operation *op, const OwningRewritePatternList &patterns) { 225 return applyPatternsAndFoldGreedily(op->getRegions(), patterns); 226 } 227 228 /// Rewrite the given regions, which must be isolated from above. 229 bool mlir::applyPatternsAndFoldGreedily( 230 MutableArrayRef<Region> regions, const OwningRewritePatternList &patterns) { 231 if (regions.empty()) 232 return true; 233 234 // The top-level operation must be known to be isolated from above to 235 // prevent performing canonicalizations on operations defined at or above 236 // the region containing 'op'. 237 auto regionIsIsolated = [](Region ®ion) { 238 return region.getParentOp()->isKnownIsolatedFromAbove(); 239 }; 240 (void)regionIsIsolated; 241 assert(llvm::all_of(regions, regionIsIsolated) && 242 "patterns can only be applied to operations IsolatedFromAbove"); 243 244 // Start the pattern driver. 245 GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns); 246 bool converged = driver.simplify(regions, maxPatternMatchIterations); 247 LLVM_DEBUG(if (!converged) { 248 llvm::dbgs() << "The pattern rewrite doesn't converge after scanning " 249 << maxPatternMatchIterations << " times"; 250 }); 251 return converged; 252 } 253 254 //===----------------------------------------------------------------------===// 255 // OpPatternRewriteDriver 256 //===----------------------------------------------------------------------===// 257 258 namespace { 259 /// This is a simple driver for the PatternMatcher to apply patterns and perform 260 /// folding on a single op. It repeatedly applies locally optimal patterns. 261 class OpPatternRewriteDriver : public PatternRewriter { 262 public: 263 explicit OpPatternRewriteDriver(MLIRContext *ctx, 264 const OwningRewritePatternList &patterns) 265 : PatternRewriter(ctx), matcher(patterns), folder(ctx) {} 266 267 bool simplifyLocally(Operation *op, int maxIterations, bool &erased); 268 269 /// No additional action needed other than inserting the op. 270 Operation *insert(Operation *op) override { return OpBuilder::insert(op); } 271 272 // These are hooks implemented for PatternRewriter. 273 protected: 274 /// If an operation is about to be removed, mark it so that we can let clients 275 /// know. 276 void notifyOperationRemoved(Operation *op) override { 277 opErasedViaPatternRewrites = true; 278 } 279 280 // When a root is going to be replaced, its removal will be notified as well. 281 // So there is nothing to do here. 282 void notifyRootReplaced(Operation *op) override {} 283 284 private: 285 /// The low-level pattern matcher. 286 RewritePatternMatcher matcher; 287 288 /// Non-pattern based folder for operations. 289 OperationFolder folder; 290 291 /// Set to true if the operation has been erased via pattern rewrites. 292 bool opErasedViaPatternRewrites = false; 293 }; 294 295 } // anonymous namespace 296 297 /// Performs the rewrites and folding only on `op`. The simplification converges 298 /// if the op is erased as a result of being folded, replaced, or dead, or no 299 /// more changes happen in an iteration. Returns true if the rewrite converges 300 /// in `maxIterations`. `erased` is set to true if `op` gets erased. 301 bool OpPatternRewriteDriver::simplifyLocally(Operation *op, 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 // If the operation is trivially dead - remove it. 311 if (isOpTriviallyDead(op)) { 312 op->erase(); 313 erased = true; 314 return true; 315 } 316 317 // Try to fold this op. 318 bool inPlaceUpdate; 319 if (succeeded(folder.tryToFold(op, /*processGeneratedConstants=*/nullptr, 320 /*preReplaceAction=*/nullptr, 321 &inPlaceUpdate))) { 322 changed = true; 323 if (!inPlaceUpdate) { 324 erased = true; 325 return true; 326 } 327 } 328 329 // Make sure that any new operations are inserted at this point. 330 setInsertionPoint(op); 331 332 // Try to match one of the patterns. The rewriter is automatically 333 // notified of any necessary changes, so there is nothing else to do here. 334 changed |= matcher.matchAndRewrite(op, *this); 335 if ((erased = opErasedViaPatternRewrites)) 336 return true; 337 } while (changed && ++i < maxIterations); 338 339 // Whether the rewrite converges, i.e. wasn't changed in the last iteration. 340 return !changed; 341 } 342 343 /// Rewrites only `op` using the supplied canonicalization patterns and 344 /// folding. `erased` is set to true if the op is erased as a result of being 345 /// folded, replaced, or dead. 346 bool mlir::applyOpPatternsAndFold(Operation *op, 347 const OwningRewritePatternList &patterns, 348 bool *erased) { 349 // Start the pattern driver. 350 OpPatternRewriteDriver driver(op->getContext(), patterns); 351 bool opErased; 352 bool converged = 353 driver.simplifyLocally(op, maxPatternMatchIterations, opErased); 354 if (erased) 355 *erased = opErased; 356 LLVM_DEBUG(if (!converged) { 357 llvm::dbgs() << "The pattern rewrite doesn't converge after scanning " 358 << maxPatternMatchIterations << " times"; 359 }); 360 return converged; 361 } 362