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"
251982afb1SRiver Riddle #include "mlir/Transforms/FoldUtils.h"
2664d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
275c757087SFeng Liu #include "llvm/Support/CommandLine.h"
285c757087SFeng Liu #include "llvm/Support/Debug.h"
295c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
304e40c832SLei Zhang 
3164d52014SChris Lattner using namespace mlir;
3264d52014SChris Lattner 
335c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
345c757087SFeng Liu 
355c757087SFeng Liu static llvm::cl::opt<unsigned> maxPatternMatchIterations(
365c757087SFeng Liu     "mlir-max-pattern-match-iterations",
37e7a2ef21SRiver Riddle     llvm::cl::desc("Max number of iterations scanning for pattern match"),
385c757087SFeng Liu     llvm::cl::init(10));
395c757087SFeng Liu 
4064d52014SChris Lattner namespace {
4164d52014SChris Lattner 
4264d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
4364d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
444bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
4564d52014SChris Lattner public:
462566a72aSRiver Riddle   explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
475290e8c3SRiver Riddle                                       const OwningRewritePatternList &patterns)
486563b1c4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
4964d52014SChris Lattner     worklist.reserve(64);
5064d52014SChris Lattner   }
5164d52014SChris Lattner 
525c757087SFeng Liu   /// Perform the rewrites. Return true if the rewrite converges in
535c757087SFeng Liu   /// `maxIterations`.
546b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
5564d52014SChris Lattner 
5699b87c97SRiver Riddle   void addToWorklist(Operation *op) {
575c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
585c4f1fddSRiver Riddle     if (worklistMap.count(op))
595c4f1fddSRiver Riddle       return;
605c4f1fddSRiver Riddle 
6164d52014SChris Lattner     worklistMap[op] = worklist.size();
6264d52014SChris Lattner     worklist.push_back(op);
6364d52014SChris Lattner   }
6464d52014SChris Lattner 
6599b87c97SRiver Riddle   Operation *popFromWorklist() {
6664d52014SChris Lattner     auto *op = worklist.back();
6764d52014SChris Lattner     worklist.pop_back();
6864d52014SChris Lattner 
6964d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
7064d52014SChris Lattner     if (op)
7164d52014SChris Lattner       worklistMap.erase(op);
7264d52014SChris Lattner     return op;
7364d52014SChris Lattner   }
7464d52014SChris Lattner 
7564d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
7664d52014SChris Lattner   /// a no-op.
7799b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
7864d52014SChris Lattner     auto it = worklistMap.find(op);
7964d52014SChris Lattner     if (it != worklistMap.end()) {
8064d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
8164d52014SChris Lattner       worklist[it->second] = nullptr;
82*c87c7f57SDiego Caballero       worklistMap.erase(it);
8364d52014SChris Lattner     }
8464d52014SChris Lattner   }
8564d52014SChris Lattner 
864bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
874bd9f936SChris Lattner protected:
884bd9f936SChris Lattner   // Implement the hook for creating operations, and make sure that newly
894bd9f936SChris Lattner   // created ops are added to the worklist for processing.
9099b87c97SRiver Riddle   Operation *createOperation(const OperationState &state) override {
91f1b848e4SRiver Riddle     auto *result = OpBuilder::createOperation(state);
924bd9f936SChris Lattner     addToWorklist(result);
934bd9f936SChris Lattner     return result;
944bd9f936SChris Lattner   }
9564d52014SChris Lattner 
9664d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
9764d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
9899b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
99a8866258SRiver Riddle     addToWorklist(op->getOperands());
10055f2e24aSAndy Ly     op->walk([this](Operation *operation) {
10155f2e24aSAndy Ly       removeFromWorklist(operation);
10255f2e24aSAndy Ly       folder.notifyRemoval(operation);
10355f2e24aSAndy Ly     });
10464d52014SChris Lattner   }
10564d52014SChris Lattner 
106085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
107085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
108085b687fSChris Lattner   // before the root is changed.
10999b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
110085b687fSChris Lattner     for (auto *result : op->getResults())
1118780d8d8SRiver Riddle       for (auto *user : result->getUsers())
1128780d8d8SRiver Riddle         addToWorklist(user);
113085b687fSChris Lattner   }
114085b687fSChris Lattner 
1154bd9f936SChris Lattner private:
11699b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
117a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
118a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
119a8866258SRiver Riddle   // simplifications.
120a8866258SRiver Riddle   template <typename Operands> void addToWorklist(Operands &&operands) {
121a8866258SRiver Riddle     for (Value *operand : operands) {
122a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
12399b87c97SRiver Riddle       // operation to the worklist.
12499b87c97SRiver Riddle       // TODO(riverriddle) This is based on the fact that zero use operations
125a8866258SRiver Riddle       // may be deleted, and that single use values often have more
126a8866258SRiver Riddle       // canonicalization opportunities.
1275c757087SFeng Liu       if (!operand->use_empty() && !operand->hasOneUse())
128a8866258SRiver Riddle         continue;
129f9d91531SRiver Riddle       if (auto *defInst = operand->getDefiningOp())
130a8866258SRiver Riddle         addToWorklist(defInst);
131a8866258SRiver Riddle     }
132a8866258SRiver Riddle   }
133a8866258SRiver Riddle 
1344bd9f936SChris Lattner   /// The low-level pattern matcher.
1355de726f4SRiver Riddle   RewritePatternMatcher matcher;
1364bd9f936SChris Lattner 
1374bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1384bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
139e7a2ef21SRiver Riddle   /// efficiently remove operations from the worklist when they are erased, even
140e7a2ef21SRiver Riddle   /// if they aren't the root of a pattern.
14199b87c97SRiver Riddle   std::vector<Operation *> worklist;
14299b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
14360a29837SRiver Riddle 
14460a29837SRiver Riddle   /// Non-pattern based folder for operations.
14560a29837SRiver Riddle   OperationFolder folder;
14664d52014SChris Lattner };
14791f07810SMehdi Amini } // end anonymous namespace
14864d52014SChris Lattner 
1494bd9f936SChris Lattner /// Perform the rewrites.
1506b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
1516b1cc3c6SRiver Riddle                                           int maxIterations) {
152bcacef1aSRiver Riddle   // Add the given operation to the worklist.
153bcacef1aSRiver Riddle   auto collectOps = [this](Operation *op) { addToWorklist(op); };
154bcacef1aSRiver Riddle 
1555c757087SFeng Liu   bool changed = false;
1565c757087SFeng Liu   int i = 0;
1575c757087SFeng Liu   do {
158e7a2ef21SRiver Riddle     // Add all nested operations to the worklist.
1596b1cc3c6SRiver Riddle     for (auto &region : regions)
160e7a2ef21SRiver Riddle       region.walk(collectOps);
1614e40c832SLei Zhang 
1624e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
163934b6d12SChris Lattner     SmallVector<Value *, 8> originalOperands, resultValues;
16464d52014SChris Lattner 
1655c757087SFeng Liu     changed = false;
16664d52014SChris Lattner     while (!worklist.empty()) {
16764d52014SChris Lattner       auto *op = popFromWorklist();
16864d52014SChris Lattner 
1695c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1705c757087SFeng Liu       // them.
17164d52014SChris Lattner       if (op == nullptr)
17264d52014SChris Lattner         continue;
17364d52014SChris Lattner 
1745c757087SFeng Liu       // If the operation has no side effects, and no users, then it is
1755c757087SFeng Liu       // trivially dead - remove it.
17664d52014SChris Lattner       if (op->hasNoSideEffect() && op->use_empty()) {
1776a501e3dSAndy Ly         // Be careful to update bookkeeping.
1786a501e3dSAndy Ly         notifyOperationRemoved(op);
17964d52014SChris Lattner         op->erase();
18064d52014SChris Lattner         continue;
18164d52014SChris Lattner       }
18264d52014SChris Lattner 
1834e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
1846a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
1851982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
1866a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
187a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
1881982afb1SRiver Riddle         addToWorklist(originalOperands);
1891982afb1SRiver Riddle 
1904e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
1914e40c832SLei Zhang         // to revisit them.
1928780d8d8SRiver Riddle         for (auto *result : op->getResults())
1938780d8d8SRiver Riddle           for (auto *operand : result->getUsers())
1948780d8d8SRiver Riddle             addToWorklist(operand);
1956a501e3dSAndy Ly 
1966a501e3dSAndy Ly         notifyOperationRemoved(op);
1974e40c832SLei Zhang       };
19864d52014SChris Lattner 
1991982afb1SRiver Riddle       // Try to fold this op.
2006a501e3dSAndy Ly       if (succeeded(folder.tryToFold(op, collectOps, preReplaceAction))) {
2015c757087SFeng Liu         changed |= true;
202934b6d12SChris Lattner         continue;
20364d52014SChris Lattner       }
20464d52014SChris Lattner 
20564d52014SChris Lattner       // Make sure that any new operations are inserted at this point.
206eb5ec039SRiver Riddle       setInsertionPoint(op);
2075de726f4SRiver Riddle 
20832052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
20932052c84SRiver Riddle       // notified of any necessary changes, so there is nothing else to do here.
2103de0c769SRiver Riddle       changed |= matcher.matchAndRewrite(op, *this);
21164d52014SChris Lattner     }
2125c757087SFeng Liu   } while (changed && ++i < maxIterations);
2135c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2145c757087SFeng Liu   return !changed;
21564d52014SChris Lattner }
21664d52014SChris Lattner 
217e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
218e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
219e7a2ef21SRiver Riddle /// work-list driven manner. Return true if no more patterns can be matched in
220e7a2ef21SRiver Riddle /// the result operation regions.
221e7a2ef21SRiver Riddle /// Note: This does not apply patterns to the top-level operation itself.
22264d52014SChris Lattner ///
223e7a2ef21SRiver Riddle bool mlir::applyPatternsGreedily(Operation *op,
2245290e8c3SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2256b1cc3c6SRiver Riddle   return applyPatternsGreedily(op->getRegions(), patterns);
2266b1cc3c6SRiver Riddle }
2276b1cc3c6SRiver Riddle 
2286b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
2296b1cc3c6SRiver Riddle bool mlir::applyPatternsGreedily(MutableArrayRef<Region> regions,
2306b1cc3c6SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2316b1cc3c6SRiver Riddle   if (regions.empty())
2326b1cc3c6SRiver Riddle     return true;
2336b1cc3c6SRiver Riddle 
234e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
235e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
236e7a2ef21SRiver Riddle   // the region containing 'op'.
2376b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
2386b1cc3c6SRiver Riddle     return region.getParentOp()->isKnownIsolatedFromAbove();
2396b1cc3c6SRiver Riddle   };
2406b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2416b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2426b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
243e7a2ef21SRiver Riddle 
2446b1cc3c6SRiver Riddle   // Start the pattern driver.
2456b1cc3c6SRiver Riddle   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns);
2466b1cc3c6SRiver Riddle   bool converged = driver.simplify(regions, maxPatternMatchIterations);
2475c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
248e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
2495c757087SFeng Liu                  << maxPatternMatchIterations << " times";
2505c757087SFeng Liu   });
2515c757087SFeng Liu   return converged;
25264d52014SChris Lattner }
253