xref: /llvm-project/mlir/lib/Dialect/EmitC/Transforms/FormExpressions.cpp (revision 09dfc5713d7e2342bea4c8447d1ed76c85eb8225)
1 //===- FormExpressions.cpp - Form C-style expressions --------*- C++ -*-===//
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 file implements a pass that forms EmitC operations modeling C operators
10 // into C-style expressions using the emitc.expression op.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/EmitC/IR/EmitC.h"
15 #include "mlir/Dialect/EmitC/Transforms/Passes.h"
16 #include "mlir/Dialect/EmitC/Transforms/Transforms.h"
17 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
18 
19 namespace mlir {
20 namespace emitc {
21 #define GEN_PASS_DEF_FORMEXPRESSIONS
22 #include "mlir/Dialect/EmitC/Transforms/Passes.h.inc"
23 } // namespace emitc
24 } // namespace mlir
25 
26 using namespace mlir;
27 using namespace emitc;
28 
29 namespace {
30 struct FormExpressionsPass
31     : public emitc::impl::FormExpressionsBase<FormExpressionsPass> {
32   void runOnOperation() override {
33     Operation *rootOp = getOperation();
34     MLIRContext *context = rootOp->getContext();
35 
36     // Wrap each C operator op with an expression op.
37     OpBuilder builder(context);
38     auto matchFun = [&](Operation *op) {
39       if (op->hasTrait<OpTrait::emitc::CExpression>() &&
40           !op->getParentOfType<emitc::ExpressionOp>() &&
41           op->getNumResults() == 1)
42         createExpression(op, builder);
43     };
44     rootOp->walk(matchFun);
45 
46     // Fold expressions where possible.
47     RewritePatternSet patterns(context);
48     populateExpressionPatterns(patterns);
49 
50     if (failed(applyPatternsGreedily(rootOp, std::move(patterns))))
51       return signalPassFailure();
52   }
53 
54   void getDependentDialects(DialectRegistry &registry) const override {
55     registry.insert<emitc::EmitCDialect>();
56   }
57 };
58 } // namespace
59 
60 std::unique_ptr<Pass> mlir::emitc::createFormExpressionsPass() {
61   return std::make_unique<FormExpressionsPass>();
62 }
63