1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include <memory>
16 #include <tuple>
17 
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Casting.h"
20 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
21 #include "mlir/IR/Block.h"  // from @llvm-project
22 #include "mlir/IR/BuiltinOps.h"  // from @llvm-project
23 #include "mlir/IR/Diagnostics.h"  // from @llvm-project
24 #include "mlir/IR/OpDefinition.h"  // from @llvm-project
25 #include "mlir/IR/Operation.h"  // from @llvm-project
26 #include "mlir/IR/Types.h"  // from @llvm-project
27 #include "mlir/IR/Value.h"  // from @llvm-project
28 #include "mlir/Parser/Parser.h"  // from @llvm-project
29 #include "mlir/Pass/Pass.h"  // from @llvm-project
30 #include "mlir/Pass/PassRegistry.h"  // from @llvm-project
31 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
32 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h"
33 
34 #define DEBUG_TYPE "tf-materialize-passthrough-op"
35 
36 namespace mlir {
37 namespace {
38 
39 class MaterializePassthroughOpPass
40     : public TF::MaterializePassthroughOpBase<MaterializePassthroughOpPass> {
41  public:
42   void runOnOperation() override;
43 };
44 
runOnOperation()45 void MaterializePassthroughOpPass::runOnOperation() {
46   getOperation().walk([](Operation *op) {
47     auto passthrough_op = dyn_cast<TF::MlirPassthroughOp>(op);
48     if (!passthrough_op) return;
49     std::string module_string(passthrough_op.mlir_module());
50     // Parse the module.
51     auto nested_module =
52         parseSourceString<ModuleOp>(module_string, op->getContext());
53     if (!nested_module) {
54       op->emitError() << "could not parse attached MLIR module";
55       return;
56     }
57     func::FuncOp main =
58         dyn_cast<func::FuncOp>(nested_module->lookupSymbol("main"));
59     if (!main) {
60       op->emitError() << "MLIR Opaque Op expects a main() entry point\n";
61       return;
62     }
63     if (main.getNumArguments() != op->getNumOperands()) {
64       op->emitError() << "mismatch between MLIR Opaque Op number of operands ("
65                       << op->getNumOperands()
66                       << ") and main() entry point in the module ("
67                       << main.getNumArguments() << " args)\n";
68       return;
69     }
70     if (main.getFunctionType().getNumResults() != op->getNumResults()) {
71       op->emitError() << "mismatch between MLIR Opaque Op number of results ("
72                       << op->getNumResults()
73                       << ") and main() entry point in the module ("
74                       << main.getFunctionType().getNumResults()
75                       << " results)\n";
76       return;
77     }
78     Region &body = main.getBody();
79     if (!llvm::hasSingleElement(body)) {
80       op->emitError() << "MLIR Opaque Op expects a main() entry point with a "
81                          "single block\n";
82       return;
83     }
84     Block &block = body.front();
85     for (const auto &arg_mapping :
86          llvm::zip(block.getArguments(), op->getOperands())) {
87       std::get<0>(arg_mapping).replaceAllUsesWith(std::get<1>(arg_mapping));
88     }
89     op->getBlock()->getOperations().splice(op->getIterator(),
90                                            block.getOperations(), block.begin(),
91                                            std::prev(block.end()));
92     Operation &return_op = block.front();
93     for (auto ret_mapping :
94          llvm::zip(op->getResults(), return_op.getOperands())) {
95       std::get<0>(ret_mapping).replaceAllUsesWith(std::get<1>(ret_mapping));
96     }
97     op->erase();
98   });
99 }
100 
101 }  // namespace
102 
103 namespace TF {
104 std::unique_ptr<OperationPass<func::FuncOp>>
CreateMaterializePassthroughOpPass()105 CreateMaterializePassthroughOpPass() {
106   return std::make_unique<MaterializePassthroughOpPass>();
107 }
108 }  // namespace TF
109 
110 }  // namespace mlir
111