1 // Copyright (c) 2017 Google Inc.
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 <iostream>
16 #include <memory>
17 #include <set>
18
19 #include "source/cfa.h"
20 #include "source/opt/dominator_tree.h"
21 #include "source/opt/ir_context.h"
22
23 // Calculates the dominator or postdominator tree for a given function.
24 // 1 - Compute the successors and predecessors for each BasicBlock. We add a
25 // placeholder node for the start node or for postdominators the exit. This node
26 // will point to all entry or all exit nodes.
27 // 2 - Using the CFA::DepthFirstTraversal get a depth first postordered list of
28 // all BasicBlocks. Using the successors (or for postdominator, predecessors)
29 // calculated in step 1 to traverse the tree.
30 // 3 - Pass the list calculated in step 2 to the CFA::CalculateDominators using
31 // the predecessors list (or for postdominator, successors). This will give us a
32 // vector of BB pairs. Each BB and its immediate dominator.
33 // 4 - Using the list from 3 use those edges to build a tree of
34 // DominatorTreeNodes. Each node containing a link to the parent dominator and
35 // children which are dominated.
36 // 5 - Using the tree from 4, perform a depth first traversal to calculate the
37 // preorder and postorder index of each node. We use these indexes to compare
38 // nodes against each other for domination checks.
39
40 namespace spvtools {
41 namespace opt {
42 namespace {
43
44 // Wrapper around CFA::DepthFirstTraversal to provide an interface to perform
45 // depth first search on generic BasicBlock types. Will call post and pre order
46 // user defined functions during traversal
47 //
48 // BBType - BasicBlock type. Will either be BasicBlock or DominatorTreeNode
49 // SuccessorLambda - Lamdba matching the signature of 'const
50 // std::vector<BBType>*(const BBType *A)'. Will return a vector of the nodes
51 // succeeding BasicBlock A.
52 // PostLambda - Lamdba matching the signature of 'void (const BBType*)' will be
53 // called on each node traversed AFTER their children.
54 // PreLambda - Lamdba matching the signature of 'void (const BBType*)' will be
55 // called on each node traversed BEFORE their children.
56 template <typename BBType, typename SuccessorLambda, typename PreLambda,
57 typename PostLambda>
DepthFirstSearch(const BBType * bb,SuccessorLambda successors,PreLambda pre,PostLambda post)58 static void DepthFirstSearch(const BBType* bb, SuccessorLambda successors,
59 PreLambda pre, PostLambda post) {
60 auto no_terminal_blocks = [](const BBType*) { return false; };
61 CFA<BBType>::DepthFirstTraversal(bb, successors, pre, post,
62 no_terminal_blocks);
63 }
64
65 // Wrapper around CFA::DepthFirstTraversal to provide an interface to perform
66 // depth first search on generic BasicBlock types. This overload is for only
67 // performing user defined post order.
68 //
69 // BBType - BasicBlock type. Will either be BasicBlock or DominatorTreeNode
70 // SuccessorLambda - Lamdba matching the signature of 'const
71 // std::vector<BBType>*(const BBType *A)'. Will return a vector of the nodes
72 // succeeding BasicBlock A.
73 // PostLambda - Lamdba matching the signature of 'void (const BBType*)' will be
74 // called on each node traversed after their children.
75 template <typename BBType, typename SuccessorLambda, typename PostLambda>
DepthFirstSearchPostOrder(const BBType * bb,SuccessorLambda successors,PostLambda post)76 static void DepthFirstSearchPostOrder(const BBType* bb,
77 SuccessorLambda successors,
78 PostLambda post) {
79 // Ignore preorder operation.
80 auto nop_preorder = [](const BBType*) {};
81 DepthFirstSearch(bb, successors, nop_preorder, post);
82 }
83
84 // Small type trait to get the function class type.
85 template <typename BBType>
86 struct GetFunctionClass {
87 using FunctionType = Function;
88 };
89
90 // Helper class to compute predecessors and successors for each Basic Block in a
91 // function. Through GetPredFunctor and GetSuccessorFunctor it provides an
92 // interface to get the successor and predecessor lists for each basic
93 // block. This is required by the DepthFirstTraversal and ComputeDominator
94 // functions which take as parameter an std::function returning the successors
95 // and predecessors respectively.
96 //
97 // When computing the post-dominator tree, all edges are inverted. So successors
98 // returned by this class will be predecessors in the original CFG.
99 template <typename BBType>
100 class BasicBlockSuccessorHelper {
101 // This should eventually become const BasicBlock.
102 using BasicBlock = BBType;
103 using Function = typename GetFunctionClass<BBType>::FunctionType;
104
105 using BasicBlockListTy = std::vector<BasicBlock*>;
106 using BasicBlockMapTy =
107 std::unordered_map<const BasicBlock*, BasicBlockListTy>;
108
109 public:
110 // For compliance with the dominance tree computation, entry nodes are
111 // connected to a single placeholder node.
112 BasicBlockSuccessorHelper(Function& func,
113 const BasicBlock* placeholder_start_node,
114 bool post);
115
116 // CFA::CalculateDominators requires std::vector<BasicBlock*>.
117 using GetBlocksFunction =
118 std::function<const std::vector<BasicBlock*>*(const BasicBlock*)>;
119
120 // Returns the list of predecessor functions.
GetPredFunctor()121 GetBlocksFunction GetPredFunctor() {
122 return [this](const BasicBlock* bb) {
123 BasicBlockListTy* v = &this->predecessors_[bb];
124 return v;
125 };
126 }
127
128 // Returns a vector of the list of successor nodes from a given node.
GetSuccessorFunctor()129 GetBlocksFunction GetSuccessorFunctor() {
130 return [this](const BasicBlock* bb) {
131 BasicBlockListTy* v = &this->successors_[bb];
132 return v;
133 };
134 }
135
136 private:
137 bool invert_graph_;
138 BasicBlockMapTy successors_;
139 BasicBlockMapTy predecessors_;
140
141 // Build the successors and predecessors map for each basic blocks |f|.
142 // If |invert_graph_| is true, all edges are reversed (successors becomes
143 // predecessors and vice versa).
144 // For convenience, the start of the graph is |placeholder_start_node|.
145 // The dominator tree construction requires a unique entry node, which cannot
146 // be guaranteed for the postdominator graph. The |placeholder_start_node| BB
147 // is here to gather all entry nodes.
148 void CreateSuccessorMap(Function& f,
149 const BasicBlock* placeholder_start_node);
150 };
151
152 template <typename BBType>
BasicBlockSuccessorHelper(Function & func,const BasicBlock * placeholder_start_node,bool invert)153 BasicBlockSuccessorHelper<BBType>::BasicBlockSuccessorHelper(
154 Function& func, const BasicBlock* placeholder_start_node, bool invert)
155 : invert_graph_(invert) {
156 CreateSuccessorMap(func, placeholder_start_node);
157 }
158
159 template <typename BBType>
CreateSuccessorMap(Function & f,const BasicBlock * placeholder_start_node)160 void BasicBlockSuccessorHelper<BBType>::CreateSuccessorMap(
161 Function& f, const BasicBlock* placeholder_start_node) {
162 IRContext* context = f.DefInst().context();
163
164 if (invert_graph_) {
165 // For the post dominator tree, we see the inverted graph.
166 // successors_ in the inverted graph are the predecessors in the CFG.
167 // The tree construction requires 1 entry point, so we add a placeholder
168 // node that is connected to all function exiting basic blocks. An exiting
169 // basic block is a block with an OpKill, OpUnreachable, OpReturn,
170 // OpReturnValue, or OpTerminateInvocation as terminator instruction.
171 for (BasicBlock& bb : f) {
172 if (bb.hasSuccessor()) {
173 BasicBlockListTy& pred_list = predecessors_[&bb];
174 const auto& const_bb = bb;
175 const_bb.ForEachSuccessorLabel(
176 [this, &pred_list, &bb, context](const uint32_t successor_id) {
177 BasicBlock* succ = context->get_instr_block(successor_id);
178 // Inverted graph: our successors in the CFG
179 // are our predecessors in the inverted graph.
180 this->successors_[succ].push_back(&bb);
181 pred_list.push_back(succ);
182 });
183 } else {
184 successors_[placeholder_start_node].push_back(&bb);
185 predecessors_[&bb].push_back(
186 const_cast<BasicBlock*>(placeholder_start_node));
187 }
188 }
189 } else {
190 successors_[placeholder_start_node].push_back(f.entry().get());
191 predecessors_[f.entry().get()].push_back(
192 const_cast<BasicBlock*>(placeholder_start_node));
193 for (BasicBlock& bb : f) {
194 BasicBlockListTy& succ_list = successors_[&bb];
195
196 const auto& const_bb = bb;
197 const_bb.ForEachSuccessorLabel([&](const uint32_t successor_id) {
198 BasicBlock* succ = context->get_instr_block(successor_id);
199 succ_list.push_back(succ);
200 predecessors_[succ].push_back(&bb);
201 });
202 }
203 }
204 }
205
206 } // namespace
207
StrictlyDominates(uint32_t a,uint32_t b) const208 bool DominatorTree::StrictlyDominates(uint32_t a, uint32_t b) const {
209 if (a == b) return false;
210 return Dominates(a, b);
211 }
212
StrictlyDominates(const BasicBlock * a,const BasicBlock * b) const213 bool DominatorTree::StrictlyDominates(const BasicBlock* a,
214 const BasicBlock* b) const {
215 return DominatorTree::StrictlyDominates(a->id(), b->id());
216 }
217
StrictlyDominates(const DominatorTreeNode * a,const DominatorTreeNode * b) const218 bool DominatorTree::StrictlyDominates(const DominatorTreeNode* a,
219 const DominatorTreeNode* b) const {
220 if (a == b) return false;
221 return Dominates(a, b);
222 }
223
Dominates(uint32_t a,uint32_t b) const224 bool DominatorTree::Dominates(uint32_t a, uint32_t b) const {
225 // Check that both of the inputs are actual nodes.
226 const DominatorTreeNode* a_node = GetTreeNode(a);
227 const DominatorTreeNode* b_node = GetTreeNode(b);
228 if (!a_node || !b_node) return false;
229
230 return Dominates(a_node, b_node);
231 }
232
Dominates(const DominatorTreeNode * a,const DominatorTreeNode * b) const233 bool DominatorTree::Dominates(const DominatorTreeNode* a,
234 const DominatorTreeNode* b) const {
235 if (!a || !b) return false;
236 // Node A dominates node B if they are the same.
237 if (a == b) return true;
238
239 return a->dfs_num_pre_ < b->dfs_num_pre_ &&
240 a->dfs_num_post_ > b->dfs_num_post_;
241 }
242
Dominates(const BasicBlock * A,const BasicBlock * B) const243 bool DominatorTree::Dominates(const BasicBlock* A, const BasicBlock* B) const {
244 return Dominates(A->id(), B->id());
245 }
246
ImmediateDominator(const BasicBlock * A) const247 BasicBlock* DominatorTree::ImmediateDominator(const BasicBlock* A) const {
248 return ImmediateDominator(A->id());
249 }
250
ImmediateDominator(uint32_t a) const251 BasicBlock* DominatorTree::ImmediateDominator(uint32_t a) const {
252 // Check that A is a valid node in the tree.
253 auto a_itr = nodes_.find(a);
254 if (a_itr == nodes_.end()) return nullptr;
255
256 const DominatorTreeNode* node = &a_itr->second;
257
258 if (node->parent_ == nullptr) {
259 return nullptr;
260 }
261
262 return node->parent_->bb_;
263 }
264
GetOrInsertNode(BasicBlock * bb)265 DominatorTreeNode* DominatorTree::GetOrInsertNode(BasicBlock* bb) {
266 DominatorTreeNode* dtn = nullptr;
267
268 std::map<uint32_t, DominatorTreeNode>::iterator node_iter =
269 nodes_.find(bb->id());
270 if (node_iter == nodes_.end()) {
271 dtn = &nodes_.emplace(std::make_pair(bb->id(), DominatorTreeNode{bb}))
272 .first->second;
273 } else {
274 dtn = &node_iter->second;
275 }
276
277 return dtn;
278 }
279
GetDominatorEdges(const Function * f,const BasicBlock * placeholder_start_node,std::vector<std::pair<BasicBlock *,BasicBlock * >> * edges)280 void DominatorTree::GetDominatorEdges(
281 const Function* f, const BasicBlock* placeholder_start_node,
282 std::vector<std::pair<BasicBlock*, BasicBlock*>>* edges) {
283 // Each time the depth first traversal calls the postorder callback
284 // std::function we push that node into the postorder vector to create our
285 // postorder list.
286 std::vector<const BasicBlock*> postorder;
287 auto postorder_function = [&](const BasicBlock* b) {
288 postorder.push_back(b);
289 };
290
291 // CFA::CalculateDominators requires std::vector<BasicBlock*>
292 // BB are derived from F, so we need to const cast it at some point
293 // no modification is made on F.
294 BasicBlockSuccessorHelper<BasicBlock> helper{
295 *const_cast<Function*>(f), placeholder_start_node, postdominator_};
296
297 // The successor function tells DepthFirstTraversal how to move to successive
298 // nodes by providing an interface to get a list of successor nodes from any
299 // given node.
300 auto successor_functor = helper.GetSuccessorFunctor();
301
302 // The predecessor functor does the same as the successor functor
303 // but for all nodes preceding a given node.
304 auto predecessor_functor = helper.GetPredFunctor();
305
306 // If we're building a post dominator tree we traverse the tree in reverse
307 // using the predecessor function in place of the successor function and vice
308 // versa.
309 DepthFirstSearchPostOrder(placeholder_start_node, successor_functor,
310 postorder_function);
311 *edges = CFA<BasicBlock>::CalculateDominators(postorder, predecessor_functor);
312 }
313
InitializeTree(const CFG & cfg,const Function * f)314 void DominatorTree::InitializeTree(const CFG& cfg, const Function* f) {
315 ClearTree();
316
317 // Skip over empty functions.
318 if (f->cbegin() == f->cend()) {
319 return;
320 }
321
322 const BasicBlock* placeholder_start_node =
323 postdominator_ ? cfg.pseudo_exit_block() : cfg.pseudo_entry_block();
324
325 // Get the immediate dominator for each node.
326 std::vector<std::pair<BasicBlock*, BasicBlock*>> edges;
327 GetDominatorEdges(f, placeholder_start_node, &edges);
328
329 // Transform the vector<pair> into the tree structure which we can use to
330 // efficiently query dominance.
331 for (auto edge : edges) {
332 DominatorTreeNode* first = GetOrInsertNode(edge.first);
333
334 if (edge.first == edge.second) {
335 if (std::find(roots_.begin(), roots_.end(), first) == roots_.end())
336 roots_.push_back(first);
337 continue;
338 }
339
340 DominatorTreeNode* second = GetOrInsertNode(edge.second);
341
342 first->parent_ = second;
343 second->children_.push_back(first);
344 }
345 ResetDFNumbering();
346 }
347
ResetDFNumbering()348 void DominatorTree::ResetDFNumbering() {
349 int index = 0;
350 auto preFunc = [&index](const DominatorTreeNode* node) {
351 const_cast<DominatorTreeNode*>(node)->dfs_num_pre_ = ++index;
352 };
353
354 auto postFunc = [&index](const DominatorTreeNode* node) {
355 const_cast<DominatorTreeNode*>(node)->dfs_num_post_ = ++index;
356 };
357
358 auto getSucc = [](const DominatorTreeNode* node) { return &node->children_; };
359
360 for (auto root : roots_) DepthFirstSearch(root, getSucc, preFunc, postFunc);
361 }
362
DumpTreeAsDot(std::ostream & out_stream) const363 void DominatorTree::DumpTreeAsDot(std::ostream& out_stream) const {
364 out_stream << "digraph {\n";
365 Visit([&out_stream](const DominatorTreeNode* node) {
366 // Print the node.
367 if (node->bb_) {
368 out_stream << node->bb_->id() << "[label=\"" << node->bb_->id()
369 << "\"];\n";
370 }
371
372 // Print the arrow from the parent to this node. Entry nodes will not have
373 // parents so draw them as children from the placeholder node.
374 if (node->parent_) {
375 out_stream << node->parent_->bb_->id() << " -> " << node->bb_->id()
376 << ";\n";
377 }
378
379 // Return true to continue the traversal.
380 return true;
381 });
382 out_stream << "}\n";
383 }
384
385 } // namespace opt
386 } // namespace spvtools
387