1 //===- Canonicalizer.cpp - Canonicalize MLIR operations -------------------===//
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 transformation pass converts operations into their canonical forms by
10 // folding constants, applying operation identity transformations etc.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/Pass/Pass.h"
16 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
17 #include "mlir/Transforms/Passes.h"
18 
19 using namespace mlir;
20 
21 namespace {
22 /// Canonicalize operations in nested regions.
23 struct Canonicalizer : public CanonicalizerBase<Canonicalizer> {
24   /// Initialize the canonicalizer by building the set of patterns used during
25   /// execution.
26   LogicalResult initialize(MLIRContext *context) override {
27     RewritePatternSet owningPatterns(context);
28     for (auto *op : context->getRegisteredOperations())
29       op->getCanonicalizationPatterns(owningPatterns, context);
30     patterns = std::move(owningPatterns);
31     return success();
32   }
33   void runOnOperation() override {
34     (void)applyPatternsAndFoldGreedily(
35         getOperation()->getRegions(), patterns,
36         /*maxIterations=*/10, /*useTopDownTraversal=*/
37         topDownProcessingEnabled);
38   }
39 
40   FrozenRewritePatternSet patterns;
41 };
42 } // end anonymous namespace
43 
44 /// Create a Canonicalizer pass.
45 std::unique_ptr<Pass> mlir::createCanonicalizerPass() {
46   return std::make_unique<Canonicalizer>();
47 }
48