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 "mlir/IR/MLIRContext.h" 15 #include "mlir/IR/PatternMatch.h" 16 #include "mlir/Pass/Pass.h" 17 #include "mlir/Transforms/Passes.h" 18 using namespace mlir; 19 20 namespace { 21 /// Canonicalize operations in nested regions. 22 struct Canonicalizer : public OperationPass<Canonicalizer> { 23 void runOnOperation() override { 24 OwningRewritePatternList patterns; 25 26 // TODO: Instead of adding all known patterns from the whole system lazily 27 // add and cache the canonicalization patterns for ops we see in practice 28 // when building the worklist. For now, we just grab everything. 29 auto *context = &getContext(); 30 for (auto *op : context->getRegisteredOperations()) 31 op->getCanonicalizationPatterns(patterns, context); 32 33 Operation *op = getOperation(); 34 applyPatternsGreedily(op->getRegions(), patterns); 35 } 36 }; 37 } // end anonymous namespace 38 39 /// Create a Canonicalizer pass. 40 std::unique_ptr<Pass> mlir::createCanonicalizerPass() { 41 return std::make_unique<Canonicalizer>(); 42 } 43 44 static PassRegistration<Canonicalizer> pass("canonicalize", 45 "Canonicalize operations"); 46