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/xla/service/flatten_call_graph.h"
17 
18 #include "tensorflow/compiler/xla/service/call_graph.h"
19 #include "tensorflow/compiler/xla/service/hlo_computation.h"
20 #include "tensorflow/compiler/xla/service/hlo_instruction.h"
21 #include "tensorflow/compiler/xla/service/hlo_module.h"
22 #include "tensorflow/compiler/xla/util.h"
23 #include "tensorflow/core/lib/core/errors.h"
24 
25 namespace xla {
26 
27 namespace {
28 
29 // Helper to replace the called computation at a while-, call-, case-, or
30 // conditional-instruction. This function replaces exactly one instance of
31 // 'computation' with 'new_computation' even if 'instruction' calls
32 // 'computation' more than once.
ReplaceCalledComputation(HloInstruction * instruction,HloComputation * computation,HloComputation * new_computation)33 void ReplaceCalledComputation(HloInstruction* instruction,
34                               HloComputation* computation,
35                               HloComputation* new_computation) {
36   switch (instruction->opcode()) {
37     case HloOpcode::kWhile: {
38       if (computation == instruction->while_condition()) {
39         instruction->set_while_condition(new_computation);
40       } else {
41         CHECK_EQ(computation, instruction->while_body());
42         instruction->set_while_body(new_computation);
43       }
44       break;
45     }
46     case HloOpcode::kCall: {
47       CHECK_EQ(instruction->to_apply(), computation);
48       instruction->set_to_apply(new_computation);
49       break;
50     }
51     case HloOpcode::kConditional: {
52       for (int b = 0; b < instruction->branch_count(); ++b) {
53         if (b == instruction->branch_count() - 1) {
54           CHECK_EQ(computation, instruction->branch_computation(b));
55         }
56         if (computation == instruction->branch_computation(b)) {
57           instruction->set_branch_computation(b, new_computation);
58           break;
59         }
60       }
61       break;
62     }
63     default:
64       LOG(FATAL) << "unexpected opcode: "
65                  << HloOpcodeString(instruction->opcode());
66   }
67 }
68 
69 // Flatten a single call graph node. Expects to visit nodes in postorder.
FlattenNode(const CallGraphNode & node)70 Status FlattenNode(const CallGraphNode& node) {
71   HloComputation* computation = node.computation();
72   HloModule* module = computation->parent();
73   // Clone callee for all call-sites except the first one.
74   for (int i = 0; i < node.caller_callsites().size(); ++i) {
75     CallSite call_site = node.caller_callsites()[i];
76     // Only consider sequential call contexts.
77     if (call_site.context() == CallContext::kParallel) {
78       continue;
79     }
80     CHECK_EQ(call_site.context(), CallContext::kSequential);
81 
82     // Skip first element if this computation is only called from a sequential
83     // context.
84     if (node.context() != CallContext::kBoth && i == 0) {
85       continue;
86     }
87 
88     // Clone computation for the remaining sequential context call sites.
89     HloComputation* clone =
90         module->AddEmbeddedComputation(computation->Clone());
91     ReplaceCalledComputation(call_site.instruction(), computation, clone);
92     // Clone the sub-tree of all computations called from this node.
93     std::vector<HloComputation*> worklist;
94     worklist.push_back(clone);
95     while (!worklist.empty()) {
96       auto current = worklist.back();
97       worklist.pop_back();
98       for (auto* instruction : current->instructions()) {
99         if (GetInstructionCallContext(instruction->opcode()) !=
100             CallContext::kSequential) {
101           continue;
102         }
103         for (auto callee : instruction->called_computations()) {
104           HloComputation* callee_clone =
105               module->AddEmbeddedComputation(callee->Clone());
106           ReplaceCalledComputation(instruction, callee, callee_clone);
107           worklist.push_back(callee_clone);
108         }
109       }
110     }
111   }
112   return Status::OK();
113 }
114 
115 }  // namespace
116 
Run(HloModule * module)117 StatusOr<bool> FlattenCallGraph::Run(HloModule* module) {
118   XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString());
119 
120   std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module);
121   TF_RETURN_IF_ERROR(call_graph->VisitNodes(FlattenNode));
122 
123   XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString());
124   return true;
125 }
126 
127 }  // namespace xla
128