164d52014SChris Lattner //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
264d52014SChris Lattner //
364d52014SChris Lattner // Copyright 2019 The MLIR Authors.
464d52014SChris Lattner //
564d52014SChris Lattner // Licensed under the Apache License, Version 2.0 (the "License");
664d52014SChris Lattner // you may not use this file except in compliance with the License.
764d52014SChris Lattner // You may obtain a copy of the License at
864d52014SChris Lattner //
964d52014SChris Lattner //   http://www.apache.org/licenses/LICENSE-2.0
1064d52014SChris Lattner //
1164d52014SChris Lattner // Unless required by applicable law or agreed to in writing, software
1264d52014SChris Lattner // distributed under the License is distributed on an "AS IS" BASIS,
1364d52014SChris Lattner // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1464d52014SChris Lattner // See the License for the specific language governing permissions and
1564d52014SChris Lattner // limitations under the License.
1664d52014SChris Lattner // =============================================================================
1764d52014SChris Lattner //
1864d52014SChris Lattner // This file implements mlir::applyPatternsGreedily.
1964d52014SChris Lattner //
2064d52014SChris Lattner //===----------------------------------------------------------------------===//
2164d52014SChris Lattner 
22ba0fa925SRiver Riddle #include "mlir/Dialect/StandardOps/Ops.h"
2364d52014SChris Lattner #include "mlir/IR/Builders.h"
247de0da95SChris Lattner #include "mlir/IR/PatternMatch.h"
25*a32f0dcbSRiver Riddle #include "mlir/IR/RegionGraphTraits.h"
261982afb1SRiver Riddle #include "mlir/Transforms/FoldUtils.h"
2764d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
28*a32f0dcbSRiver Riddle #include "llvm/ADT/DepthFirstIterator.h"
295c757087SFeng Liu #include "llvm/Support/CommandLine.h"
305c757087SFeng Liu #include "llvm/Support/Debug.h"
315c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
324e40c832SLei Zhang 
3364d52014SChris Lattner using namespace mlir;
3464d52014SChris Lattner 
355c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
365c757087SFeng Liu 
375c757087SFeng Liu static llvm::cl::opt<unsigned> maxPatternMatchIterations(
385c757087SFeng Liu     "mlir-max-pattern-match-iterations",
39e7a2ef21SRiver Riddle     llvm::cl::desc("Max number of iterations scanning for pattern match"),
405c757087SFeng Liu     llvm::cl::init(10));
415c757087SFeng Liu 
4264d52014SChris Lattner namespace {
4364d52014SChris Lattner 
4464d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
4564d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
464bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
4764d52014SChris Lattner public:
482566a72aSRiver Riddle   explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
495290e8c3SRiver Riddle                                       const OwningRewritePatternList &patterns)
506563b1c4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
5164d52014SChris Lattner     worklist.reserve(64);
5264d52014SChris Lattner   }
5364d52014SChris Lattner 
545c757087SFeng Liu   /// Perform the rewrites. Return true if the rewrite converges in
555c757087SFeng Liu   /// `maxIterations`.
566b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
5764d52014SChris Lattner 
5899b87c97SRiver Riddle   void addToWorklist(Operation *op) {
595c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
605c4f1fddSRiver Riddle     if (worklistMap.count(op))
615c4f1fddSRiver Riddle       return;
625c4f1fddSRiver Riddle 
6364d52014SChris Lattner     worklistMap[op] = worklist.size();
6464d52014SChris Lattner     worklist.push_back(op);
6564d52014SChris Lattner   }
6664d52014SChris Lattner 
6799b87c97SRiver Riddle   Operation *popFromWorklist() {
6864d52014SChris Lattner     auto *op = worklist.back();
6964d52014SChris Lattner     worklist.pop_back();
7064d52014SChris Lattner 
7164d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
7264d52014SChris Lattner     if (op)
7364d52014SChris Lattner       worklistMap.erase(op);
7464d52014SChris Lattner     return op;
7564d52014SChris Lattner   }
7664d52014SChris Lattner 
7764d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
7864d52014SChris Lattner   /// a no-op.
7999b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
8064d52014SChris Lattner     auto it = worklistMap.find(op);
8164d52014SChris Lattner     if (it != worklistMap.end()) {
8264d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
8364d52014SChris Lattner       worklist[it->second] = nullptr;
84c87c7f57SDiego Caballero       worklistMap.erase(it);
8564d52014SChris Lattner     }
8664d52014SChris Lattner   }
8764d52014SChris Lattner 
884bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
894bd9f936SChris Lattner protected:
904bd9f936SChris Lattner   // Implement the hook for creating operations, and make sure that newly
914bd9f936SChris Lattner   // created ops are added to the worklist for processing.
9299b87c97SRiver Riddle   Operation *createOperation(const OperationState &state) override {
93f1b848e4SRiver Riddle     auto *result = OpBuilder::createOperation(state);
944bd9f936SChris Lattner     addToWorklist(result);
954bd9f936SChris Lattner     return result;
964bd9f936SChris Lattner   }
9764d52014SChris Lattner 
9864d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
9964d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
10099b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
101a8866258SRiver Riddle     addToWorklist(op->getOperands());
10255f2e24aSAndy Ly     op->walk([this](Operation *operation) {
10355f2e24aSAndy Ly       removeFromWorklist(operation);
10455f2e24aSAndy Ly       folder.notifyRemoval(operation);
10555f2e24aSAndy Ly     });
10664d52014SChris Lattner   }
10764d52014SChris Lattner 
108085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
109085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
110085b687fSChris Lattner   // before the root is changed.
11199b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
112085b687fSChris Lattner     for (auto *result : op->getResults())
1138780d8d8SRiver Riddle       for (auto *user : result->getUsers())
1148780d8d8SRiver Riddle         addToWorklist(user);
115085b687fSChris Lattner   }
116085b687fSChris Lattner 
1174bd9f936SChris Lattner private:
118*a32f0dcbSRiver Riddle   /// Erase the unreachable blocks within the provided regions. Returns success
119*a32f0dcbSRiver Riddle   /// if any blocks were erased, failure otherwise.
120*a32f0dcbSRiver Riddle   LogicalResult eraseUnreachableBlocks(MutableArrayRef<Region> regions) {
121*a32f0dcbSRiver Riddle     // Set of blocks found to be reachable within a given region.
122*a32f0dcbSRiver Riddle     llvm::df_iterator_default_set<Block *, 16> reachable;
123*a32f0dcbSRiver Riddle     // If any blocks were found to be dead.
124*a32f0dcbSRiver Riddle     bool erasedDeadBlocks = false;
125*a32f0dcbSRiver Riddle 
126*a32f0dcbSRiver Riddle     SmallVector<Region *, 1> worklist;
127*a32f0dcbSRiver Riddle     worklist.reserve(regions.size());
128*a32f0dcbSRiver Riddle     for (Region &region : regions)
129*a32f0dcbSRiver Riddle       worklist.push_back(&region);
130*a32f0dcbSRiver Riddle     while (!worklist.empty()) {
131*a32f0dcbSRiver Riddle       Region *region = worklist.pop_back_val();
132*a32f0dcbSRiver Riddle       if (region->empty())
133*a32f0dcbSRiver Riddle         continue;
134*a32f0dcbSRiver Riddle 
135*a32f0dcbSRiver Riddle       // If this is a single block region, just collect the nested regions.
136*a32f0dcbSRiver Riddle       if (std::next(region->begin()) == region->end()) {
137*a32f0dcbSRiver Riddle         for (Operation &op : region->front())
138*a32f0dcbSRiver Riddle           for (Region &region : op.getRegions())
139*a32f0dcbSRiver Riddle             worklist.push_back(&region);
140*a32f0dcbSRiver Riddle         continue;
141*a32f0dcbSRiver Riddle       }
142*a32f0dcbSRiver Riddle 
143*a32f0dcbSRiver Riddle       // Mark all reachable blocks.
144*a32f0dcbSRiver Riddle       reachable.clear();
145*a32f0dcbSRiver Riddle       for (Block *block : depth_first_ext(&region->front(), reachable))
146*a32f0dcbSRiver Riddle         (void)block /* Mark all reachable blocks */;
147*a32f0dcbSRiver Riddle 
148*a32f0dcbSRiver Riddle       // Collect all of the dead blocks and push the live regions onto the
149*a32f0dcbSRiver Riddle       // worklist.
150*a32f0dcbSRiver Riddle       for (Block &block : llvm::make_early_inc_range(*region)) {
151*a32f0dcbSRiver Riddle         if (!reachable.count(&block)) {
152*a32f0dcbSRiver Riddle           block.dropAllDefinedValueUses();
153*a32f0dcbSRiver Riddle           block.erase();
154*a32f0dcbSRiver Riddle           erasedDeadBlocks = true;
155*a32f0dcbSRiver Riddle           continue;
156*a32f0dcbSRiver Riddle         }
157*a32f0dcbSRiver Riddle 
158*a32f0dcbSRiver Riddle         // Walk any regions within this block.
159*a32f0dcbSRiver Riddle         for (Operation &op : block)
160*a32f0dcbSRiver Riddle           for (Region &region : op.getRegions())
161*a32f0dcbSRiver Riddle             worklist.push_back(&region);
162*a32f0dcbSRiver Riddle       }
163*a32f0dcbSRiver Riddle     }
164*a32f0dcbSRiver Riddle 
165*a32f0dcbSRiver Riddle     return success(erasedDeadBlocks);
166*a32f0dcbSRiver Riddle   }
167*a32f0dcbSRiver Riddle 
16899b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
169a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
170a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
171a8866258SRiver Riddle   // simplifications.
172a8866258SRiver Riddle   template <typename Operands> void addToWorklist(Operands &&operands) {
173a8866258SRiver Riddle     for (Value *operand : operands) {
174a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
17599b87c97SRiver Riddle       // operation to the worklist.
17699b87c97SRiver Riddle       // TODO(riverriddle) This is based on the fact that zero use operations
177a8866258SRiver Riddle       // may be deleted, and that single use values often have more
178a8866258SRiver Riddle       // canonicalization opportunities.
1795c757087SFeng Liu       if (!operand->use_empty() && !operand->hasOneUse())
180a8866258SRiver Riddle         continue;
181f9d91531SRiver Riddle       if (auto *defInst = operand->getDefiningOp())
182a8866258SRiver Riddle         addToWorklist(defInst);
183a8866258SRiver Riddle     }
184a8866258SRiver Riddle   }
185a8866258SRiver Riddle 
1864bd9f936SChris Lattner   /// The low-level pattern matcher.
1875de726f4SRiver Riddle   RewritePatternMatcher matcher;
1884bd9f936SChris Lattner 
1894bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1904bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
191e7a2ef21SRiver Riddle   /// efficiently remove operations from the worklist when they are erased, even
192e7a2ef21SRiver Riddle   /// if they aren't the root of a pattern.
19399b87c97SRiver Riddle   std::vector<Operation *> worklist;
19499b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
19560a29837SRiver Riddle 
19660a29837SRiver Riddle   /// Non-pattern based folder for operations.
19760a29837SRiver Riddle   OperationFolder folder;
19864d52014SChris Lattner };
19991f07810SMehdi Amini } // end anonymous namespace
20064d52014SChris Lattner 
2014bd9f936SChris Lattner /// Perform the rewrites.
2026b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
2036b1cc3c6SRiver Riddle                                           int maxIterations) {
204bcacef1aSRiver Riddle   // Add the given operation to the worklist.
205bcacef1aSRiver Riddle   auto collectOps = [this](Operation *op) { addToWorklist(op); };
206bcacef1aSRiver Riddle 
2075c757087SFeng Liu   bool changed = false;
2085c757087SFeng Liu   int i = 0;
2095c757087SFeng Liu   do {
210e7a2ef21SRiver Riddle     // Add all nested operations to the worklist.
2116b1cc3c6SRiver Riddle     for (auto &region : regions)
212e7a2ef21SRiver Riddle       region.walk(collectOps);
2134e40c832SLei Zhang 
2144e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
215934b6d12SChris Lattner     SmallVector<Value *, 8> originalOperands, resultValues;
21664d52014SChris Lattner 
2175c757087SFeng Liu     changed = false;
21864d52014SChris Lattner     while (!worklist.empty()) {
21964d52014SChris Lattner       auto *op = popFromWorklist();
22064d52014SChris Lattner 
2215c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
2225c757087SFeng Liu       // them.
22364d52014SChris Lattner       if (op == nullptr)
22464d52014SChris Lattner         continue;
22564d52014SChris Lattner 
2265c757087SFeng Liu       // If the operation has no side effects, and no users, then it is
2275c757087SFeng Liu       // trivially dead - remove it.
22864d52014SChris Lattner       if (op->hasNoSideEffect() && op->use_empty()) {
2296a501e3dSAndy Ly         // Be careful to update bookkeeping.
2306a501e3dSAndy Ly         notifyOperationRemoved(op);
23164d52014SChris Lattner         op->erase();
23264d52014SChris Lattner         continue;
23364d52014SChris Lattner       }
23464d52014SChris Lattner 
2354e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
2366a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
2371982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
2386a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
239a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
2401982afb1SRiver Riddle         addToWorklist(originalOperands);
2411982afb1SRiver Riddle 
2424e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
2434e40c832SLei Zhang         // to revisit them.
2448780d8d8SRiver Riddle         for (auto *result : op->getResults())
2458780d8d8SRiver Riddle           for (auto *operand : result->getUsers())
2468780d8d8SRiver Riddle             addToWorklist(operand);
2476a501e3dSAndy Ly 
2486a501e3dSAndy Ly         notifyOperationRemoved(op);
2494e40c832SLei Zhang       };
25064d52014SChris Lattner 
2511982afb1SRiver Riddle       // Try to fold this op.
2526a501e3dSAndy Ly       if (succeeded(folder.tryToFold(op, collectOps, preReplaceAction))) {
2535c757087SFeng Liu         changed |= true;
254934b6d12SChris Lattner         continue;
25564d52014SChris Lattner       }
25664d52014SChris Lattner 
25764d52014SChris Lattner       // Make sure that any new operations are inserted at this point.
258eb5ec039SRiver Riddle       setInsertionPoint(op);
2595de726f4SRiver Riddle 
26032052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
26132052c84SRiver Riddle       // notified of any necessary changes, so there is nothing else to do here.
2623de0c769SRiver Riddle       changed |= matcher.matchAndRewrite(op, *this);
26364d52014SChris Lattner     }
264*a32f0dcbSRiver Riddle 
265*a32f0dcbSRiver Riddle     // After applying patterns, make sure that the CFG of each of the regions is
266*a32f0dcbSRiver Riddle     // kept up to date.
267*a32f0dcbSRiver Riddle     changed |= succeeded(eraseUnreachableBlocks(regions));
2685c757087SFeng Liu   } while (changed && ++i < maxIterations);
2695c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2705c757087SFeng Liu   return !changed;
27164d52014SChris Lattner }
27264d52014SChris Lattner 
273e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
274e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
275e7a2ef21SRiver Riddle /// work-list driven manner. Return true if no more patterns can be matched in
276e7a2ef21SRiver Riddle /// the result operation regions.
277e7a2ef21SRiver Riddle /// Note: This does not apply patterns to the top-level operation itself.
27864d52014SChris Lattner ///
279e7a2ef21SRiver Riddle bool mlir::applyPatternsGreedily(Operation *op,
2805290e8c3SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2816b1cc3c6SRiver Riddle   return applyPatternsGreedily(op->getRegions(), patterns);
2826b1cc3c6SRiver Riddle }
2836b1cc3c6SRiver Riddle 
2846b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
2856b1cc3c6SRiver Riddle bool mlir::applyPatternsGreedily(MutableArrayRef<Region> regions,
2866b1cc3c6SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2876b1cc3c6SRiver Riddle   if (regions.empty())
2886b1cc3c6SRiver Riddle     return true;
2896b1cc3c6SRiver Riddle 
290e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
291e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
292e7a2ef21SRiver Riddle   // the region containing 'op'.
2936b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
2946b1cc3c6SRiver Riddle     return region.getParentOp()->isKnownIsolatedFromAbove();
2956b1cc3c6SRiver Riddle   };
2966b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2976b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2986b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
299e7a2ef21SRiver Riddle 
3006b1cc3c6SRiver Riddle   // Start the pattern driver.
3016b1cc3c6SRiver Riddle   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns);
3026b1cc3c6SRiver Riddle   bool converged = driver.simplify(regions, maxPatternMatchIterations);
3035c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
304e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
3055c757087SFeng Liu                  << maxPatternMatchIterations << " times";
3065c757087SFeng Liu   });
3075c757087SFeng Liu   return converged;
30864d52014SChris Lattner }
309