164d52014SChris Lattner //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
264d52014SChris Lattner //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
664d52014SChris Lattner //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
864d52014SChris Lattner //
9a60fdd2bSLorenzo Chelini // This file implements mlir::applyPatternsAndFoldGreedily.
1064d52014SChris Lattner //
1164d52014SChris Lattner //===----------------------------------------------------------------------===//
1264d52014SChris Lattner 
137de0da95SChris Lattner #include "mlir/IR/PatternMatch.h"
14*eb623ae8SStephen Neuendorffer #include "mlir/Interfaces/SideEffectInterfaces.h"
151982afb1SRiver Riddle #include "mlir/Transforms/FoldUtils.h"
16fafb708bSRiver Riddle #include "mlir/Transforms/RegionUtils.h"
1764d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
185c757087SFeng Liu #include "llvm/Support/CommandLine.h"
195c757087SFeng Liu #include "llvm/Support/Debug.h"
205c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
214e40c832SLei Zhang 
2264d52014SChris Lattner using namespace mlir;
2364d52014SChris Lattner 
245c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
255c757087SFeng Liu 
26400ad6f9SRiver Riddle /// The max number of iterations scanning for pattern match.
27400ad6f9SRiver Riddle static unsigned maxPatternMatchIterations = 10;
285c757087SFeng Liu 
2904b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
3004b5274eSUday Bondhugula // GreedyPatternRewriteDriver
3104b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
3204b5274eSUday Bondhugula 
3364d52014SChris Lattner namespace {
3464d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
3564d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
364bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
3764d52014SChris Lattner public:
382566a72aSRiver Riddle   explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
395290e8c3SRiver Riddle                                       const OwningRewritePatternList &patterns)
406563b1c4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
4164d52014SChris Lattner     worklist.reserve(64);
4264d52014SChris Lattner   }
4364d52014SChris Lattner 
446b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
4564d52014SChris Lattner 
4699b87c97SRiver Riddle   void addToWorklist(Operation *op) {
475c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
485c4f1fddSRiver Riddle     if (worklistMap.count(op))
495c4f1fddSRiver Riddle       return;
505c4f1fddSRiver Riddle 
5164d52014SChris Lattner     worklistMap[op] = worklist.size();
5264d52014SChris Lattner     worklist.push_back(op);
5364d52014SChris Lattner   }
5464d52014SChris Lattner 
5599b87c97SRiver Riddle   Operation *popFromWorklist() {
5664d52014SChris Lattner     auto *op = worklist.back();
5764d52014SChris Lattner     worklist.pop_back();
5864d52014SChris Lattner 
5964d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
6064d52014SChris Lattner     if (op)
6164d52014SChris Lattner       worklistMap.erase(op);
6264d52014SChris Lattner     return op;
6364d52014SChris Lattner   }
6464d52014SChris Lattner 
6564d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
6664d52014SChris Lattner   /// a no-op.
6799b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
6864d52014SChris Lattner     auto it = worklistMap.find(op);
6964d52014SChris Lattner     if (it != worklistMap.end()) {
7064d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
7164d52014SChris Lattner       worklist[it->second] = nullptr;
72c87c7f57SDiego Caballero       worklistMap.erase(it);
7364d52014SChris Lattner     }
7464d52014SChris Lattner   }
7564d52014SChris Lattner 
764bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
774bd9f936SChris Lattner protected:
78851a8516SRiver Riddle   // Implement the hook for inserting operations, and make sure that newly
79851a8516SRiver Riddle   // inserted ops are added to the worklist for processing.
80359164f8SRiver Riddle   void notifyOperationInserted(Operation *op) override { addToWorklist(op); }
8164d52014SChris Lattner 
8264d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
8364d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
8499b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
85a8866258SRiver Riddle     addToWorklist(op->getOperands());
8655f2e24aSAndy Ly     op->walk([this](Operation *operation) {
8755f2e24aSAndy Ly       removeFromWorklist(operation);
8855f2e24aSAndy Ly       folder.notifyRemoval(operation);
8955f2e24aSAndy Ly     });
9064d52014SChris Lattner   }
9164d52014SChris Lattner 
92085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
93085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
94085b687fSChris Lattner   // before the root is changed.
9599b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
9635807bc4SRiver Riddle     for (auto result : op->getResults())
972bdf33ccSRiver Riddle       for (auto *user : result.getUsers())
988780d8d8SRiver Riddle         addToWorklist(user);
99085b687fSChris Lattner   }
100085b687fSChris Lattner 
1014bd9f936SChris Lattner private:
10299b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
103a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
104a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
105a8866258SRiver Riddle   // simplifications.
106cbcb12fdSUday Bondhugula   template <typename Operands>
107cbcb12fdSUday Bondhugula   void addToWorklist(Operands &&operands) {
108e62a6956SRiver Riddle     for (Value operand : operands) {
109a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
11099b87c97SRiver Riddle       // operation to the worklist.
11199b87c97SRiver Riddle       // TODO(riverriddle) This is based on the fact that zero use operations
112a8866258SRiver Riddle       // may be deleted, and that single use values often have more
113a8866258SRiver Riddle       // canonicalization opportunities.
1142bdf33ccSRiver Riddle       if (!operand.use_empty() && !operand.hasOneUse())
115a8866258SRiver Riddle         continue;
1162bdf33ccSRiver Riddle       if (auto *defInst = operand.getDefiningOp())
117a8866258SRiver Riddle         addToWorklist(defInst);
118a8866258SRiver Riddle     }
119a8866258SRiver Riddle   }
120a8866258SRiver Riddle 
1214bd9f936SChris Lattner   /// The low-level pattern matcher.
1225de726f4SRiver Riddle   RewritePatternMatcher matcher;
1234bd9f936SChris Lattner 
1244bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1254bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
126e7a2ef21SRiver Riddle   /// efficiently remove operations from the worklist when they are erased, even
127e7a2ef21SRiver Riddle   /// if they aren't the root of a pattern.
12899b87c97SRiver Riddle   std::vector<Operation *> worklist;
12999b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
13060a29837SRiver Riddle 
13160a29837SRiver Riddle   /// Non-pattern based folder for operations.
13260a29837SRiver Riddle   OperationFolder folder;
13364d52014SChris Lattner };
13491f07810SMehdi Amini } // end anonymous namespace
13564d52014SChris Lattner 
136cbcb12fdSUday Bondhugula /// Performs the rewrites while folding and erasing any dead ops. Returns true
137cbcb12fdSUday Bondhugula /// if the rewrite converges in `maxIterations`.
1386b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
1396b1cc3c6SRiver Riddle                                           int maxIterations) {
140bcacef1aSRiver Riddle   // Add the given operation to the worklist.
141bcacef1aSRiver Riddle   auto collectOps = [this](Operation *op) { addToWorklist(op); };
142bcacef1aSRiver Riddle 
1435c757087SFeng Liu   bool changed = false;
1445c757087SFeng Liu   int i = 0;
1455c757087SFeng Liu   do {
146e7a2ef21SRiver Riddle     // Add all nested operations to the worklist.
1476b1cc3c6SRiver Riddle     for (auto &region : regions)
148e7a2ef21SRiver Riddle       region.walk(collectOps);
1494e40c832SLei Zhang 
1504e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
151e62a6956SRiver Riddle     SmallVector<Value, 8> originalOperands, resultValues;
15264d52014SChris Lattner 
1535c757087SFeng Liu     changed = false;
15464d52014SChris Lattner     while (!worklist.empty()) {
15564d52014SChris Lattner       auto *op = popFromWorklist();
15664d52014SChris Lattner 
1575c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1585c757087SFeng Liu       // them.
15964d52014SChris Lattner       if (op == nullptr)
16064d52014SChris Lattner         continue;
16164d52014SChris Lattner 
1620ddba0bdSRiver Riddle       // If the operation is trivially dead - remove it.
1630ddba0bdSRiver Riddle       if (isOpTriviallyDead(op)) {
1646a501e3dSAndy Ly         notifyOperationRemoved(op);
16564d52014SChris Lattner         op->erase();
166f875e55bSUday Bondhugula         changed = true;
16764d52014SChris Lattner         continue;
16864d52014SChris Lattner       }
16964d52014SChris Lattner 
1704e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
1716a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
1721982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
1736a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
174a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
1751982afb1SRiver Riddle         addToWorklist(originalOperands);
1761982afb1SRiver Riddle 
1774e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
1784e40c832SLei Zhang         // to revisit them.
17935807bc4SRiver Riddle         for (auto result : op->getResults())
180cc673894SUday Bondhugula           for (auto *userOp : result.getUsers())
181cc673894SUday Bondhugula             addToWorklist(userOp);
1826a501e3dSAndy Ly 
1836a501e3dSAndy Ly         notifyOperationRemoved(op);
1844e40c832SLei Zhang       };
18564d52014SChris Lattner 
1861982afb1SRiver Riddle       // Try to fold this op.
187cbcb12fdSUday Bondhugula       bool inPlaceUpdate;
188cbcb12fdSUday Bondhugula       if ((succeeded(folder.tryToFold(op, collectOps, preReplaceAction,
189cbcb12fdSUday Bondhugula                                       &inPlaceUpdate)))) {
190f875e55bSUday Bondhugula         changed = true;
191cbcb12fdSUday Bondhugula         if (!inPlaceUpdate)
192934b6d12SChris Lattner           continue;
19364d52014SChris Lattner       }
19464d52014SChris Lattner 
19564d52014SChris Lattner       // Make sure that any new operations are inserted at this point.
196eb5ec039SRiver Riddle       setInsertionPoint(op);
1975de726f4SRiver Riddle 
19832052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
19932052c84SRiver Riddle       // notified of any necessary changes, so there is nothing else to do here.
2003de0c769SRiver Riddle       changed |= matcher.matchAndRewrite(op, *this);
20164d52014SChris Lattner     }
202a32f0dcbSRiver Riddle 
203a32f0dcbSRiver Riddle     // After applying patterns, make sure that the CFG of each of the regions is
204a32f0dcbSRiver Riddle     // kept up to date.
2050ddba0bdSRiver Riddle     if (succeeded(simplifyRegions(regions))) {
2060ddba0bdSRiver Riddle       folder.clear();
2070ddba0bdSRiver Riddle       changed = true;
2080ddba0bdSRiver Riddle     }
2095c757087SFeng Liu   } while (changed && ++i < maxIterations);
2105c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2115c757087SFeng Liu   return !changed;
21264d52014SChris Lattner }
21364d52014SChris Lattner 
214e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
215e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
216e7a2ef21SRiver Riddle /// work-list driven manner. Return true if no more patterns can be matched in
217e7a2ef21SRiver Riddle /// the result operation regions.
218e7a2ef21SRiver Riddle /// Note: This does not apply patterns to the top-level operation itself.
21964d52014SChris Lattner ///
220a5b9316bSUday Bondhugula bool mlir::applyPatternsAndFoldGreedily(
221a5b9316bSUday Bondhugula     Operation *op, const OwningRewritePatternList &patterns) {
222a5b9316bSUday Bondhugula   return applyPatternsAndFoldGreedily(op->getRegions(), patterns);
2236b1cc3c6SRiver Riddle }
2246b1cc3c6SRiver Riddle 
2256b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
226a5b9316bSUday Bondhugula bool mlir::applyPatternsAndFoldGreedily(
227a5b9316bSUday Bondhugula     MutableArrayRef<Region> regions, const OwningRewritePatternList &patterns) {
2286b1cc3c6SRiver Riddle   if (regions.empty())
2296b1cc3c6SRiver Riddle     return true;
2306b1cc3c6SRiver Riddle 
231e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
232e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
233e7a2ef21SRiver Riddle   // the region containing 'op'.
2346b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
2356b1cc3c6SRiver Riddle     return region.getParentOp()->isKnownIsolatedFromAbove();
2366b1cc3c6SRiver Riddle   };
2376b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2386b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2396b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
240e7a2ef21SRiver Riddle 
2416b1cc3c6SRiver Riddle   // Start the pattern driver.
2426b1cc3c6SRiver Riddle   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns);
2436b1cc3c6SRiver Riddle   bool converged = driver.simplify(regions, maxPatternMatchIterations);
2445c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
245e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
2465c757087SFeng Liu                  << maxPatternMatchIterations << " times";
2475c757087SFeng Liu   });
2485c757087SFeng Liu   return converged;
24964d52014SChris Lattner }
25004b5274eSUday Bondhugula 
25104b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
25204b5274eSUday Bondhugula // OpPatternRewriteDriver
25304b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
25404b5274eSUday Bondhugula 
25504b5274eSUday Bondhugula namespace {
25604b5274eSUday Bondhugula /// This is a simple driver for the PatternMatcher to apply patterns and perform
25704b5274eSUday Bondhugula /// folding on a single op. It repeatedly applies locally optimal patterns.
25804b5274eSUday Bondhugula class OpPatternRewriteDriver : public PatternRewriter {
25904b5274eSUday Bondhugula public:
26004b5274eSUday Bondhugula   explicit OpPatternRewriteDriver(MLIRContext *ctx,
26104b5274eSUday Bondhugula                                   const OwningRewritePatternList &patterns)
26204b5274eSUday Bondhugula       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {}
26304b5274eSUday Bondhugula 
26404b5274eSUday Bondhugula   bool simplifyLocally(Operation *op, int maxIterations, bool &erased);
26504b5274eSUday Bondhugula 
26604b5274eSUday Bondhugula   // These are hooks implemented for PatternRewriter.
26704b5274eSUday Bondhugula protected:
26804b5274eSUday Bondhugula   /// If an operation is about to be removed, mark it so that we can let clients
26904b5274eSUday Bondhugula   /// know.
27004b5274eSUday Bondhugula   void notifyOperationRemoved(Operation *op) override {
27104b5274eSUday Bondhugula     opErasedViaPatternRewrites = true;
27204b5274eSUday Bondhugula   }
27304b5274eSUday Bondhugula 
27404b5274eSUday Bondhugula   // When a root is going to be replaced, its removal will be notified as well.
27504b5274eSUday Bondhugula   // So there is nothing to do here.
27604b5274eSUday Bondhugula   void notifyRootReplaced(Operation *op) override {}
27704b5274eSUday Bondhugula 
27804b5274eSUday Bondhugula private:
27904b5274eSUday Bondhugula   /// The low-level pattern matcher.
28004b5274eSUday Bondhugula   RewritePatternMatcher matcher;
28104b5274eSUday Bondhugula 
28204b5274eSUday Bondhugula   /// Non-pattern based folder for operations.
28304b5274eSUday Bondhugula   OperationFolder folder;
28404b5274eSUday Bondhugula 
28504b5274eSUday Bondhugula   /// Set to true if the operation has been erased via pattern rewrites.
28604b5274eSUday Bondhugula   bool opErasedViaPatternRewrites = false;
28704b5274eSUday Bondhugula };
28804b5274eSUday Bondhugula 
28904b5274eSUday Bondhugula } // anonymous namespace
29004b5274eSUday Bondhugula 
29104b5274eSUday Bondhugula /// Performs the rewrites and folding only on `op`. The simplification converges
29204b5274eSUday Bondhugula /// if the op is erased as a result of being folded, replaced, or dead, or no
29304b5274eSUday Bondhugula /// more changes happen in an iteration. Returns true if the rewrite converges
29404b5274eSUday Bondhugula /// in `maxIterations`. `erased` is set to true if `op` gets erased.
29504b5274eSUday Bondhugula bool OpPatternRewriteDriver::simplifyLocally(Operation *op, int maxIterations,
29604b5274eSUday Bondhugula                                              bool &erased) {
29704b5274eSUday Bondhugula   bool changed = false;
29804b5274eSUday Bondhugula   erased = false;
29904b5274eSUday Bondhugula   opErasedViaPatternRewrites = false;
30004b5274eSUday Bondhugula   int i = 0;
30104b5274eSUday Bondhugula   // Iterate until convergence or until maxIterations. Deletion of the op as
30204b5274eSUday Bondhugula   // a result of being dead or folded is convergence.
30304b5274eSUday Bondhugula   do {
30404b5274eSUday Bondhugula     // If the operation is trivially dead - remove it.
30504b5274eSUday Bondhugula     if (isOpTriviallyDead(op)) {
30604b5274eSUday Bondhugula       op->erase();
30704b5274eSUday Bondhugula       erased = true;
30804b5274eSUday Bondhugula       return true;
30904b5274eSUday Bondhugula     }
31004b5274eSUday Bondhugula 
31104b5274eSUday Bondhugula     // Try to fold this op.
31204b5274eSUday Bondhugula     bool inPlaceUpdate;
31304b5274eSUday Bondhugula     if (succeeded(folder.tryToFold(op, /*processGeneratedConstants=*/nullptr,
31404b5274eSUday Bondhugula                                    /*preReplaceAction=*/nullptr,
31504b5274eSUday Bondhugula                                    &inPlaceUpdate))) {
31604b5274eSUday Bondhugula       changed = true;
31704b5274eSUday Bondhugula       if (!inPlaceUpdate) {
31804b5274eSUday Bondhugula         erased = true;
31904b5274eSUday Bondhugula         return true;
32004b5274eSUday Bondhugula       }
32104b5274eSUday Bondhugula     }
32204b5274eSUday Bondhugula 
32304b5274eSUday Bondhugula     // Make sure that any new operations are inserted at this point.
32404b5274eSUday Bondhugula     setInsertionPoint(op);
32504b5274eSUday Bondhugula 
32604b5274eSUday Bondhugula     // Try to match one of the patterns. The rewriter is automatically
32704b5274eSUday Bondhugula     // notified of any necessary changes, so there is nothing else to do here.
32804b5274eSUday Bondhugula     changed |= matcher.matchAndRewrite(op, *this);
32904b5274eSUday Bondhugula     if ((erased = opErasedViaPatternRewrites))
33004b5274eSUday Bondhugula       return true;
33104b5274eSUday Bondhugula   } while (changed && ++i < maxIterations);
33204b5274eSUday Bondhugula 
33304b5274eSUday Bondhugula   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
33404b5274eSUday Bondhugula   return !changed;
33504b5274eSUday Bondhugula }
33604b5274eSUday Bondhugula 
33704b5274eSUday Bondhugula /// Rewrites only `op` using the supplied canonicalization patterns and
33804b5274eSUday Bondhugula /// folding. `erased` is set to true if the op is erased as a result of being
33904b5274eSUday Bondhugula /// folded, replaced, or dead.
34004b5274eSUday Bondhugula bool mlir::applyOpPatternsAndFold(Operation *op,
34104b5274eSUday Bondhugula                                   const OwningRewritePatternList &patterns,
34204b5274eSUday Bondhugula                                   bool *erased) {
34304b5274eSUday Bondhugula   // Start the pattern driver.
34404b5274eSUday Bondhugula   OpPatternRewriteDriver driver(op->getContext(), patterns);
34504b5274eSUday Bondhugula   bool opErased;
34604b5274eSUday Bondhugula   bool converged =
34704b5274eSUday Bondhugula       driver.simplifyLocally(op, maxPatternMatchIterations, opErased);
34804b5274eSUday Bondhugula   if (erased)
34904b5274eSUday Bondhugula     *erased = opErased;
35004b5274eSUday Bondhugula   LLVM_DEBUG(if (!converged) {
35104b5274eSUday Bondhugula     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
35204b5274eSUday Bondhugula                  << maxPatternMatchIterations << " times";
35304b5274eSUday Bondhugula   });
35404b5274eSUday Bondhugula   return converged;
35504b5274eSUday Bondhugula }
356