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