xref: /aosp_15_r20/external/tensorflow/tensorflow/core/transforms/func_to_graph/pass.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2022 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 
16 #include "tensorflow/core/transforms/func_to_graph/pass.h"
17 
18 #include "mlir/IR/BuiltinAttributes.h"  // from @llvm-project
19 #include "mlir/IR/SymbolTable.h"  // from @llvm-project
20 #include "mlir/Pass/Pass.h"  // from @llvm-project
21 #include "tensorflow/core/ir/ops.h"
22 #include "tensorflow/core/transforms/func_to_graph/func_to_graph.h"
23 #include "tensorflow/core/transforms/pass_detail.h"
24 
25 namespace mlir {
26 namespace tfg {
27 namespace {
28 class FuncToGraphPass : public FuncToGraphBase<FuncToGraphPass> {
29  public:
30   FuncToGraphPass() = default;
31 
32   // This will try to lower the function that has attribute
33   // `tfg.lifted_graph_version` to a graph. It replaces all the uses of
34   // arguments with related op results. The relation between args and ops is
35   // identified by the tfg.name attr. The arg's tfg.name attr will be prefixed
36   // with the related op's tfg.name. Besides, The ReturnOp will be dropped
37   // directly.
38   void runOnOperation() override;
39 };
40 }  // namespace
41 
runOnOperation()42 void FuncToGraphPass::runOnOperation() {
43   ModuleOp module = getOperation();
44 
45   auto *dialect = getContext().getLoadedDialect<TFGraphDialect>();
46   StringAttr lifted_graph_func_name =
47       dialect->getLiftedGraphFuncNameAttrIdentifier();
48 
49   GraphFuncOp lifted_graph_func;
50   for (auto func : module.getOps<GraphFuncOp>()) {
51     if (func.sym_name() == lifted_graph_func_name) {
52       lifted_graph_func = func;
53       break;
54     }
55   }
56 
57   if (!lifted_graph_func) return;
58 
59   auto status = FuncToGraph(lifted_graph_func);
60   if (!status.ok()) {
61     emitError(lifted_graph_func.getLoc())
62         << "FuncToGraph failed: " << status.error_message();
63     signalPassFailure();
64   }
65 }
66 
CreateFuncToGraphPass()67 std::unique_ptr<Pass> CreateFuncToGraphPass() {
68   return std::make_unique<FuncToGraphPass>();
69 }
70 
71 }  // namespace tfg
72 }  // namespace mlir
73