LLVM 24.0.0git
GenericDomTreeConstruction.h
Go to the documentation of this file.
1//===- GenericDomTreeConstruction.h - Dominator Calculation ------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// Generic dominator tree construction - this file provides routines to
11/// construct immediate dominator information for a flow-graph based on the
12/// Semi-NCA algorithm described in this dissertation:
13///
14/// [1] Linear-Time Algorithms for Dominators and Related Problems
15/// Loukas Georgiadis, Princeton University, November 2005, pp. 21-23:
16/// ftp://ftp.cs.princeton.edu/reports/2005/737.pdf
17///
18/// Semi-NCA algorithm runs in O(n^2) worst-case time but usually slightly
19/// faster than Simple Lengauer-Tarjan in practice.
20///
21/// O(n^2) worst cases happen when the computation of nearest common ancestors
22/// requires O(n) average time, which is very unlikely in real world. If this
23/// ever turns out to be an issue, consider implementing a hybrid algorithm
24/// that uses SLT to perform full constructions and SemiNCA for incremental
25/// updates.
26///
27/// The file uses the Depth Based Search algorithm to perform incremental
28/// updates (insertion and deletions). The implemented algorithm is based on
29/// this publication:
30///
31/// [2] An Experimental Study of Dynamic Dominators
32/// Loukas Georgiadis, et al., April 12 2016, pp. 5-7, 9-10:
33/// https://arxiv.org/pdf/1604.02711.pdf
34///
35//===----------------------------------------------------------------------===//
36
37#ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
38#define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
39
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseSet.h"
44#include "llvm/Support/Debug.h"
46#include <optional>
47#include <queue>
48
49#define DEBUG_TYPE "dom-tree-builder"
50
51namespace llvm {
52namespace DomTreeBuilder {
53
54template <typename DomTreeT> struct SemiNCAInfo {
55 using NodePtr = typename DomTreeT::NodePtr;
56 using NodeT = typename DomTreeT::NodeType;
58 using RootsT = decltype(DomTreeT::Roots);
59 static constexpr bool IsPostDom = DomTreeT::IsPostDominator;
61
62 // Marks a node that hasn't been visited by DFS.
63 static constexpr unsigned Unvisited = 0;
64
65 // Trivially-copyable record used by Semi-NCA during tree construction.
66 // DFSNumPlus1 is the DFS number + 1, so a zeroed InfoRec is unvisited.
67 struct InfoRec {
68 unsigned DFSNumPlus1 = 0;
69 unsigned Parent = 0;
70 unsigned Semi = 0;
71 unsigned Label = 0;
72 NodePtr IDom = nullptr;
73 // Head index + 1 into ReverseChildren; 0: empty list.
75 };
76
77 // Map a 0-based DFS number to the node. 0 is the DFS root, or the virtual
78 // root for postdominators.
80 // If blocks have numbers (e.g., BasicBlock, MachineBasicBlock), store node
81 // infos in a vector. Otherwise, store them in a map.
82 std::conditional_t<GraphHasNodeNumbers<NodePtr>, SmallVector<InfoRec, 32>,
85
86 /// Reverse children of nodes; pairs of (DFSNum (predecessor), next-or-zero);
87 /// forms a linked list in this vector.
89
90 using UpdateT = typename DomTreeT::UpdateType;
91 using UpdateKind = typename DomTreeT::UpdateKind;
93 // Note: Updates inside PreViewCFG are already legalized.
97
98 // Remembers if the whole tree was recalculated at some point during the
99 // current batch update.
100 bool IsRecalculated = false;
103 const size_t NumLegalized;
104 };
105
108
109 // If BUI is a nullptr, then there's no batch update in progress.
110 SemiNCAInfo(const DomTreeT &DT, BatchUpdatePtr BUI) : BatchUpdates(BUI) {
111 if constexpr (GraphHasNodeNumbers<NodePtr>) {
112 unsigned MaxNodeNumber =
114 NodeInfos.resize(MaxNodeNumber + 1); // nullptr block is zero.
115 }
116 }
117
118 void clear() {
119 NumToNode.clear();
120 if constexpr (GraphHasNodeNumbers<NodePtr>)
121 NodeInfos.assign(NodeInfos.size(), InfoRec{});
122 else
123 NodeInfos.clear();
124 ReverseChildren.clear();
125 // Don't reset the pointer to BatchUpdateInfo here -- if there's an update
126 // in progress, we need this information to continue it.
127 }
128
129 template <bool Inversed>
131 if (BUI)
132 return BUI->PreViewCFG.template getChildren<Inversed>(N);
133 auto Children = getChildren<Inversed>(N);
134 return SmallVector<NodePtr, 8>(Children.begin(), Children.end());
135 }
136
137 // Returns a lazy range over N's children, reversed for non-inverted graphs so
138 // a LIFO worklist visits them in their natural order.
139 template <bool Inversed> static auto getChildren(NodePtr N) {
140 using DirectedNodeT =
141 std::conditional_t<Inversed, Inverse<NodePtr>, NodePtr>;
143 }
144
146 if constexpr (GraphHasNodeNumbers<NodePtr>) {
147 unsigned Idx = BB ? GraphTraits<NodePtr>::getNumber(BB) + 1 : 0;
148 return NodeInfos[Idx];
149 } else {
150 return NodeInfos[BB];
151 }
152 }
153
155
157 if (TreeNodePtr Node = DT.getNode(BB))
158 return Node;
159
160 // Haven't calculated this node yet? Get or calculate the node for the
161 // immediate dominator.
162 NodePtr IDom = getIDom(BB);
163
164 assert(IDom || DT.getNode(nullptr));
165 TreeNodePtr IDomNode = getNodeForBlock(IDom, DT);
166
167 // Add a new tree node for this NodeT, and link it as a child of
168 // IDomNode
169 return DT.createNode(BB, IDomNode);
170 }
171
172 static bool AlwaysDescend(NodePtr, NodePtr) { return true; }
173
176
178 BlockNamePrinter(TreeNodePtr TN) : N(TN ? TN->getBlock() : nullptr) {}
179
181 if (!BP.N)
182 O << "nullptr";
183 else
184 BP.N->printAsOperand(O, false);
185
186 return O;
187 }
188 };
189
191
192 // Custom DFS implementation which can skip nodes based on a provided
193 // predicate. It also collects ReverseChildren so that we don't have to spend
194 // time getting predecessors in SemiNCA.
195 //
196 // If IsReverse is set to true, the DFS walk will be performed backwards
197 // relative to IsPostDom -- using reverse edges for dominators and forward
198 // edges for postdominators.
199 //
200 // If SuccOrder is specified then in this order the DFS traverses the children
201 // otherwise the order is implied by the results of getChildren().
202 template <bool IsReverse = false, typename DescendCondition>
203 unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition,
204 unsigned AttachToNum,
205 const NodeOrderMap *SuccOrder = nullptr) {
206 assert(V);
207 SmallVector<std::pair<NodePtr, unsigned>, 64> WorkList = {{V, AttachToNum}};
208 getNodeInfo(V).Parent = AttachToNum;
209
210 while (!WorkList.empty()) {
211 const auto [BB, ParentNum] = WorkList.pop_back_val();
212 auto &BBInfo = getNodeInfo(BB);
213 ReverseChildren.emplace_back(ParentNum, BBInfo.ReverseChildrenStart);
214 BBInfo.ReverseChildrenStart = ReverseChildren.size();
215
216 if (BBInfo.DFSNumPlus1 != Unvisited)
217 continue;
218 BBInfo.Parent = ParentNum;
219 unsigned Num = LastNum++;
220 BBInfo.Semi = BBInfo.Label = Num;
221 BBInfo.DFSNumPlus1 = Num + 1;
222 NumToNode.push_back(BB);
223
224 constexpr bool Direction = IsReverse != IsPostDom; // XOR.
225 // Common case: iterate the lazy successor range directly. Materializing
226 // is only needed to reorder by SuccOrder or to consult a batch update
227 // view.
228 if (!SuccOrder && !BatchUpdates) {
229 for (const NodePtr Succ : getChildren<Direction>(BB))
230 if (Condition(BB, Succ))
231 WorkList.push_back({Succ, Num});
232 continue;
233 }
234
235 auto Successors = getChildren<Direction>(BB, BatchUpdates);
236 if (SuccOrder && Successors.size() > 1)
238 Successors.begin(), Successors.end(), [=](NodePtr A, NodePtr B) {
239 return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
240 });
241
242 for (const NodePtr Succ : Successors) {
243 if (!Condition(BB, Succ))
244 continue;
245
246 WorkList.push_back({Succ, Num});
247 }
248 }
249
250 return LastNum;
251 }
252
253 // V is a predecessor of W. eval() returns V if V < W, otherwise the minimum
254 // of sdom(U), where U > W and there is a virtual forest path from U to V. The
255 // virtual forest consists of linked edges of processed vertices.
256 //
257 // We can follow Parent pointers (virtual forest edges) to determine the
258 // ancestor U with minimum sdom(U). But it is slow and thus we employ the path
259 // compression technique to speed up to O(m*log(n)). Theoretically the virtual
260 // forest can be organized as balanced trees to achieve almost linear
261 // O(m*alpha(m,n)) running time. But it requires two auxiliary arrays (Size
262 // and Child) and is unlikely to be faster than the simple implementation.
263 //
264 // For each vertex V, its Label is the minimal sdom (Semi) on its path from V
265 // (included) to NodeToInfo[V].Parent (excluded), held directly as a Semi
266 // value.
267 unsigned eval(unsigned V, unsigned LastLinked,
269 ArrayRef<InfoRec *> NumToInfo) {
270 InfoRec *VInfo = NumToInfo[V];
271 if (VInfo->Parent < LastLinked)
272 return VInfo->Label;
273
274 // Store ancestors except the last (root of a virtual tree) into a stack.
275 assert(Stack.empty());
276 do {
277 Stack.push_back(VInfo);
278 VInfo = NumToInfo[VInfo->Parent];
279 } while (VInfo->Parent >= LastLinked);
280
281 // Path compression. Point each vertex's Parent to the root and update its
282 // Label if any of its ancestors (PLabel) has a smaller Semi.
283 const InfoRec *PInfo = VInfo;
284 unsigned PLabel = PInfo->Label;
285 do {
286 VInfo = Stack.pop_back_val();
287 VInfo->Parent = PInfo->Parent;
288 unsigned VLabel = VInfo->Label;
289 if (PLabel < VLabel)
290 VInfo->Label = PLabel;
291 else
292 PLabel = VLabel;
293 PInfo = VInfo;
294 } while (!Stack.empty());
295 return VInfo->Label;
296 }
297
298 // This function requires DFS to be run before calling it.
299 void runSemiNCA() {
300 const unsigned NextDFSNum(NumToNode.size());
301 // NumToInfo and IDoms are indexed by DFS number; 0 is the root. IDoms holds
302 // immediate dominators in DFS-number space, initialized below to spanning
303 // tree parents.
305 NumToInfo.resize_for_overwrite(NextDFSNum);
307 IDoms.resize_for_overwrite(NextDFSNum);
308 for (unsigned i = 0; i < NextDFSNum; ++i) {
309 auto &VInfo = getNodeInfo(NumToNode[i]);
310 IDoms[i] = VInfo.Parent;
311 NumToInfo[i] = &VInfo;
312 }
313
314 // Step #1: Calculate the semidominators of all vertices.
316 for (unsigned i = NextDFSNum; --i;) {
317 auto &WInfo = *NumToInfo[i];
318
319 // Initialize the semi dominator to point to the parent node.
320 WInfo.Semi = WInfo.Parent;
321 for (unsigned RCIdx = WInfo.ReverseChildrenStart; RCIdx != 0;) {
322 const auto &Entry = ReverseChildren[RCIdx - 1];
323 RCIdx = Entry.second;
324 unsigned SemiU = eval(Entry.first, i + 1, EvalStack, NumToInfo);
325 if (SemiU < WInfo.Semi)
326 WInfo.Semi = SemiU;
327 }
328 // Label now holds the semidominator value for later eval() calls.
329 WInfo.Label = WInfo.Semi;
330 }
331
332 // Step #2: Explicitly define the immediate dominator of each vertex.
333 // IDom[i] = NCA(SDom[i], SpanningTreeParent(i)).
334 // SDom[i]'s DFS number is just Semi.
335 for (unsigned i = 1; i < NextDFSNum; ++i) {
336 auto &WInfo = *NumToInfo[i];
337 unsigned WIDom = IDoms[i];
338 while (WIDom > WInfo.Semi)
339 WIDom = IDoms[WIDom];
340 IDoms[i] = WIDom;
341 WInfo.IDom = NumToNode[WIDom];
342 }
343 }
344
345 // PostDominatorTree always has a virtual root that represents a virtual CFG
346 // node that serves as a single exit from the function. All the other exits
347 // (CFG nodes with terminators and nodes in infinite loops are logically
348 // connected to this virtual CFG exit node).
349 // This functions maps a nullptr CFG node to the virtual root tree node.
351 assert(IsPostDom && "Only postdominators have a virtual root");
352 assert(NumToNode.empty() && "SNCAInfo must be freshly constructed");
353
354 auto &BBInfo = getNodeInfo(nullptr);
355 BBInfo.Semi = BBInfo.Label = 0;
356 BBInfo.DFSNumPlus1 = 1;
357
358 NumToNode.push_back(nullptr); // NumToNode[0] = nullptr;
359 }
360
361 // For postdominators, nodes with no forward successors are trivial roots that
362 // are always selected as tree roots. Roots with forward successors correspond
363 // to CFG nodes within infinite loops.
365 assert(N && "N must be a valid node");
366 return !getChildren<false>(N, BUI).empty();
367 }
368
369 static NodePtr GetEntryNode(const DomTreeT &DT) {
370 assert(DT.Parent && "Parent not set");
372 }
373
374 // Finds all roots without relaying on the set of roots already stored in the
375 // tree.
376 // We define roots to be some non-redundant set of the CFG nodes
377 static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI) {
378 assert(DT.Parent && "Parent pointer is not set");
379 RootsT Roots;
380
381 // For dominators, function entry CFG node is always a tree root node.
382 if (!IsPostDom) {
383 Roots.push_back(GetEntryNode(DT));
384 return Roots;
385 }
386
387 SemiNCAInfo SNCA(DT, BUI);
388
389 // PostDominatorTree always has a virtual root.
390 SNCA.addVirtualRoot();
391 unsigned Num = 1;
392
393 LLVM_DEBUG(dbgs() << "\t\tLooking for trivial roots\n");
394
395 // Step #1: Find all the trivial roots that are going to will definitely
396 // remain tree roots.
397 unsigned Total = 0;
398 // It may happen that there are some new nodes in the CFG that are result of
399 // the ongoing batch update, but we cannot really pretend that they don't
400 // exist -- we won't see any outgoing or incoming edges to them, so it's
401 // fine to discover them here, as they would end up appearing in the CFG at
402 // some point anyway.
403 for (const NodePtr N : nodes(DT.Parent)) {
404 ++Total;
405 // If it has no *successors*, it is definitely a root.
406 if (!HasForwardSuccessors(N, BUI)) {
407 Roots.push_back(N);
408 // Run DFS not to walk this part of CFG later.
409 Num = SNCA.runDFS(N, Num, AlwaysDescend, 0);
410 LLVM_DEBUG(dbgs() << "Found a new trivial root: " << BlockNamePrinter(N)
411 << "\n");
412 LLVM_DEBUG(dbgs() << "Last visited node: "
413 << BlockNamePrinter(SNCA.NumToNode[Num - 1]) << "\n");
414 }
415 }
416
417 LLVM_DEBUG(dbgs() << "\t\tLooking for non-trivial roots\n");
418
419 // Step #2: Find all non-trivial root candidates. Those are CFG nodes that
420 // are reverse-unreachable were not visited by previous DFS walks (i.e. CFG
421 // nodes in infinite loops).
422 bool HasNonTrivialRoots = false;
423 // Accounting for the virtual exit, see if we had any reverse-unreachable
424 // nodes.
425 if (Total + 1 != Num) {
426 HasNonTrivialRoots = true;
427
428 // SuccOrder is the order of blocks in the function. It is needed to make
429 // the calculation of the FurthestAway node and the whole PostDomTree
430 // immune to swap successors transformation (e.g. canonicalizing branch
431 // predicates). SuccOrder is initialized lazily only for successors of
432 // reverse unreachable nodes.
433 std::optional<NodeOrderMap> SuccOrder;
434 auto InitSuccOrderOnce = [&]() {
435 SuccOrder = NodeOrderMap();
436 for (const auto Node : nodes(DT.Parent))
438 for (const auto Succ : getChildren<false>(Node, SNCA.BatchUpdates))
439 SuccOrder->try_emplace(Succ, 0);
440
441 // Add mapping for all entries of SuccOrder.
442 unsigned NodeNum = 0;
443 for (const auto Node : nodes(DT.Parent)) {
444 ++NodeNum;
445 auto Order = SuccOrder->find(Node);
446 if (Order != SuccOrder->end()) {
447 assert(Order->second == 0);
448 Order->second = NodeNum;
449 }
450 }
451 };
452
453 // Make another DFS pass over all other nodes to find the
454 // reverse-unreachable blocks, and find the furthest paths we'll be able
455 // to make.
456 // Note that this looks N^2, but it's really 2N worst case, if every node
457 // is unreachable. This is because we are still going to only visit each
458 // unreachable node once, we may just visit it in two directions,
459 // depending on how lucky we get.
460 for (const NodePtr I : nodes(DT.Parent)) {
461 if (SNCA.getNodeInfo(I).DFSNumPlus1 == Unvisited) {
463 << "\t\t\tVisiting node " << BlockNamePrinter(I) << "\n");
464 // Find the furthest away we can get by following successors, then
465 // follow them in reverse. This gives us some reasonable answer about
466 // the post-dom tree inside any infinite loop. In particular, it
467 // guarantees we get to the farthest away point along *some*
468 // path. This also matches the GCC's behavior.
469 // If we really wanted a totally complete picture of dominance inside
470 // this infinite loop, we could do it with SCC-like algorithms to find
471 // the lowest and highest points in the infinite loop. In theory, it
472 // would be nice to give the canonical backedge for the loop, but it's
473 // expensive and does not always lead to a minimal set of roots.
474 LLVM_DEBUG(dbgs() << "\t\t\tRunning forward DFS\n");
475
476 if (!SuccOrder)
477 InitSuccOrderOnce();
478 assert(SuccOrder);
479
480 const unsigned NewNum =
481 SNCA.runDFS<true>(I, Num, AlwaysDescend, Num, &*SuccOrder);
482 const NodePtr FurthestAway = SNCA.NumToNode[NewNum - 1];
483 LLVM_DEBUG(dbgs() << "\t\t\tFound a new furthest away node "
484 << "(non-trivial root): "
485 << BlockNamePrinter(FurthestAway) << "\n");
486 Roots.push_back(FurthestAway);
487 LLVM_DEBUG(dbgs() << "\t\t\tPrev DFSNum: " << Num << ", new DFSNum: "
488 << NewNum << "\n\t\t\tRemoving DFS info\n");
489 for (unsigned i = NewNum; i-- > Num;) {
490 const NodePtr N = SNCA.NumToNode[i];
491 LLVM_DEBUG(dbgs() << "\t\t\t\tRemoving DFS info for "
492 << BlockNamePrinter(N) << "\n");
493 SNCA.getNodeInfo(N) = {};
494 SNCA.NumToNode.pop_back();
495 }
496 const unsigned PrevNum = Num;
497 LLVM_DEBUG(dbgs() << "\t\t\tRunning reverse DFS\n");
498 Num = SNCA.runDFS(FurthestAway, Num, AlwaysDescend, 0);
499 for (unsigned i = PrevNum; i < Num; ++i)
500 LLVM_DEBUG(dbgs() << "\t\t\t\tfound node "
501 << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
502 }
503 }
504 }
505
506 LLVM_DEBUG(dbgs() << "Total: " << Total << ", Num: " << Num << "\n");
507 LLVM_DEBUG(dbgs() << "Discovered CFG nodes:\n");
508 LLVM_DEBUG(for (size_t i = 0; i < Num; ++i) dbgs()
509 << i << ": " << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
510
511 assert((Total + 1 == Num) && "Everything should have been visited");
512
513 // Step #3: If we found some non-trivial roots, make them non-redundant.
514 if (HasNonTrivialRoots)
515 RemoveRedundantRoots(DT, BUI, Roots);
516
517 LLVM_DEBUG(dbgs() << "Found roots: ");
518 LLVM_DEBUG(for (auto *Root : Roots) dbgs()
519 << BlockNamePrinter(Root) << " ");
520 LLVM_DEBUG(dbgs() << "\n");
521
522 return Roots;
523 }
524
525 // This function only makes sense for postdominators.
526 // We define roots to be some set of CFG nodes where (reverse) DFS walks have
527 // to start in order to visit all the CFG nodes (including the
528 // reverse-unreachable ones).
529 // When the search for non-trivial roots is done it may happen that some of
530 // the non-trivial roots are reverse-reachable from other non-trivial roots,
531 // which makes them redundant. This function removes them from the set of
532 // input roots.
533 static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI,
534 RootsT &Roots) {
535 assert(IsPostDom && "This function is for postdominators only");
536 LLVM_DEBUG(dbgs() << "Removing redundant roots\n");
537
538 SemiNCAInfo SNCA(DT, BUI);
539
540 for (unsigned i = 0; i < Roots.size(); ++i) {
541 auto &Root = Roots[i];
542 // Trivial roots are always non-redundant.
543 if (!HasForwardSuccessors(Root, BUI))
544 continue;
545 LLVM_DEBUG(dbgs() << "\tChecking if " << BlockNamePrinter(Root)
546 << " remains a root\n");
547 SNCA.clear();
548 // Do a forward walk looking for the other roots.
549 const unsigned Num = SNCA.runDFS<true>(Root, 0, AlwaysDescend, 0);
550 // Skip the start node (DFS number 0).
551 for (unsigned x = 1; x < Num; ++x) {
552 const NodePtr N = SNCA.NumToNode[x];
553 // If we wound another root in a (forward) DFS walk, remove the current
554 // root from the set of roots, as it is reverse-reachable from the other
555 // one.
556 if (llvm::is_contained(Roots, N)) {
557 LLVM_DEBUG(dbgs() << "\tForward DFS walk found another root "
558 << BlockNamePrinter(N) << "\n\tRemoving root "
559 << BlockNamePrinter(Root) << "\n");
560 std::swap(Root, Roots.back());
561 Roots.pop_back();
562
563 // Root at the back takes the current root's place.
564 // Start the next loop iteration with the same index.
565 --i;
566 break;
567 }
568 }
569 }
570 }
571
572 template <typename DescendCondition>
573 void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC) {
574 if (!IsPostDom) {
575 assert(DT.Roots.size() == 1 && "Dominators should have a singe root");
576 runDFS(DT.Roots[0], 0, DC, 0);
577 return;
578 }
579
581 unsigned Num = 1;
582 for (const NodePtr Root : DT.Roots)
583 Num = runDFS(Root, Num, DC, 0);
584 }
585
586 static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI) {
587 auto *Parent = DT.Parent;
588 DT.reset();
589 DT.Parent = Parent;
590 // If the update is using the actual CFG, BUI is null. If it's using a view,
591 // BUI is non-null and the PreCFGView is used. When calculating from
592 // scratch, make the PreViewCFG equal to the PostCFGView, so Post is used.
593 BatchUpdatePtr PostViewBUI = nullptr;
594 if (BUI && BUI->PostViewCFG) {
595 BUI->PreViewCFG = *BUI->PostViewCFG;
596 PostViewBUI = BUI;
597 }
598 // This is rebuilding the whole tree, not incrementally, but PostViewBUI is
599 // used in case the caller needs a DT update with a CFGView.
600 SemiNCAInfo SNCA(DT, PostViewBUI);
601
602 // Step #0: Number blocks in depth-first order and initialize variables used
603 // in later stages of the algorithm.
604 DT.Roots = FindRoots(DT, PostViewBUI);
606
607 SNCA.runSemiNCA();
608 if (BUI) {
609 BUI->IsRecalculated = true;
611 dbgs() << "DomTree recalculated, skipping future batch updates\n");
612 }
613
614 if (DT.Roots.empty())
615 return;
616
617 // Add a node for the root. If the tree is a PostDominatorTree it will be
618 // the virtual exit (denoted by (BasicBlock *) nullptr) which postdominates
619 // all real exits (including multiple exit blocks, infinite loops).
620 NodePtr Root = IsPostDom ? nullptr : DT.Roots[0];
621
622 DT.RootNode = DT.createNode(Root);
623 SNCA.attachNewSubtree(DT, DT.RootNode);
624 }
625
626 void attachNewSubtree(DomTreeT &DT, const TreeNodePtr AttachTo) {
627 // Attach the first unreachable block to AttachTo.
628 getNodeInfo(NumToNode[0]).IDom = AttachTo->getBlock();
629 // Loop over all of the discovered blocks in the function...
630 for (NodePtr W : NumToNode) {
631 if (DT.getNode(W))
632 continue; // Already calculated the node before
633
634 NodePtr ImmDom = getIDom(W);
635
636 // Get or calculate the node for the immediate dominator.
637 TreeNodePtr IDomNode = getNodeForBlock(ImmDom, DT);
638
639 // Add a new tree node for this BasicBlock, and link it as a child of
640 // IDomNode.
641 DT.createNode(W, IDomNode);
642 }
643 }
644
645 void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo) {
646 getNodeInfo(NumToNode[0]).IDom = AttachTo->getBlock();
647 for (const NodePtr N : NumToNode) {
648 const TreeNodePtr TN = DT.getNode(N);
649 assert(TN);
650 const TreeNodePtr NewIDom = DT.getNode(getNodeInfo(N).IDom);
651 TN->setIDom(NewIDom);
652 }
653 }
654
655 // Helper struct used during edge insertions.
657 struct Compare {
659 return LHS->getLevel() < RHS->getLevel();
660 }
661 };
662
663 // Bucket queue of tree nodes ordered by descending level. For simplicity,
664 // we use a priority_queue here.
665 std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>, Compare>
669#if LLVM_ENABLE_ABI_BREAKING_CHECKS
670 SmallVector<TreeNodePtr, 8> VisitedUnaffected;
671#endif
672 };
673
674 static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
675 const NodePtr From, const NodePtr To) {
676 assert((From || IsPostDom) &&
677 "From has to be a valid CFG node or a virtual root");
678 assert(To && "Cannot be a nullptr");
679 LLVM_DEBUG(dbgs() << "Inserting edge " << BlockNamePrinter(From) << " -> "
680 << BlockNamePrinter(To) << "\n");
681 TreeNodePtr FromTN = DT.getNode(From);
682
683 if (!FromTN) {
684 // Ignore edges from unreachable nodes for (forward) dominators.
685 if (!IsPostDom)
686 return;
687
688 // The unreachable node becomes a new root -- a tree node for it.
689 TreeNodePtr VirtualRoot = DT.getNode(nullptr);
690 FromTN = DT.createNode(From, VirtualRoot);
691 DT.Roots.push_back(From);
692 }
693
694 DT.DFSInfoValid = false;
695
696 const TreeNodePtr ToTN = DT.getNode(To);
697 if (!ToTN)
698 InsertUnreachable(DT, BUI, FromTN, To);
699 else
700 InsertReachable(DT, BUI, FromTN, ToTN);
701 }
702
703 // Determines if some existing root becomes reverse-reachable after the
704 // insertion. Rebuilds the whole tree if that situation happens.
705 static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
706 const TreeNodePtr From,
707 const TreeNodePtr To) {
708 assert(IsPostDom && "This function is only for postdominators");
709 // Destination node is not attached to the virtual root, so it cannot be a
710 // root.
711 if (!DT.isVirtualRoot(To->getIDom()))
712 return false;
713
714 if (!llvm::is_contained(DT.Roots, To->getBlock()))
715 return false; // To is not a root, nothing to update.
716
717 LLVM_DEBUG(dbgs() << "\t\tAfter the insertion, " << BlockNamePrinter(To)
718 << " is no longer a root\n\t\tRebuilding the tree!!!\n");
719
720 CalculateFromScratch(DT, BUI);
721 return true;
722 }
723
726 if (A.size() != B.size())
727 return false;
729 for (NodePtr N : B)
730 if (Set.count(N) == 0)
731 return false;
732 return true;
733 }
734
735 // Updates the set of roots after insertion or deletion. This ensures that
736 // roots are the same when after a series of updates and when the tree would
737 // be built from scratch.
738 static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI) {
739 assert(IsPostDom && "This function is only for postdominators");
740
741 // The tree has only trivial roots -- nothing to update.
742 if (llvm::none_of(DT.Roots, [BUI](const NodePtr N) {
743 return HasForwardSuccessors(N, BUI);
744 }))
745 return;
746
747 // Recalculate the set of roots.
748 RootsT Roots = FindRoots(DT, BUI);
749 if (!isPermutation(DT.Roots, Roots)) {
750 // The roots chosen in the CFG have changed. This is because the
751 // incremental algorithm does not really know or use the set of roots and
752 // can make a different (implicit) decision about which node within an
753 // infinite loop becomes a root.
754
755 LLVM_DEBUG(dbgs() << "Roots are different in updated trees\n"
756 << "The entire tree needs to be rebuilt\n");
757 // It may be possible to update the tree without recalculating it, but
758 // we do not know yet how to do it, and it happens rarely in practice.
759 CalculateFromScratch(DT, BUI);
760 }
761 }
762
763 // Handles insertion to a node already in the dominator tree.
764 static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
765 const TreeNodePtr From, const TreeNodePtr To) {
766 LLVM_DEBUG(dbgs() << "\tReachable " << BlockNamePrinter(From->getBlock())
767 << " -> " << BlockNamePrinter(To->getBlock()) << "\n");
768 if (IsPostDom && UpdateRootsBeforeInsertion(DT, BUI, From, To))
769 return;
770 // DT.findNCD expects both pointers to be valid. When From is a virtual
771 // root, then its CFG block pointer is a nullptr, so we have to 'compute'
772 // the NCD manually.
773 const NodePtr NCDBlock =
774 (From->getBlock() && To->getBlock())
775 ? DT.findNearestCommonDominator(From->getBlock(), To->getBlock())
776 : nullptr;
777 assert(NCDBlock || DT.isPostDominator());
778 const TreeNodePtr NCD = DT.getNode(NCDBlock);
779 assert(NCD);
780
781 LLVM_DEBUG(dbgs() << "\t\tNCA == " << BlockNamePrinter(NCD) << "\n");
782 const unsigned NCDLevel = NCD->getLevel();
783
784 // Based on Lemma 2.5 from [2], after insertion of (From,To), v is affected
785 // iff depth(NCD)+1 < depth(v) && a path P from To to v exists where every
786 // w on P s.t. depth(v) <= depth(w)
787 //
788 // This reduces to a widest path problem (maximizing the depth of the
789 // minimum vertex in the path) which can be solved by a modified version of
790 // Dijkstra with a bucket queue (named depth-based search in [2]).
791
792 // To is in the path, so depth(NCD)+1 < depth(v) <= depth(To). Nothing
793 // affected if this does not hold.
794 if (NCDLevel + 1 >= To->getLevel())
795 return;
796
798 SmallVector<TreeNodePtr, 8> UnaffectedOnCurrentLevel;
799 II.Bucket.push(To);
800 II.Visited.insert(To);
801
802 while (!II.Bucket.empty()) {
803 TreeNodePtr TN = II.Bucket.top();
804 II.Bucket.pop();
805 II.Affected.push_back(TN);
806
807 const unsigned CurrentLevel = TN->getLevel();
808 LLVM_DEBUG(dbgs() << "Mark " << BlockNamePrinter(TN)
809 << "as affected, CurrentLevel " << CurrentLevel
810 << "\n");
811
812 assert(TN->getBlock() && II.Visited.count(TN) && "Preconditions!");
813
814 while (true) {
815 // Unlike regular Dijkstra, we have an inner loop to expand more
816 // vertices. The first iteration is for the (affected) vertex popped
817 // from II.Bucket and the rest are for vertices in
818 // UnaffectedOnCurrentLevel, which may eventually expand to affected
819 // vertices.
820 //
821 // Invariant: there is an optimal path from `To` to TN with the minimum
822 // depth being CurrentLevel.
823 for (const NodePtr Succ : getChildren<IsPostDom>(TN->getBlock(), BUI)) {
824 const TreeNodePtr SuccTN = DT.getNode(Succ);
825 assert(SuccTN &&
826 "Unreachable successor found at reachable insertion");
827 const unsigned SuccLevel = SuccTN->getLevel();
828
829 LLVM_DEBUG(dbgs() << "\tSuccessor " << BlockNamePrinter(Succ)
830 << ", level = " << SuccLevel << "\n");
831
832 // There is an optimal path from `To` to Succ with the minimum depth
833 // being min(CurrentLevel, SuccLevel).
834 //
835 // If depth(NCD)+1 < depth(Succ) is not satisfied, Succ is unaffected
836 // and no affected vertex may be reached by a path passing through it.
837 // Stop here. Also, Succ may be visited by other predecessors but the
838 // first visit has the optimal path. Stop if Succ has been visited.
839 if (SuccLevel <= NCDLevel + 1 || !II.Visited.insert(SuccTN).second)
840 continue;
841
842 if (SuccLevel > CurrentLevel) {
843 // Succ is unaffected but it may (transitively) expand to affected
844 // vertices. Store it in UnaffectedOnCurrentLevel.
845 LLVM_DEBUG(dbgs() << "\t\tMarking visited not affected "
846 << BlockNamePrinter(Succ) << "\n");
847 UnaffectedOnCurrentLevel.push_back(SuccTN);
848#if LLVM_ENABLE_ABI_BREAKING_CHECKS
849 II.VisitedUnaffected.push_back(SuccTN);
850#endif
851 } else {
852 // The condition is satisfied (Succ is affected). Add Succ to the
853 // bucket queue.
854 LLVM_DEBUG(dbgs() << "\t\tAdd " << BlockNamePrinter(Succ)
855 << " to a Bucket\n");
856 II.Bucket.push(SuccTN);
857 }
858 }
859
860 if (UnaffectedOnCurrentLevel.empty())
861 break;
862 TN = UnaffectedOnCurrentLevel.pop_back_val();
863 LLVM_DEBUG(dbgs() << " Next: " << BlockNamePrinter(TN) << "\n");
864 }
865 }
866
867 // Finish by updating immediate dominators and levels.
868 UpdateInsertion(DT, BUI, NCD, II);
869 }
870
871 // Updates immediate dominators and levels after insertion.
872 static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
873 const TreeNodePtr NCD, InsertionInfo &II) {
874 LLVM_DEBUG(dbgs() << "Updating NCD = " << BlockNamePrinter(NCD) << "\n");
875
876 for (const TreeNodePtr TN : II.Affected) {
877 LLVM_DEBUG(dbgs() << "\tIDom(" << BlockNamePrinter(TN)
878 << ") = " << BlockNamePrinter(NCD) << "\n");
879 TN->setIDom(NCD);
880 }
881
882#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
883 for (const TreeNodePtr TN : II.VisitedUnaffected)
884 assert(TN->getLevel() == TN->getIDom()->getLevel() + 1 &&
885 "TN should have been updated by an affected ancestor");
886#endif
887
888 if (IsPostDom)
889 UpdateRootsAfterUpdate(DT, BUI);
890 }
891
892 // Handles insertion to previously unreachable nodes.
893 static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
894 const TreeNodePtr From, const NodePtr To) {
895 LLVM_DEBUG(dbgs() << "Inserting " << BlockNamePrinter(From)
896 << " -> (unreachable) " << BlockNamePrinter(To) << "\n");
897
898 // Collect discovered edges to already reachable nodes.
899 SmallVector<std::pair<NodePtr, TreeNodePtr>, 8> DiscoveredEdgesToReachable;
900 // Discover and connect nodes that became reachable with the insertion.
901 ComputeUnreachableDominators(DT, BUI, To, From, DiscoveredEdgesToReachable);
902
903 LLVM_DEBUG(dbgs() << "Inserted " << BlockNamePrinter(From)
904 << " -> (prev unreachable) " << BlockNamePrinter(To)
905 << "\n");
906
907 // Used the discovered edges and inset discovered connecting (incoming)
908 // edges.
909 for (const auto &Edge : DiscoveredEdgesToReachable) {
910 LLVM_DEBUG(dbgs() << "\tInserting discovered connecting edge "
911 << BlockNamePrinter(Edge.first) << " -> "
912 << BlockNamePrinter(Edge.second) << "\n");
913 InsertReachable(DT, BUI, DT.getNode(Edge.first), Edge.second);
914 }
915 }
916
917 // Connects nodes that become reachable with an insertion.
918 static void
920 const NodePtr Root, const TreeNodePtr Incoming,
921 SmallVectorImpl<std::pair<NodePtr, TreeNodePtr>>
922 &DiscoveredConnectingEdges) {
923 assert(!DT.getNode(Root) && "Root must not be reachable");
924
925 // Visit only previously unreachable nodes.
926 auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](NodePtr From,
927 NodePtr To) {
928 const TreeNodePtr ToTN = DT.getNode(To);
929 if (!ToTN)
930 return true;
931
932 DiscoveredConnectingEdges.push_back({From, ToTN});
933 return false;
934 };
935
936 SemiNCAInfo SNCA(DT, BUI);
937 SNCA.runDFS(Root, 0, UnreachableDescender, 0);
938 SNCA.runSemiNCA();
939 SNCA.attachNewSubtree(DT, Incoming);
940
941 LLVM_DEBUG(dbgs() << "After adding unreachable nodes\n");
942 }
943
944 static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
945 const NodePtr From, const NodePtr To) {
946 assert(From && To && "Cannot disconnect nullptrs");
947 LLVM_DEBUG(dbgs() << "Deleting edge " << BlockNamePrinter(From) << " -> "
948 << BlockNamePrinter(To) << "\n");
949
950#if LLVM_ENABLE_ABI_BREAKING_CHECKS
951 // Ensure that the edge was in fact deleted from the CFG before informing
952 // the DomTree about it.
953 // The check is O(N), so run it only in debug configuration.
954 auto IsSuccessor = [BUI](const NodePtr SuccCandidate, const NodePtr Of) {
955 auto Successors = getChildren<IsPostDom>(Of, BUI);
956 return llvm::is_contained(Successors, SuccCandidate);
957 };
958 (void)IsSuccessor;
959 assert(!IsSuccessor(To, From) && "Deleted edge still exists in the CFG!");
960#endif
961
962 const TreeNodePtr FromTN = DT.getNode(From);
963 // Deletion in an unreachable subtree -- nothing to do.
964 if (!FromTN)
965 return;
966
967 const TreeNodePtr ToTN = DT.getNode(To);
968 if (!ToTN) {
970 dbgs() << "\tTo (" << BlockNamePrinter(To)
971 << ") already unreachable -- there is no edge to delete\n");
972 return;
973 }
974
975 const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
976 const TreeNodePtr NCD = DT.getNode(NCDBlock);
977
978 // If To dominates From -- nothing to do.
979 if (ToTN != NCD) {
980 DT.DFSInfoValid = false;
981
982 const TreeNodePtr ToIDom = ToTN->getIDom();
983 LLVM_DEBUG(dbgs() << "\tNCD " << BlockNamePrinter(NCD) << ", ToIDom "
984 << BlockNamePrinter(ToIDom) << "\n");
985
986 // To remains reachable after deletion.
987 // (Based on the caption under Figure 4. from [2].)
988 if (FromTN != ToIDom || HasProperSupport(DT, BUI, ToTN))
989 DeleteReachable(DT, BUI, FromTN, ToTN);
990 else
991 DeleteUnreachable(DT, BUI, ToTN);
992 }
993
994 if (IsPostDom)
995 UpdateRootsAfterUpdate(DT, BUI);
996 }
997
998 // Handles deletions that leave destination nodes reachable.
999 static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
1000 const TreeNodePtr FromTN,
1001 const TreeNodePtr ToTN) {
1002 LLVM_DEBUG(dbgs() << "Deleting reachable " << BlockNamePrinter(FromTN)
1003 << " -> " << BlockNamePrinter(ToTN) << "\n");
1004 LLVM_DEBUG(dbgs() << "\tRebuilding subtree\n");
1005
1006 // Find the top of the subtree that needs to be rebuilt.
1007 // (Based on the lemma 2.6 from [2].)
1008 const NodePtr ToIDom =
1009 DT.findNearestCommonDominator(FromTN->getBlock(), ToTN->getBlock());
1010 assert(ToIDom || DT.isPostDominator());
1011 const TreeNodePtr ToIDomTN = DT.getNode(ToIDom);
1012 assert(ToIDomTN);
1013 const TreeNodePtr PrevIDomSubTree = ToIDomTN->getIDom();
1014 // Top of the subtree to rebuild is the root node. Rebuild the tree from
1015 // scratch.
1016 if (!PrevIDomSubTree) {
1017 LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
1018 CalculateFromScratch(DT, BUI);
1019 return;
1020 }
1021
1022 // Only visit nodes in the subtree starting at To.
1023 const unsigned Level = ToIDomTN->getLevel();
1024 auto DescendBelow = [Level, &DT](NodePtr, NodePtr To) {
1025 return DT.getNode(To)->getLevel() > Level;
1026 };
1027
1028 LLVM_DEBUG(dbgs() << "\tTop of subtree: " << BlockNamePrinter(ToIDomTN)
1029 << "\n");
1030
1031 SemiNCAInfo SNCA(DT, BUI);
1032 SNCA.runDFS(ToIDom, 0, DescendBelow, 0);
1033 LLVM_DEBUG(dbgs() << "\tRunning Semi-NCA\n");
1034 SNCA.runSemiNCA();
1035 SNCA.reattachExistingSubtree(DT, PrevIDomSubTree);
1036 }
1037
1038 // Checks if a node has proper support, as defined on the page 3 and later
1039 // explained on the page 7 of [2].
1040 static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI,
1041 const TreeNodePtr TN) {
1042 LLVM_DEBUG(dbgs() << "IsReachableFromIDom " << BlockNamePrinter(TN)
1043 << "\n");
1044 auto TNB = TN->getBlock();
1045 for (const NodePtr Pred : getChildren<!IsPostDom>(TNB, BUI)) {
1046 LLVM_DEBUG(dbgs() << "\tPred " << BlockNamePrinter(Pred) << "\n");
1047 if (!DT.getNode(Pred))
1048 continue;
1049
1050 const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
1051 LLVM_DEBUG(dbgs() << "\tSupport " << BlockNamePrinter(Support) << "\n");
1052 if (Support != TNB) {
1053 LLVM_DEBUG(dbgs() << "\t" << BlockNamePrinter(TN)
1054 << " is reachable from support "
1055 << BlockNamePrinter(Support) << "\n");
1056 return true;
1057 }
1058 }
1059
1060 return false;
1061 }
1062
1063 // Handle deletions that make destination node unreachable.
1064 // (Based on the lemma 2.7 from the [2].)
1065 static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
1066 const TreeNodePtr ToTN) {
1067 LLVM_DEBUG(dbgs() << "Deleting unreachable subtree "
1068 << BlockNamePrinter(ToTN) << "\n");
1069 assert(ToTN);
1070 assert(ToTN->getBlock());
1071
1072 if (IsPostDom) {
1073 // Deletion makes a region reverse-unreachable and creates a new root.
1074 // Simulate that by inserting an edge from the virtual root to ToTN and
1075 // adding it as a new root.
1076 LLVM_DEBUG(dbgs() << "\tDeletion made a region reverse-unreachable\n");
1077 LLVM_DEBUG(dbgs() << "\tAdding new root " << BlockNamePrinter(ToTN)
1078 << "\n");
1079 DT.Roots.push_back(ToTN->getBlock());
1080 InsertReachable(DT, BUI, DT.getNode(nullptr), ToTN);
1081 return;
1082 }
1083
1084 SmallVector<NodePtr, 16> AffectedQueue;
1085 const unsigned Level = ToTN->getLevel();
1086
1087 // Traverse destination node's descendants with greater level in the tree
1088 // and collect visited nodes.
1089 auto DescendAndCollect = [Level, &AffectedQueue, &DT](NodePtr, NodePtr To) {
1090 const TreeNodePtr TN = DT.getNode(To);
1091 assert(TN);
1092 if (TN->getLevel() > Level)
1093 return true;
1094 if (!llvm::is_contained(AffectedQueue, To))
1095 AffectedQueue.push_back(To);
1096
1097 return false;
1098 };
1099
1100 SemiNCAInfo SNCA(DT, BUI);
1101 unsigned LastDFSNum =
1102 SNCA.runDFS(ToTN->getBlock(), 0, DescendAndCollect, 0);
1103
1104 TreeNodePtr MinNode = ToTN;
1105
1106 // Identify the top of the subtree to rebuild by finding the NCD of all
1107 // the affected nodes.
1108 for (const NodePtr N : AffectedQueue) {
1109 const TreeNodePtr TN = DT.getNode(N);
1110 const NodePtr NCDBlock =
1111 DT.findNearestCommonDominator(TN->getBlock(), ToTN->getBlock());
1112 assert(NCDBlock || DT.isPostDominator());
1113 const TreeNodePtr NCD = DT.getNode(NCDBlock);
1114 assert(NCD);
1115
1116 LLVM_DEBUG(dbgs() << "Processing affected node " << BlockNamePrinter(TN)
1117 << " with NCD = " << BlockNamePrinter(NCD)
1118 << ", MinNode =" << BlockNamePrinter(MinNode) << "\n");
1119 if (NCD != TN && NCD->getLevel() < MinNode->getLevel())
1120 MinNode = NCD;
1121 }
1122
1123 // Root reached, rebuild the whole tree from scratch.
1124 if (!MinNode->getIDom()) {
1125 LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
1126 CalculateFromScratch(DT, BUI);
1127 return;
1128 }
1129
1130 // Erase the unreachable subtree in reverse preorder to process all children
1131 // before deleting their parent.
1132 for (unsigned i = LastDFSNum; i-- > 0;) {
1133 const NodePtr N = SNCA.NumToNode[i];
1134 LLVM_DEBUG(dbgs() << "Erasing node " << BlockNamePrinter(DT.getNode(N))
1135 << "\n");
1136 DT.eraseNode(N);
1137 }
1138
1139 // The affected subtree start at the To node -- there's no extra work to do.
1140 if (MinNode == ToTN)
1141 return;
1142
1143 LLVM_DEBUG(dbgs() << "DeleteUnreachable: running DFS with MinNode = "
1144 << BlockNamePrinter(MinNode) << "\n");
1145 const unsigned MinLevel = MinNode->getLevel();
1146 const TreeNodePtr PrevIDom = MinNode->getIDom();
1147 assert(PrevIDom);
1148 SNCA.clear();
1149
1150 // Identify nodes that remain in the affected subtree.
1151 auto DescendBelow = [MinLevel, &DT](NodePtr R, NodePtr To) {
1152 const TreeNodePtr ToTN = DT.getNode(To);
1153 if (ToTN)
1154 return ToTN->getLevel() > MinLevel;
1155 DT.createNode(To, DT.getNode(R));
1156 return true;
1157 };
1158 SNCA.runDFS(MinNode->getBlock(), 0, DescendBelow, 0);
1159
1160 LLVM_DEBUG(dbgs() << "Previous IDom(MinNode) = "
1161 << BlockNamePrinter(PrevIDom) << "\nRunning Semi-NCA\n");
1162
1163 // Rebuild the remaining part of affected subtree.
1164 SNCA.runSemiNCA();
1165 SNCA.reattachExistingSubtree(DT, PrevIDom);
1166 }
1167
1168 //~~
1169 //===--------------------- DomTree Batch Updater --------------------------===
1170 //~~
1171
1172 static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG,
1173 GraphDiffT *PostViewCFG) {
1174 // Note: the PostViewCFG is only used when computing from scratch. It's data
1175 // should already included in the PreViewCFG for incremental updates.
1176 const size_t NumUpdates = PreViewCFG.getNumLegalizedUpdates();
1177 if (NumUpdates == 0)
1178 return;
1179
1180 // Take the fast path for a single update and avoid running the batch update
1181 // machinery.
1182 if (NumUpdates == 1) {
1183 UpdateT Update = PreViewCFG.popUpdateForIncrementalUpdates();
1184 if (!PostViewCFG) {
1185 if (Update.getKind() == UpdateKind::Insert)
1186 InsertEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
1187 else
1188 DeleteEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
1189 } else {
1190 BatchUpdateInfo BUI(*PostViewCFG, PostViewCFG);
1191 if (Update.getKind() == UpdateKind::Insert)
1192 InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1193 else
1194 DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1195 }
1196 return;
1197 }
1198
1199 BatchUpdateInfo BUI(PreViewCFG, PostViewCFG);
1200 // Recalculate the DominatorTree when the number of updates
1201 // exceeds a threshold, which usually makes direct updating slower than
1202 // recalculation. We select this threshold proportional to the
1203 // size of the DominatorTree. The constant is selected
1204 // by choosing the one with an acceptable performance on some real-world
1205 // inputs.
1206
1207 // Make unittests of the incremental algorithm work
1208 if (DT.DomTreeNodes.size() <= 100) {
1209 if (BUI.NumLegalized > DT.DomTreeNodes.size())
1210 CalculateFromScratch(DT, &BUI);
1211 } else if (BUI.NumLegalized > DT.DomTreeNodes.size() / 40)
1212 CalculateFromScratch(DT, &BUI);
1213
1214 // If the DominatorTree was recalculated at some point, stop the batch
1215 // updates. Full recalculations ignore batch updates and look at the actual
1216 // CFG.
1217 for (size_t i = 0; i < BUI.NumLegalized && !BUI.IsRecalculated; ++i)
1218 ApplyNextUpdate(DT, BUI);
1219 }
1220
1221 static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI) {
1222 // Popping the next update, will move the PreViewCFG to the next snapshot.
1224#if 0
1225 // FIXME: The LLVM_DEBUG macro only plays well with a modular
1226 // build of LLVM when the header is marked as textual, but doing
1227 // so causes redefinition errors.
1228 LLVM_DEBUG(dbgs() << "Applying update: ");
1229 LLVM_DEBUG(CurrentUpdate.dump(); dbgs() << "\n");
1230#endif
1231
1232 if (CurrentUpdate.getKind() == UpdateKind::Insert)
1233 InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1234 else
1235 DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1236 }
1237
1238 //~~
1239 //===--------------- DomTree correctness verification ---------------------===
1240 //~~
1241
1242 // Check if the tree has correct roots. A DominatorTree always has a single
1243 // root which is the function's entry node. A PostDominatorTree can have
1244 // multiple roots - one for each node with no successors and for infinite
1245 // loops.
1246 // Running time: O(N).
1247 bool verifyRoots(const DomTreeT &DT) {
1248 if (!DT.Parent && !DT.Roots.empty()) {
1249 errs() << "Tree has no parent but has roots!\n";
1250 errs().flush();
1251 return false;
1252 }
1253
1254 if (!IsPostDom) {
1255 if (DT.Roots.empty()) {
1256 errs() << "Tree doesn't have a root!\n";
1257 errs().flush();
1258 return false;
1259 }
1260
1261 if (DT.getRoot() != GetEntryNode(DT)) {
1262 errs() << "Tree's root is not its parent's entry node!\n";
1263 errs().flush();
1264 return false;
1265 }
1266 }
1267
1268 RootsT ComputedRoots = FindRoots(DT, nullptr);
1269 if (!isPermutation(DT.Roots, ComputedRoots)) {
1270 errs() << "Tree has different roots than freshly computed ones!\n";
1271 errs() << "\tPDT roots: ";
1272 for (const NodePtr N : DT.Roots)
1273 errs() << BlockNamePrinter(N) << ", ";
1274 errs() << "\n\tComputed roots: ";
1275 for (const NodePtr N : ComputedRoots)
1276 errs() << BlockNamePrinter(N) << ", ";
1277 errs() << "\n";
1278 errs().flush();
1279 return false;
1280 }
1281
1282 return true;
1283 }
1284
1285 // Checks if the tree contains all reachable nodes in the input graph.
1286 // Running time: O(N).
1287 bool verifyReachability(const DomTreeT &DT) {
1288 clear();
1290
1291 for (auto *TN : DT.DomTreeNodes) {
1292 if (!TN)
1293 continue;
1294 const NodePtr BB = TN->getBlock();
1295
1296 // Virtual root has a corresponding virtual CFG node.
1297 if (DT.isVirtualRoot(TN))
1298 continue;
1299
1300 if (getNodeInfo(BB).DFSNumPlus1 == Unvisited) {
1301 errs() << "DomTree node " << BlockNamePrinter(BB)
1302 << " not found by DFS walk!\n";
1303 errs().flush();
1304
1305 return false;
1306 }
1307 }
1308
1309 for (const NodePtr N : NumToNode) {
1310 if (N && !DT.getNode(N)) {
1311 errs() << "CFG node " << BlockNamePrinter(N)
1312 << " not found in the DomTree!\n";
1313 errs().flush();
1314
1315 return false;
1316 }
1317 }
1318
1319 return true;
1320 }
1321
1322 // Check if for every parent with a level L in the tree all of its children
1323 // have level L + 1.
1324 // Running time: O(N).
1325 static bool VerifyLevels(const DomTreeT &DT) {
1326 for (auto *TN : DT.DomTreeNodes) {
1327 if (!TN)
1328 continue;
1329 const NodePtr BB = TN->getBlock();
1330 if (!BB)
1331 continue;
1332
1333 const TreeNodePtr IDom = TN->getIDom();
1334 if (!IDom && TN->getLevel() != 0) {
1335 errs() << "Node without an IDom " << BlockNamePrinter(BB)
1336 << " has a nonzero level " << TN->getLevel() << "!\n";
1337 errs().flush();
1338
1339 return false;
1340 }
1341
1342 if (IDom && TN->getLevel() != IDom->getLevel() + 1) {
1343 errs() << "Node " << BlockNamePrinter(BB) << " has level "
1344 << TN->getLevel() << " while its IDom "
1345 << BlockNamePrinter(IDom->getBlock()) << " has level "
1346 << IDom->getLevel() << "!\n";
1347 errs().flush();
1348
1349 return false;
1350 }
1351 }
1352
1353 return true;
1354 }
1355
1356 // Check if the computed DFS numbers are correct. Note that DFS info may not
1357 // be valid, and when that is the case, we don't verify the numbers.
1358 // Running time: O(N log(N)).
1359 static bool VerifyDFSNumbers(const DomTreeT &DT) {
1360 if (!DT.DFSInfoValid || !DT.Parent)
1361 return true;
1362
1363 const NodePtr RootBB = IsPostDom ? nullptr : *DT.root_begin();
1364 const TreeNodePtr Root = DT.getNode(RootBB);
1365
1366 auto PrintNodeAndDFSNums = [](const TreeNodePtr TN) {
1367 errs() << BlockNamePrinter(TN) << " {" << TN->getDFSNumIn() << ", "
1368 << TN->getDFSNumOut() << '}';
1369 };
1370
1371 // Verify the root's DFS In number. Although DFS numbering would also work
1372 // if we started from some other value, we assume 0-based numbering.
1373 if (Root->getDFSNumIn() != 0) {
1374 errs() << "DFSIn number for the tree root is not:\n\t";
1375 PrintNodeAndDFSNums(Root);
1376 errs() << '\n';
1377 errs().flush();
1378 return false;
1379 }
1380
1381 // For each tree node verify if children's DFS numbers cover their parent's
1382 // DFS numbers with no gaps.
1383 for (auto *Node : DT.DomTreeNodes) {
1384 if (!Node)
1385 continue;
1386
1387 // Handle tree leaves.
1388 if (Node->isLeaf()) {
1389 if (Node->getDFSNumIn() + 1 != Node->getDFSNumOut()) {
1390 errs() << "Tree leaf should have DFSOut = DFSIn + 1:\n\t";
1391 PrintNodeAndDFSNums(Node);
1392 errs() << '\n';
1393 errs().flush();
1394 return false;
1395 }
1396
1397 continue;
1398 }
1399
1400 // Make a copy and sort it such that it is possible to check if there are
1401 // no gaps between DFS numbers of adjacent children.
1402 SmallVector<TreeNodePtr, 8> Children(Node->begin(), Node->end());
1403 llvm::sort(Children, [](const TreeNodePtr Ch1, const TreeNodePtr Ch2) {
1404 return Ch1->getDFSNumIn() < Ch2->getDFSNumIn();
1405 });
1406
1407 auto PrintChildrenError =
1408 [Node, &Children, PrintNodeAndDFSNums](const TreeNodePtr FirstCh,
1409 const TreeNodePtr SecondCh) {
1410 assert(FirstCh);
1411
1412 errs() << "Incorrect DFS numbers for:\n\tParent ";
1413 PrintNodeAndDFSNums(Node);
1414
1415 errs() << "\n\tChild ";
1416 PrintNodeAndDFSNums(FirstCh);
1417
1418 if (SecondCh) {
1419 errs() << "\n\tSecond child ";
1420 PrintNodeAndDFSNums(SecondCh);
1421 }
1422
1423 errs() << "\nAll children: ";
1424 for (const TreeNodePtr Ch : Children) {
1425 PrintNodeAndDFSNums(Ch);
1426 errs() << ", ";
1427 }
1428
1429 errs() << '\n';
1430 errs().flush();
1431 };
1432
1433 if (Children.front()->getDFSNumIn() != Node->getDFSNumIn() + 1) {
1434 PrintChildrenError(Children.front(), nullptr);
1435 return false;
1436 }
1437
1438 if (Children.back()->getDFSNumOut() != Node->getDFSNumOut()) {
1439 PrintChildrenError(Children.back(), nullptr);
1440 return false;
1441 }
1442
1443 for (size_t i = 0, e = Children.size() - 1; i != e; ++i) {
1444 if (Children[i]->getDFSNumOut() != Children[i + 1]->getDFSNumIn()) {
1445 PrintChildrenError(Children[i], Children[i + 1]);
1446 return false;
1447 }
1448 }
1449 }
1450
1451 return true;
1452 }
1453
1454 // The below routines verify the correctness of the dominator tree relative to
1455 // the CFG it's coming from. A tree is a dominator tree iff it has two
1456 // properties, called the parent property and the sibling property. Tarjan
1457 // and Lengauer prove (but don't explicitly name) the properties as part of
1458 // the proofs in their 1972 paper, but the proofs are mostly part of proving
1459 // things about semidominators and idoms, and some of them are simply asserted
1460 // based on even earlier papers (see, e.g., lemma 2). Some papers refer to
1461 // these properties as "valid" and "co-valid". See, e.g., "Dominators,
1462 // directed bipolar orders, and independent spanning trees" by Loukas
1463 // Georgiadis and Robert E. Tarjan, as well as "Dominator Tree Verification
1464 // and Vertex-Disjoint Paths " by the same authors.
1465
1466 // A very simple and direct explanation of these properties can be found in
1467 // "An Experimental Study of Dynamic Dominators", found at
1468 // https://arxiv.org/abs/1604.02711
1469
1470 // The easiest way to think of the parent property is that it's a requirement
1471 // of being a dominator. Let's just take immediate dominators. For PARENT to
1472 // be an immediate dominator of CHILD, all paths in the CFG must go through
1473 // PARENT before they hit CHILD. This implies that if you were to cut PARENT
1474 // out of the CFG, there should be no paths to CHILD that are reachable. If
1475 // there are, then you now have a path from PARENT to CHILD that goes around
1476 // PARENT and still reaches CHILD, which by definition, means PARENT can't be
1477 // a dominator of CHILD (let alone an immediate one).
1478
1479 // The sibling property is similar. It says that for each pair of sibling
1480 // nodes in the dominator tree (LEFT and RIGHT) , they must not dominate each
1481 // other. If sibling LEFT dominated sibling RIGHT, it means there are no
1482 // paths in the CFG from sibling LEFT to sibling RIGHT that do not go through
1483 // LEFT, and thus, LEFT is really an ancestor (in the dominator tree) of
1484 // RIGHT, not a sibling.
1485
1486 // It is possible to verify the parent and sibling properties in linear time,
1487 // but the algorithms are complex. Instead, we do it in a straightforward
1488 // N^2 and N^3 way below, using direct path reachability.
1489
1490 // Checks if the tree has the parent property: if for all edges from V to W in
1491 // the input graph, such that V is reachable, the parent of W in the tree is
1492 // an ancestor of V in the tree.
1493 // Running time: O(N^2).
1494 //
1495 // This means that if a node gets disconnected from the graph, then all of
1496 // the nodes it dominated previously will now become unreachable.
1497 bool verifyParentProperty(const DomTreeT &DT) {
1498 for (auto *TN : DT.DomTreeNodes) {
1499 if (!TN)
1500 continue;
1501 const NodePtr BB = TN->getBlock();
1502 if (!BB || TN->isLeaf())
1503 continue;
1504
1505 LLVM_DEBUG(dbgs() << "Verifying parent property of node "
1506 << BlockNamePrinter(TN) << "\n");
1507 clear();
1508 doFullDFSWalk(DT, [BB](NodePtr From, NodePtr To) {
1509 return From != BB && To != BB;
1510 });
1511
1512 for (TreeNodePtr Child : TN->children())
1513 if (getNodeInfo(Child->getBlock()).DFSNumPlus1 != Unvisited) {
1514 errs() << "Child " << BlockNamePrinter(Child)
1515 << " reachable after its parent " << BlockNamePrinter(BB)
1516 << " is removed!\n";
1517 errs().flush();
1518
1519 return false;
1520 }
1521 }
1522
1523 return true;
1524 }
1525
1526 // Check if the tree has sibling property: if a node V does not dominate a
1527 // node W for all siblings V and W in the tree.
1528 // Running time: O(N^3).
1529 //
1530 // This means that if a node gets disconnected from the graph, then all of its
1531 // siblings will now still be reachable.
1532 bool verifySiblingProperty(const DomTreeT &DT) {
1533 for (auto *TN : DT.DomTreeNodes) {
1534 if (!TN)
1535 continue;
1536 const NodePtr BB = TN->getBlock();
1537 if (!BB || TN->isLeaf())
1538 continue;
1539
1540 for (const TreeNodePtr N : TN->children()) {
1541 clear();
1542 NodePtr BBN = N->getBlock();
1543 doFullDFSWalk(DT, [BBN](NodePtr From, NodePtr To) {
1544 return From != BBN && To != BBN;
1545 });
1546
1547 for (const TreeNodePtr S : TN->children()) {
1548 if (S == N)
1549 continue;
1550
1551 if (getNodeInfo(S->getBlock()).DFSNumPlus1 == Unvisited) {
1552 errs() << "Node " << BlockNamePrinter(S)
1553 << " not reachable when its sibling " << BlockNamePrinter(N)
1554 << " is removed!\n";
1555 errs().flush();
1556
1557 return false;
1558 }
1559 }
1560 }
1561 }
1562
1563 return true;
1564 }
1565
1566 // Check if the given tree is the same as a freshly computed one for the same
1567 // Parent.
1568 // Running time: O(N^2), but faster in practice (same as tree construction).
1569 //
1570 // Note that this does not check if that the tree construction algorithm is
1571 // correct and should be only used for fast (but possibly unsound)
1572 // verification.
1573 static bool IsSameAsFreshTree(const DomTreeT &DT) {
1574 DomTreeT FreshTree;
1575 FreshTree.recalculate(*DT.Parent);
1576 const bool Different = DT.compare(FreshTree);
1577
1578 if (Different) {
1579 errs() << (DT.isPostDominator() ? "Post" : "")
1580 << "DominatorTree is different than a freshly computed one!\n"
1581 << "\tCurrent:\n";
1582 DT.print(errs());
1583 errs() << "\n\tFreshly computed tree:\n";
1584 FreshTree.print(errs());
1585 errs().flush();
1586 }
1587
1588 return !Different;
1589 }
1590};
1591
1592template <class DomTreeT> void Calculate(DomTreeT &DT) {
1594}
1595
1596template <typename DomTreeT>
1597void CalculateWithUpdates(DomTreeT &DT,
1599 // FIXME: Updated to use the PreViewCFG and behave the same as until now.
1600 // This behavior is however incorrect; this actually needs the PostViewCFG.
1602 Updates, /*ReverseApplyUpdates=*/true);
1603 typename SemiNCAInfo<DomTreeT>::BatchUpdateInfo BUI(PreViewCFG);
1605}
1606
1607template <class DomTreeT>
1608void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
1609 typename DomTreeT::NodePtr To) {
1610 if (DT.isPostDominator())
1611 std::swap(From, To);
1612 SemiNCAInfo<DomTreeT>::InsertEdge(DT, nullptr, From, To);
1613}
1614
1615template <class DomTreeT>
1616void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
1617 typename DomTreeT::NodePtr To) {
1618 if (DT.isPostDominator())
1619 std::swap(From, To);
1620 SemiNCAInfo<DomTreeT>::DeleteEdge(DT, nullptr, From, To);
1621}
1622
1623template <class DomTreeT>
1624void ApplyUpdates(DomTreeT &DT,
1625 GraphDiff<typename DomTreeT::NodePtr,
1626 DomTreeT::IsPostDominator> &PreViewCFG,
1627 GraphDiff<typename DomTreeT::NodePtr,
1628 DomTreeT::IsPostDominator> *PostViewCFG) {
1629 SemiNCAInfo<DomTreeT>::ApplyUpdates(DT, PreViewCFG, PostViewCFG);
1630}
1631
1632template <class DomTreeT>
1633bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL) {
1634 SemiNCAInfo<DomTreeT> SNCA(DT, nullptr);
1635
1636 // Simplist check is to compare against a new tree. This will also
1637 // usefully print the old and new trees, if they are different.
1638 if (!SNCA.IsSameAsFreshTree(DT))
1639 return false;
1640
1641 // Common checks to verify the properties of the tree. O(N log N) at worst.
1642 if (!SNCA.verifyRoots(DT) || !SNCA.verifyReachability(DT) ||
1643 !SNCA.VerifyLevels(DT) || !SNCA.VerifyDFSNumbers(DT))
1644 return false;
1645
1646 // Extra checks depending on VerificationLevel. Up to O(N^3).
1647 if (VL == DomTreeT::VerificationLevel::Basic ||
1648 VL == DomTreeT::VerificationLevel::Full)
1649 if (!SNCA.verifyParentProperty(DT))
1650 return false;
1651 if (VL == DomTreeT::VerificationLevel::Full)
1652 if (!SNCA.verifySiblingProperty(DT))
1653 return false;
1654
1655 return true;
1656}
1657
1658} // namespace DomTreeBuilder
1659} // namespace llvm
1660
1661#undef DEBUG_TYPE
1662
1663#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
ppc ctr loops PowerPC CTR Loops Verify
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for the actual dominator tree node.
void setIDom(DomTreeNodeBase *NewIDom)
DomTreeNodeBase * getIDom() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
NodeT * getBlock() const
unsigned getLevel() const
cfg::Update< NodePtr > popUpdateForIncrementalUpdates()
Definition CFGDiff.h:111
unsigned getNumLegalizedUpdates() const
Definition CFGDiff.h:109
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
void CalculateWithUpdates(DomTreeT &DT, ArrayRef< typename DomTreeT::UpdateType > Updates)
void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
void ApplyUpdates(DomTreeT &DT, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > &PreViewCFG, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > *PostViewCFG)
void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
auto reverse_if(Range &&R)
Definition CFGDiff.h:45
This is an optimization pass for GlobalISel generic memory operations.
constexpr from_range_t from_range
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
BatchUpdateInfo(GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG=nullptr)
friend raw_ostream & operator<<(raw_ostream &O, const BlockNamePrinter &BP)
std::priority_queue< TreeNodePtr, SmallVector< TreeNodePtr, 8 >, Compare > Bucket
static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr NCD, InsertionInfo &II)
static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC)
DenseMap< NodePtr, unsigned > NodeOrderMap
static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI)
static SmallVector< NodePtr, 8 > getChildren(NodePtr N, BatchUpdatePtr BUI)
static void ComputeUnreachableDominators(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root, const TreeNodePtr Incoming, SmallVectorImpl< std::pair< NodePtr, TreeNodePtr > > &DiscoveredConnectingEdges)
static bool VerifyLevels(const DomTreeT &DT)
unsigned eval(unsigned V, unsigned LastLinked, SmallVectorImpl< InfoRec * > &Stack, ArrayRef< InfoRec * > NumToInfo)
static bool IsSameAsFreshTree(const DomTreeT &DT)
GraphDiff< NodePtr, IsPostDom > GraphDiffT
static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG)
typename DomTreeT::UpdateKind UpdateKind
static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static NodePtr GetEntryNode(const DomTreeT &DT)
static bool AlwaysDescend(NodePtr, NodePtr)
static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI)
unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition, unsigned AttachToNum, const NodeOrderMap *SuccOrder=nullptr)
static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr FromTN, const TreeNodePtr ToTN)
static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI, RootsT &Roots)
static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr TN)
static bool isPermutation(const SmallVectorImpl< NodePtr > &A, const SmallVectorImpl< NodePtr > &B)
static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI)
TreeNodePtr getNodeForBlock(NodePtr BB, DomTreeT &DT)
static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
static bool HasForwardSuccessors(const NodePtr N, BatchUpdatePtr BUI)
std::conditional_t< GraphHasNodeNumbers< NodePtr >, SmallVector< InfoRec, 32 >, DenseMap< NodePtr, InfoRec > > NodeInfos
SemiNCAInfo(const DomTreeT &DT, BatchUpdatePtr BUI)
static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const NodePtr To)
static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI)
static bool VerifyDFSNumbers(const DomTreeT &DT)
static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr ToTN)
void attachNewSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
SmallVector< std::pair< unsigned, unsigned >, 32 > ReverseChildren
Reverse children of nodes; pairs of (DFSNum (predecessor), next-or-zero); forms a linked list in this...