1 //===- Canonicalizer.cpp - Canonicalize MLIR operations -------------------===//
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 transformation pass converts operations into their canonical forms by
19 // folding constants, applying operation identity transformations etc.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "mlir/IR/MLIRContext.h"
24 #include "mlir/IR/PatternMatch.h"
25 #include "mlir/Pass/Pass.h"
26 #include "mlir/Transforms/Passes.h"
27 using namespace mlir;
28 
29 //===----------------------------------------------------------------------===//
30 // The actual Canonicalizer Pass.
31 //===----------------------------------------------------------------------===//
32 
33 namespace {
34 
35 /// Canonicalize operations in functions.
36 struct Canonicalizer : public FunctionPass<Canonicalizer> {
37   void runOnFunction() override;
38 };
39 } // end anonymous namespace
40 
41 void Canonicalizer::runOnFunction() {
42   OwningRewritePatternList patterns;
43   auto func = getFunction();
44 
45   // TODO: Instead of adding all known patterns from the whole system lazily add
46   // and cache the canonicalization patterns for ops we see in practice when
47   // building the worklist.  For now, we just grab everything.
48   auto *context = &getContext();
49   for (auto *op : context->getRegisteredOperations())
50     op->getCanonicalizationPatterns(patterns, context);
51 
52   applyPatternsGreedily(func, patterns);
53 }
54 
55 /// Create a Canonicalizer pass.
56 std::unique_ptr<FunctionPassBase> mlir::createCanonicalizerPass() {
57   return std::make_unique<Canonicalizer>();
58 }
59 
60 static PassRegistration<Canonicalizer> pass("canonicalize",
61                                             "Canonicalize operations");
62