1 /* Copyright 2017 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/compiler/tf2xla/functionalize_control_flow_util.h"
17
18 #include "tensorflow/core/framework/node_def.pb.h"
19
20 namespace tensorflow {
21
operator ()(const Node * lhs,const Node * rhs) const22 bool NodeCmpByNameResourcesLast::operator()(const Node* lhs,
23 const Node* rhs) const {
24 bool lhs_is_resource =
25 lhs->num_inputs() > 0 ? (lhs->input_type(0) == DT_RESOURCE) : false;
26 bool rhs_is_resource =
27 rhs->num_inputs() > 0 ? (rhs->input_type(0) == DT_RESOURCE) : false;
28 return std::tie(lhs_is_resource, lhs->name()) <
29 std::tie(rhs_is_resource, rhs->name());
30 }
31
AddNodeDefToGraph(const NodeDef & node_def,Graph * graph)32 xla::StatusOr<Node*> AddNodeDefToGraph(const NodeDef& node_def, Graph* graph) {
33 Status status;
34 Node* inserted_node = graph->AddNode(node_def, &status);
35 if (!status.ok()) {
36 return status;
37 }
38 return inserted_node;
39 }
40
BuildRetvalNode(Graph * graph,DataType type,int index)41 xla::StatusOr<Node*> BuildRetvalNode(Graph* graph, DataType type, int index) {
42 const char* const kRetValOp = "_Retval";
43 NodeDef ret_def;
44 ret_def.set_op(kRetValOp);
45 ret_def.set_name(absl::StrCat(kRetValOp, index));
46 AddNodeAttr("T", type, &ret_def);
47 AddNodeAttr("index", index, &ret_def);
48 return AddNodeDefToGraph(ret_def, graph);
49 }
50
51 // Check that the graph has no cycle containing the given node.
CheckNodeNotInCycle(const Node * node,const int num_nodes)52 Status CheckNodeNotInCycle(const Node* node, const int num_nodes) {
53 std::vector<const Node*> ready;
54 ready.push_back(node);
55 std::vector<bool> visited(num_nodes);
56 while (!ready.empty()) {
57 const Node* current_node = ready.back();
58 ready.pop_back();
59 visited[current_node->id()] = true;
60 for (const Edge* out : current_node->out_edges()) {
61 if (out->dst() == node) {
62 return errors::Internal("Detected a cycle: ", FormatNodeForError(*node),
63 " (", node->def().op(), ") feeds into itself.");
64 } else if (!visited[out->dst()->id()]) {
65 ready.push_back(out->dst());
66 }
67 }
68 }
69 return Status::OK();
70 }
71
72 } // namespace tensorflow
73