1 //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===// 2 // 3 // Copyright 2019 The MLIR Authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // ============================================================================= 17 // 18 // This file implements mlir::applyPatternsGreedily. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "mlir/Dialect/StandardOps/Ops.h" 23 #include "mlir/IR/Builders.h" 24 #include "mlir/IR/PatternMatch.h" 25 #include "mlir/Transforms/FoldUtils.h" 26 #include "mlir/Transforms/RegionUtils.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace mlir; 33 34 #define DEBUG_TYPE "pattern-matcher" 35 36 static llvm::cl::opt<unsigned> maxPatternMatchIterations( 37 "mlir-max-pattern-match-iterations", 38 llvm::cl::desc("Max number of iterations scanning for pattern match"), 39 llvm::cl::init(10)); 40 41 namespace { 42 43 /// This is a worklist-driven driver for the PatternMatcher, which repeatedly 44 /// applies the locally optimal patterns in a roughly "bottom up" way. 45 class GreedyPatternRewriteDriver : public PatternRewriter { 46 public: 47 explicit GreedyPatternRewriteDriver(MLIRContext *ctx, 48 const OwningRewritePatternList &patterns) 49 : PatternRewriter(ctx), matcher(patterns), folder(ctx) { 50 worklist.reserve(64); 51 } 52 53 /// Perform the rewrites. Return true if the rewrite converges in 54 /// `maxIterations`. 55 bool simplify(MutableArrayRef<Region> regions, int maxIterations); 56 57 void addToWorklist(Operation *op) { 58 // Check to see if the worklist already contains this op. 59 if (worklistMap.count(op)) 60 return; 61 62 worklistMap[op] = worklist.size(); 63 worklist.push_back(op); 64 } 65 66 Operation *popFromWorklist() { 67 auto *op = worklist.back(); 68 worklist.pop_back(); 69 70 // This operation is no longer in the worklist, keep worklistMap up to date. 71 if (op) 72 worklistMap.erase(op); 73 return op; 74 } 75 76 /// If the specified operation is in the worklist, remove it. If not, this is 77 /// a no-op. 78 void removeFromWorklist(Operation *op) { 79 auto it = worklistMap.find(op); 80 if (it != worklistMap.end()) { 81 assert(worklist[it->second] == op && "malformed worklist data structure"); 82 worklist[it->second] = nullptr; 83 worklistMap.erase(it); 84 } 85 } 86 87 // These are hooks implemented for PatternRewriter. 88 protected: 89 // Implement the hook for creating operations, and make sure that newly 90 // created ops are added to the worklist for processing. 91 Operation *createOperation(const OperationState &state) override { 92 auto *result = OpBuilder::createOperation(state); 93 addToWorklist(result); 94 return result; 95 } 96 97 // If an operation is about to be removed, make sure it is not in our 98 // worklist anymore because we'd get dangling references to it. 99 void notifyOperationRemoved(Operation *op) override { 100 addToWorklist(op->getOperands()); 101 op->walk([this](Operation *operation) { 102 removeFromWorklist(operation); 103 folder.notifyRemoval(operation); 104 }); 105 } 106 107 // When the root of a pattern is about to be replaced, it can trigger 108 // simplifications to its users - make sure to add them to the worklist 109 // before the root is changed. 110 void notifyRootReplaced(Operation *op) override { 111 for (auto *result : op->getResults()) 112 for (auto *user : result->getUsers()) 113 addToWorklist(user); 114 } 115 116 private: 117 // Look over the provided operands for any defining operations that should 118 // be re-added to the worklist. This function should be called when an 119 // operation is modified or removed, as it may trigger further 120 // simplifications. 121 template <typename Operands> void addToWorklist(Operands &&operands) { 122 for (Value *operand : operands) { 123 // If the use count of this operand is now < 2, we re-add the defining 124 // operation to the worklist. 125 // TODO(riverriddle) This is based on the fact that zero use operations 126 // may be deleted, and that single use values often have more 127 // canonicalization opportunities. 128 if (!operand->use_empty() && !operand->hasOneUse()) 129 continue; 130 if (auto *defInst = operand->getDefiningOp()) 131 addToWorklist(defInst); 132 } 133 } 134 135 /// The low-level pattern matcher. 136 RewritePatternMatcher matcher; 137 138 /// The worklist for this transformation keeps track of the operations that 139 /// need to be revisited, plus their index in the worklist. This allows us to 140 /// efficiently remove operations from the worklist when they are erased, even 141 /// if they aren't the root of a pattern. 142 std::vector<Operation *> worklist; 143 DenseMap<Operation *, unsigned> worklistMap; 144 145 /// Non-pattern based folder for operations. 146 OperationFolder folder; 147 }; 148 } // end anonymous namespace 149 150 /// Perform the rewrites. 151 bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions, 152 int maxIterations) { 153 // Add the given operation to the worklist. 154 auto collectOps = [this](Operation *op) { addToWorklist(op); }; 155 156 bool changed = false; 157 int i = 0; 158 do { 159 // Add all nested operations to the worklist. 160 for (auto ®ion : regions) 161 region.walk(collectOps); 162 163 // These are scratch vectors used in the folding loop below. 164 SmallVector<Value *, 8> originalOperands, resultValues; 165 166 changed = false; 167 while (!worklist.empty()) { 168 auto *op = popFromWorklist(); 169 170 // Nulls get added to the worklist when operations are removed, ignore 171 // them. 172 if (op == nullptr) 173 continue; 174 175 // If the operation has no side effects, and no users, then it is 176 // trivially dead - remove it. 177 if (op->hasNoSideEffect() && op->use_empty()) { 178 // Be careful to update bookkeeping. 179 notifyOperationRemoved(op); 180 op->erase(); 181 continue; 182 } 183 184 // Collects all the operands and result uses of the given `op` into work 185 // list. Also remove `op` and nested ops from worklist. 186 originalOperands.assign(op->operand_begin(), op->operand_end()); 187 auto preReplaceAction = [&](Operation *op) { 188 // Add the operands to the worklist for visitation. 189 addToWorklist(originalOperands); 190 191 // Add all the users of the result to the worklist so we make sure 192 // to revisit them. 193 for (auto *result : op->getResults()) 194 for (auto *operand : result->getUsers()) 195 addToWorklist(operand); 196 197 notifyOperationRemoved(op); 198 }; 199 200 // Try to fold this op. 201 if (succeeded(folder.tryToFold(op, collectOps, preReplaceAction))) { 202 changed |= true; 203 continue; 204 } 205 206 // Make sure that any new operations are inserted at this point. 207 setInsertionPoint(op); 208 209 // Try to match one of the patterns. The rewriter is automatically 210 // notified of any necessary changes, so there is nothing else to do here. 211 changed |= matcher.matchAndRewrite(op, *this); 212 } 213 214 // After applying patterns, make sure that the CFG of each of the regions is 215 // kept up to date. 216 changed |= succeeded(simplifyRegions(regions)); 217 } while (changed && ++i < maxIterations); 218 // Whether the rewrite converges, i.e. wasn't changed in the last iteration. 219 return !changed; 220 } 221 222 /// Rewrite the regions of the specified operation, which must be isolated from 223 /// above, by repeatedly applying the highest benefit patterns in a greedy 224 /// work-list driven manner. Return true if no more patterns can be matched in 225 /// the result operation regions. 226 /// Note: This does not apply patterns to the top-level operation itself. 227 /// 228 bool mlir::applyPatternsGreedily(Operation *op, 229 const OwningRewritePatternList &patterns) { 230 return applyPatternsGreedily(op->getRegions(), patterns); 231 } 232 233 /// Rewrite the given regions, which must be isolated from above. 234 bool mlir::applyPatternsGreedily(MutableArrayRef<Region> regions, 235 const OwningRewritePatternList &patterns) { 236 if (regions.empty()) 237 return true; 238 239 // The top-level operation must be known to be isolated from above to 240 // prevent performing canonicalizations on operations defined at or above 241 // the region containing 'op'. 242 auto regionIsIsolated = [](Region ®ion) { 243 return region.getParentOp()->isKnownIsolatedFromAbove(); 244 }; 245 (void)regionIsIsolated; 246 assert(llvm::all_of(regions, regionIsIsolated) && 247 "patterns can only be applied to operations IsolatedFromAbove"); 248 249 // Start the pattern driver. 250 GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns); 251 bool converged = driver.simplify(regions, maxPatternMatchIterations); 252 LLVM_DEBUG(if (!converged) { 253 llvm::dbgs() << "The pattern rewrite doesn't converge after scanning " 254 << maxPatternMatchIterations << " times"; 255 }); 256 return converged; 257 } 258