LLVM 23.0.0git
GenericDomTree.h
Go to the documentation of this file.
1//===- GenericDomTree.h - Generic dominator trees for graphs ----*- 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/// This file defines a set of templates that efficiently compute a dominator
11/// tree over a generic graph. This is used typically in LLVM for fast
12/// dominance queries on the CFG, but is fully generic w.r.t. the underlying
13/// graph types.
14///
15/// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
16/// on the graph's NodeRef. The NodeRef should be a pointer and,
17/// either NodeRef->getParent() must return the parent node that is also a
18/// pointer or DomTreeNodeTraits needs to be specialized.
19///
20/// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
21///
22//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_SUPPORT_GENERICDOMTREE_H
25#define LLVM_SUPPORT_GENERICDOMTREE_H
26
27#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
36#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <memory>
40#include <new>
41#include <type_traits>
42#include <utility>
43
44namespace llvm {
45
46template <typename NodeT, bool IsPostDom>
48
49template <class BlockT, class LoopT> class LoopInfoBase;
50
51namespace DomTreeBuilder {
52template <typename DomTreeT>
53struct SemiNCAInfo;
54} // namespace DomTreeBuilder
55
56/// Base class for the actual dominator tree node.
57template <class NodeT> class DomTreeNodeBase {
58 friend class PostDominatorTree;
59 friend class DominatorTreeBase<NodeT, false>;
60 friend class DominatorTreeBase<NodeT, true>;
63
64 NodeT *TheBB;
65 DomTreeNodeBase *IDom;
66 unsigned Level;
67 DomTreeNodeBase *FirstChild = nullptr;
68 DomTreeNodeBase *Sibling = nullptr;
69 DomTreeNodeBase **AppendPtr = &FirstChild;
70 mutable unsigned DFSNumIn = ~0;
71 mutable unsigned DFSNumOut = ~0;
72
73 public:
75 : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
76
79
81 : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
82 DomTreeNodeBase *> {
83 DomTreeNodeBase *Node;
84
85 public:
86 const_iterator(DomTreeNodeBase *Node = nullptr) : Node(Node) {}
87 bool operator==(const const_iterator &Other) const {
88 return Other.Node == Node;
89 }
90 DomTreeNodeBase *operator*() const { return Node; }
92 Node = Node->Sibling;
93 return *this;
94 }
96 const_iterator cp = *this;
97 ++*this;
98 return cp;
99 }
100 };
101 // We don't permit modifications through the iterator.
102 using iterator = const_iterator;
103
104 iterator begin() const { return iterator{FirstChild}; }
105 iterator end() const { return iterator{}; }
106
109 return make_range(begin(), end());
110 }
111
112 NodeT *getBlock() const { return TheBB; }
113 DomTreeNodeBase *getIDom() const { return IDom; }
114 unsigned getLevel() const { return Level; }
115
116 // TODO: make these private once NewGVN doesn't require these anymore.
118 assert(!C->Sibling && "cannot add child that already has siblings");
119 assert(!*AppendPtr && "sibling of last child must be nullptr");
120 *AppendPtr = C;
121 AppendPtr = &C->Sibling;
122 }
123
124 // TODO: make these private once NewGVN doesn't require these anymore.
126 DomTreeNodeBase **It = &FirstChild;
127 while (*It != C) {
128 assert(*It != nullptr && "Not in immediate dominator children list!");
129 It = &(*It)->Sibling;
130 }
131 assert(!*AppendPtr && "sibling of last child must be nullptr");
132 assert(C->Sibling || AppendPtr == &C->Sibling);
133 *It = C->Sibling;
134 if (C->Sibling)
135 C->Sibling = nullptr;
136 else
137 AppendPtr = It;
138 }
139
140 bool isLeaf() const { return FirstChild == nullptr; }
141
142 bool compare(const DomTreeNodeBase *Other) const {
143 if (Level != Other->Level) return true;
144
145 SmallPtrSet<const NodeT *, 4> OtherChildren;
146 for (const DomTreeNodeBase *I : *Other) {
147 const NodeT *Nd = I->getBlock();
148 OtherChildren.insert(Nd);
149 }
150
151 size_t OwnCount = 0;
152 for (const DomTreeNodeBase *I : *this) {
153 const NodeT *N = I->getBlock();
154 if (OtherChildren.count(N) == 0)
155 return true;
156 ++OwnCount;
157 }
158 return OwnCount != OtherChildren.size();
159 }
160
161 void setIDom(DomTreeNodeBase *NewIDom) {
162 assert(IDom && "No immediate dominator?");
163 if (IDom == NewIDom) return;
164 IDom->removeChild(this);
165
166 // Switch to new dominator
167 IDom = NewIDom;
168 IDom->addChild(this);
169
170 UpdateLevel();
171 }
172
173 /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
174 /// in the dominator tree. They are only guaranteed valid if
175 /// updateDFSNumbers() has been called.
176 unsigned getDFSNumIn() const { return DFSNumIn; }
177 unsigned getDFSNumOut() const { return DFSNumOut; }
178
179private:
180 // Return true if this node is dominated by other. Use this only if DFS info
181 // is valid.
182 bool DominatedBy(const DomTreeNodeBase *other) const {
183 return this->DFSNumIn >= other->DFSNumIn &&
184 this->DFSNumOut <= other->DFSNumOut;
185 }
186
187 void UpdateLevel() {
188 assert(IDom);
189 if (Level == IDom->Level + 1) return;
190
191 SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
192
193 while (!WorkStack.empty()) {
194 DomTreeNodeBase *Current = WorkStack.pop_back_val();
195 Current->Level = Current->IDom->Level + 1;
196
197 for (DomTreeNodeBase *C : *Current) {
198 assert(C->IDom);
199 if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
200 }
201 }
202 }
203};
204
205template <class NodeT>
207 if (Node->getBlock())
208 Node->getBlock()->printAsOperand(O, false);
209 else
210 O << " <<exit node>>";
211
212 O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
213 << Node->getLevel() << "]\n";
214
215 return O;
216}
217
218template <class NodeT>
220 unsigned Lev) {
221 O.indent(2 * Lev) << "[" << Lev << "] " << N;
222 for (const auto &I : *N)
223 PrintDomTree<NodeT>(I, O, Lev + 1);
224}
225
226namespace DomTreeBuilder {
227// The routines below are provided in a separate header but referenced here.
228template <typename DomTreeT>
229void Calculate(DomTreeT &DT);
230
231template <typename DomTreeT>
232void CalculateWithUpdates(DomTreeT &DT,
234
235template <typename DomTreeT>
236void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
237 typename DomTreeT::NodePtr To);
238
239template <typename DomTreeT>
240void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
241 typename DomTreeT::NodePtr To);
242
243template <typename DomTreeT>
244void ApplyUpdates(DomTreeT &DT,
245 GraphDiff<typename DomTreeT::NodePtr,
246 DomTreeT::IsPostDominator> &PreViewCFG,
247 GraphDiff<typename DomTreeT::NodePtr,
248 DomTreeT::IsPostDominator> *PostViewCFG);
249
250template <typename DomTreeT>
251bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
252} // namespace DomTreeBuilder
253
254/// Default DomTreeNode traits for NodeT. The default implementation assume a
255/// Function-like NodeT. Can be specialized to support different node types.
256template <typename NodeT> struct DomTreeNodeTraits {
257 using NodeType = NodeT;
258 using NodePtr = NodeT *;
259 using ParentPtr = decltype(std::declval<NodePtr>()->getParent());
260 static_assert(std::is_pointer_v<ParentPtr>,
261 "Currently NodeT's parent must be a pointer type");
262 using ParentType = std::remove_pointer_t<ParentPtr>;
263
264 static NodeT *getEntryNode(ParentPtr Parent) { return &Parent->front(); }
265 static ParentPtr getParent(NodePtr BB) { return BB->getParent(); }
266};
267
268/// Core dominator tree base class.
269///
270/// This class is a generic template over graph nodes. It is instantiated for
271/// various graphs in the LLVM IR or in the code generator.
272template <typename NodeT, bool IsPostDom>
274 public:
275 static_assert(std::is_pointer_v<typename GraphTraits<NodeT *>::NodeRef>,
276 "Currently DominatorTreeBase supports only pointer nodes");
279 using NodePtr = typename NodeTrait::NodePtr;
281 static_assert(std::is_pointer_v<ParentPtr>,
282 "Currently NodeT's parent must be a pointer type");
283 using ParentType = std::remove_pointer_t<ParentPtr>;
284 static constexpr bool IsPostDominator = IsPostDom;
285
288 static constexpr UpdateKind Insert = UpdateKind::Insert;
289 static constexpr UpdateKind Delete = UpdateKind::Delete;
290
292
293protected:
294 // Dominators always have a single root, postdominators can have more.
296
299 // For graphs where blocks don't have numbers, create a numbering here.
300 // TODO: use an empty struct with [[no_unique_address]] in C++20.
301 std::conditional_t<!GraphHasNodeNumbers<NodeT *>,
305 ParentPtr Parent = nullptr;
306
307 // Use small slab size to reduce memory waste for modules with many small
308 // functions. Compensate with a short GrowthDelay. This is relevant for
309 // ThinLTO on modules with many functions (not uncommon in C++), where all
310 // dominator trees are live at the same time.
311 static constexpr size_t SlabSize = 8 * sizeof(DomTreeNodeBase<NodeT>);
313 /*GrowthDelay=*/2>
315
316 mutable bool DFSInfoValid = false;
317 mutable unsigned int SlowQueries = 0;
318 unsigned BlockNumberEpoch = 0;
319
321 template <class BlockT, class LoopT> friend class LoopInfoBase;
322
323public:
324 DominatorTreeBase() = default;
325
328
331
332 /// Iteration over roots.
333 ///
334 /// This may include multiple blocks if we are computing post dominators.
335 /// For forward dominators, this will always be a single block (the entry
336 /// block).
339
340 root_iterator root_begin() { return Roots.begin(); }
341 const_root_iterator root_begin() const { return Roots.begin(); }
342 root_iterator root_end() { return Roots.end(); }
343 const_root_iterator root_end() const { return Roots.end(); }
344
345 size_t root_size() const { return Roots.size(); }
346
353
354 /// isPostDominator - Returns true if analysis based of postdoms
355 ///
356 bool isPostDominator() const { return IsPostDominator; }
357
358 /// compare - Return false if the other dominator tree base matches this
359 /// dominator tree base. Otherwise return true.
360 bool compare(const DominatorTreeBase &Other) const {
361 if (Parent != Other.Parent) return true;
362
363 if (Roots.size() != Other.Roots.size())
364 return true;
365
366 if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin()))
367 return true;
368
369 size_t NumNodes = 0;
370 // All nodes we have must exist and be equal in the other tree.
371 for (const auto &Node : DomTreeNodes) {
372 if (!Node)
373 continue;
374 if (Node->compare(Other.getNode(Node->getBlock())))
375 return true;
376 NumNodes++;
377 }
378
379 // If the other tree has more nodes than we have, they're not equal.
380 size_t NumOtherNodes = 0;
381 for (const auto &OtherNode : Other.DomTreeNodes)
382 if (OtherNode)
383 NumOtherNodes++;
384 return NumNodes != NumOtherNodes;
385 }
386
387private:
388 // For LoopInfoBase's use in deriving a reverse-preorder traversal.
389 auto nodes() const {
391 return N != nullptr;
392 });
393 }
394
395 std::optional<unsigned> getNodeIndex(const NodeT *BB) const {
396 if constexpr (GraphHasNodeNumbers<NodeT *>) {
398 GraphTraits<ParentPtr>::getNumberEpoch(Parent) &&
399 "dominator tree used with outdated block numbers");
400 if constexpr (IsPostDom) {
401 if (!BB)
402 return 0; // BB may be nullptr for post-dominator tree, map to 0.
403 } else
404 assert(BB && "dominator tree block must be non-null");
405 return GraphTraits<const NodeT *>::getNumber(BB) + 1;
406 } else {
407 if (auto It = NodeNumberMap.find(BB); It != NodeNumberMap.end())
408 return It->second;
409 return std::nullopt;
410 }
411 }
412
413 unsigned getNodeIndexForInsert(const NodeT *BB) {
414 if constexpr (GraphHasNodeNumbers<NodeT *>) {
415 // getNodeIndex will never fail if nodes have getNumber().
416 unsigned Idx = *getNodeIndex(BB);
417 if (Idx >= DomTreeNodes.size()) {
418 unsigned Max = GraphTraits<ParentPtr>::getMaxNumber(Parent);
419 DomTreeNodes.resize(Max > Idx + 1 ? Max : Idx + 1);
420 }
421 return Idx;
422 } else {
423 // We might already have a number stored for BB.
424 unsigned Idx =
425 NodeNumberMap.try_emplace(BB, DomTreeNodes.size()).first->second;
426 if (Idx >= DomTreeNodes.size())
427 DomTreeNodes.resize(Idx + 1);
428 return Idx;
429 }
430 }
431
432public:
433 /// getNode - return the (Post)DominatorTree node for the specified basic
434 /// block. This is the same as using operator[] on this class. The result
435 /// may (but is not required to) be null for a forward (backwards)
436 /// statically unreachable block.
437 DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
438 assert((!BB || Parent == NodeTrait::getParent(const_cast<NodeT *>(BB))) &&
439 "cannot get DomTreeNode of block with different parent");
440 if (auto Idx = getNodeIndex(BB); Idx && *Idx < DomTreeNodes.size())
441 return DomTreeNodes[*Idx];
442 return nullptr;
443 }
444
445 /// See getNode.
446 DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
447 return getNode(BB);
448 }
449
450 /// getRootNode - This returns the entry node for the CFG of the function. If
451 /// this tree represents the post-dominance relations for a function, however,
452 /// this root may be a node with the block == NULL. This is the case when
453 /// there are multiple exit nodes from a particular function. Consumers of
454 /// post-dominance information must be capable of dealing with this
455 /// possibility.
456 ///
458 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
459
460 /// Get all nodes dominated by R, including R itself.
461 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
462 Result.clear();
463 const DomTreeNodeBase<NodeT> *RN = getNode(R);
464 if (!RN)
465 return; // If R is unreachable, it will not be present in the DOM tree.
467 WL.push_back(RN);
468
469 while (!WL.empty()) {
471 Result.push_back(N->getBlock());
472 WL.append(N->begin(), N->end());
473 }
474 }
475
476 /// properlyDominates - Returns true iff A dominates B and A != B.
477 /// Note that this is not a constant time operation!
478 ///
480 const DomTreeNodeBase<NodeT> *B) const {
481 if (!A || !B)
482 return false;
483 if (A == B)
484 return false;
485 return dominates(A, B);
486 }
487
488 bool properlyDominates(const NodeT *A, const NodeT *B) const;
489
490 /// isReachableFromEntry - Return true if A is dominated by the entry
491 /// block of the function containing it.
492 bool isReachableFromEntry(const NodeT *A) const {
493 assert(!this->isPostDominator() &&
494 "This is not implemented for post dominators");
495 return isReachableFromEntry(getNode(A));
496 }
497
498 bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
499
500 /// dominates - Returns true iff A dominates B. Note that this is not a
501 /// constant time operation!
502 ///
504 const DomTreeNodeBase<NodeT> *B) const {
505 // A node trivially dominates itself.
506 if (B == A)
507 return true;
508
509 // An unreachable node is dominated by anything.
511 return true;
512
513 // And dominates nothing.
515 return false;
516
517 if (B->getIDom() == A) return true;
518
519 if (A->getIDom() == B) return false;
520
521 // A can only dominate B if it is higher in the tree.
522 if (A->getLevel() >= B->getLevel()) return false;
523
524 // Compare the result of the tree walk and the dfs numbers, if expensive
525 // checks are enabled.
526#ifdef EXPENSIVE_CHECKS
528 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
529 "Tree walk disagrees with dfs numbers!");
530#endif
531
532 if (DFSInfoValid)
533 return B->DominatedBy(A);
534
535 // If we end up with too many slow queries, just update the
536 // DFS numbers on the theory that we are going to keep querying.
537 SlowQueries++;
538 if (SlowQueries > 32) {
540 return B->DominatedBy(A);
541 }
542
543 return dominatedBySlowTreeWalk(A, B);
544 }
545
546 bool dominates(const NodeT *A, const NodeT *B) const;
547
548 NodeT *getRoot() const {
549 assert(this->Roots.size() == 1 && "Should always have entry node!");
550 return this->Roots[0];
551 }
552
553 /// Find nearest common dominator basic block for basic block A and B. A and B
554 /// must have tree nodes.
555 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
556 assert(A && B && "Pointers are not valid");
558 "Two blocks are not in same function");
559
560 // If either A or B is a entry block then it is nearest common dominator
561 // (for forward-dominators).
562 if (!isPostDominator()) {
563 NodeT &Entry =
565 if (A == &Entry || B == &Entry)
566 return &Entry;
567 }
568
571 assert(NodeA && "A must be in the tree");
572 assert(NodeB && "B must be in the tree");
573
574 // Use level information to go up the tree until the levels match. Then
575 // continue going up til we arrive at the same node.
576 while (NodeA != NodeB) {
577 if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
578
579 NodeA = NodeA->IDom;
580 }
581
582 return NodeA->getBlock();
583 }
584
585 const NodeT *findNearestCommonDominator(const NodeT *A,
586 const NodeT *B) const {
587 // Cast away the const qualifiers here. This is ok since
588 // const is re-introduced on the return type.
589 return findNearestCommonDominator(const_cast<NodeT *>(A),
590 const_cast<NodeT *>(B));
591 }
592
594 return isPostDominator() && !A->getBlock();
595 }
596
597 template <typename IteratorTy>
599 assert(!Nodes.empty() && "Nodes list is empty!");
600
601 NodeT *NCD = *Nodes.begin();
602 for (NodeT *Node : llvm::drop_begin(Nodes)) {
604
605 // Stop when the root is reached.
606 if (isVirtualRoot(getNode(NCD)))
607 return nullptr;
608 }
609
610 return NCD;
611 }
612
613 //===--------------------------------------------------------------------===//
614 // API to update (Post)DominatorTree information based on modifications to
615 // the CFG...
616
617 /// Inform the dominator tree about a sequence of CFG edge insertions and
618 /// deletions and perform a batch update on the tree.
619 ///
620 /// This function should be used when there were multiple CFG updates after
621 /// the last dominator tree update. It takes care of performing the updates
622 /// in sync with the CFG and optimizes away the redundant operations that
623 /// cancel each other.
624 /// The functions expects the sequence of updates to be balanced. Eg.:
625 /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
626 /// logically it results in a single insertions.
627 /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
628 /// sense to insert the same edge twice.
629 ///
630 /// What's more, the functions assumes that it's safe to ask every node in the
631 /// CFG about its children and inverse children. This implies that deletions
632 /// of CFG edges must not delete the CFG nodes before calling this function.
633 ///
634 /// The applyUpdates function can reorder the updates and remove redundant
635 /// ones internally (as long as it is done in a deterministic fashion). The
636 /// batch updater is also able to detect sequences of zero and exactly one
637 /// update -- it's optimized to do less work in these cases.
638 ///
639 /// Note that for postdominators it automatically takes care of applying
640 /// updates on reverse edges internally (so there's no need to swap the
641 /// From and To pointers when constructing DominatorTree::UpdateType).
642 /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
643 /// with the same template parameter T.
644 ///
645 /// \param Updates An ordered sequence of updates to perform. The current CFG
646 /// and the reverse of these updates provides the pre-view of the CFG.
647 ///
650 Updates, /*ReverseApplyUpdates=*/true);
651 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr);
652 }
653
654 /// \param Updates An ordered sequence of updates to perform. The current CFG
655 /// and the reverse of these updates provides the pre-view of the CFG.
656 /// \param PostViewUpdates An ordered sequence of update to perform in order
657 /// to obtain a post-view of the CFG. The DT will be updated assuming the
658 /// obtained PostViewCFG is the desired end state.
660 ArrayRef<UpdateType> PostViewUpdates) {
661 if (Updates.empty()) {
662 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
663 DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG);
664 } else {
665 // PreViewCFG needs to merge Updates and PostViewCFG. The updates in
666 // Updates need to be reversed, and match the direction in PostViewCFG.
667 // The PostViewCFG is created with updates reversed (equivalent to changes
668 // made to the CFG), so the PreViewCFG needs all the updates reverse
669 // applied.
670 SmallVector<UpdateType> AllUpdates(Updates);
671 append_range(AllUpdates, PostViewUpdates);
672 GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates,
673 /*ReverseApplyUpdates=*/true);
674 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
675 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG);
676 }
677 }
678
679 /// Inform the dominator tree about a CFG edge insertion and update the tree.
680 ///
681 /// This function has to be called just before or just after making the update
682 /// on the actual CFG. There cannot be any other updates that the dominator
683 /// tree doesn't know about.
684 ///
685 /// Note that for postdominators it automatically takes care of inserting
686 /// a reverse edge internally (so there's no need to swap the parameters).
687 ///
688 void insertEdge(NodeT *From, NodeT *To) {
689 assert(From);
690 assert(To);
693 DomTreeBuilder::InsertEdge(*this, From, To);
694 }
695
696 /// Inform the dominator tree about a CFG edge deletion and update the tree.
697 ///
698 /// This function has to be called just after making the update on the actual
699 /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
700 /// DEBUG mode. There cannot be any other updates that the
701 /// dominator tree doesn't know about.
702 ///
703 /// Note that for postdominators it automatically takes care of deleting
704 /// a reverse edge internally (so there's no need to swap the parameters).
705 ///
706 void deleteEdge(NodeT *From, NodeT *To) {
707 assert(From);
708 assert(To);
711 DomTreeBuilder::DeleteEdge(*this, From, To);
712 }
713
714 /// Add a new node to the dominator tree information.
715 ///
716 /// This creates a new node as a child of DomBB dominator node, linking it
717 /// into the children list of the immediate dominator.
718 ///
719 /// \param BB New node in CFG.
720 /// \param DomBB CFG node that is dominator for BB.
721 /// \returns New dominator tree node that represents new CFG node.
722 ///
723 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
724 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
725 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
726 assert(IDomNode && "Not immediate dominator specified for block!");
727 DFSInfoValid = false;
728 return createNode(BB, IDomNode);
729 }
730
731 /// Add a new node to the forward dominator tree and make it a new root.
732 ///
733 /// \param BB New node in CFG.
734 /// \returns New dominator tree node that represents new CFG node.
735 ///
737 assert(getNode(BB) == nullptr && "Block already in dominator tree!");
738 assert(!this->isPostDominator() &&
739 "Cannot change root of post-dominator tree");
740 DFSInfoValid = false;
741 DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
742 if (Roots.empty()) {
743 addRoot(BB);
744 } else {
745 assert(Roots.size() == 1);
746 NodeT *OldRoot = Roots.front();
747 DomTreeNodeBase<NodeT> *OldNode = getNode(OldRoot);
748 NewNode->addChild(OldNode);
749 OldNode->IDom = NewNode;
750 OldNode->UpdateLevel();
751 Roots[0] = BB;
752 }
753 return RootNode = NewNode;
754 }
755
756 /// changeImmediateDominator - This method is used to update the dominator
757 /// tree information when a node's immediate dominator changes.
758 ///
760 DomTreeNodeBase<NodeT> *NewIDom) {
761 assert(N && NewIDom && "Cannot change null node pointers!");
762 DFSInfoValid = false;
763 N->setIDom(NewIDom);
764 }
765
766 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
768 }
769
770 /// eraseNode - Removes a node from the dominator tree. Block must not
771 /// dominate any other blocks. Removes node from its immediate dominator's
772 /// children list. Deletes dominator node associated with basic block BB.
773 void eraseNode(NodeT *BB) {
774 std::optional<unsigned> IdxOpt = getNodeIndex(BB);
775 assert(IdxOpt && DomTreeNodes[*IdxOpt] &&
776 "Removing node that isn't in dominator tree.");
778 assert(Node->isLeaf() && "Node is not a leaf node.");
779
780 DFSInfoValid = false;
781
782 // Remove node from immediate dominator's children list.
783 if (DomTreeNodeBase<NodeT> *IDom = Node->getIDom())
784 IDom->removeChild(Node);
785
786 DomTreeNodes[*IdxOpt] = nullptr;
787 if constexpr (!GraphHasNodeNumbers<NodeT *>)
788 NodeNumberMap.erase(BB);
789
790 if (!IsPostDom) return;
791
792 // Remember to update PostDominatorTree roots.
793 auto RIt = llvm::find(Roots, BB);
794 if (RIt != Roots.end()) {
795 std::swap(*RIt, Roots.back());
796 Roots.pop_back();
797 }
798 }
799
800 /// splitBlock - BB is split and now it has one successor. Update dominator
801 /// tree to reflect this change.
802 void splitBlock(NodeT *NewBB) {
803 if (IsPostDominator)
805 else
806 Split<NodeT *>(NewBB);
807 }
808
809 /// print - Convert to human readable form
810 ///
811 void print(raw_ostream &O) const {
812 O << "=============================--------------------------------\n";
813 if (IsPostDominator)
814 O << "Inorder PostDominator Tree: ";
815 else
816 O << "Inorder Dominator Tree: ";
817 if (!DFSInfoValid)
818 O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
819 O << "\n";
820
821 // The postdom tree can have a null root if there are no returns.
823 O << "Roots: ";
824 for (const NodePtr Block : Roots) {
825 Block->printAsOperand(O, false);
826 O << " ";
827 }
828 O << "\n";
829 }
830
831public:
832 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
833 /// dominator tree in dfs order.
834 void updateDFSNumbers() const {
835 if (DFSInfoValid) {
836 SlowQueries = 0;
837 return;
838 }
839
842 32> WorkStack;
843
844 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
845 assert((!Parent || ThisRoot) && "Empty constructed DomTree");
846 if (!ThisRoot)
847 return;
848
849 // Both dominators and postdominators have a single root node. In the case
850 // case of PostDominatorTree, this node is a virtual root.
851 WorkStack.push_back({ThisRoot, ThisRoot->begin()});
852
853 unsigned DFSNum = 0;
854 ThisRoot->DFSNumIn = DFSNum++;
855
856 while (!WorkStack.empty()) {
857 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
858 const auto ChildIt = WorkStack.back().second;
859
860 // If we visited all of the children of this node, "recurse" back up the
861 // stack setting the DFOutNum.
862 if (ChildIt == Node->end()) {
863 Node->DFSNumOut = DFSNum;
864 WorkStack.pop_back();
865 } else {
866 // Otherwise, recursively visit this child.
867 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
868 ++WorkStack.back().second;
869
870 WorkStack.push_back({Child, Child->begin()});
871 Child->DFSNumIn = DFSNum++;
872 }
873 }
874
875 SlowQueries = 0;
876 DFSInfoValid = true;
877 }
878
879private:
880 void updateBlockNumberEpoch() {
881 // Nothing to do for graphs that don't number their blocks.
882 if constexpr (GraphHasNodeNumbers<NodeT *>)
884 }
885
886public:
887 /// recalculate - compute a dominator tree for the given function
889 Parent = &Func;
890 updateBlockNumberEpoch();
892 }
893
895 Parent = &Func;
896 updateBlockNumberEpoch();
898 }
899
900 /// Update dominator tree after renumbering blocks.
901 template <typename T = NodeT>
902 std::enable_if_t<GraphHasNodeNumbers<T *>, void> updateBlockNumbers() {
903 updateBlockNumberEpoch();
904
905 unsigned MaxNumber = GraphTraits<ParentPtr>::getMaxNumber(Parent);
906 DomTreeNodeStorageTy NewVector;
907 NewVector.resize(MaxNumber + 1); // +1, because index 0 is for nullptr
908 for (auto &Node : DomTreeNodes) {
909 if (!Node)
910 continue;
911 unsigned Idx = *getNodeIndex(Node->getBlock());
912 // getMaxNumber is not necessarily supported
913 if (Idx >= NewVector.size())
914 NewVector.resize(Idx + 1);
915 NewVector[Idx] = std::move(Node);
916 }
917 DomTreeNodes = std::move(NewVector);
918 }
919
920 /// verify - checks if the tree is correct. There are 3 level of verification:
921 /// - Full -- verifies if the tree is correct by making sure all the
922 /// properties (including the parent and the sibling property)
923 /// hold.
924 /// Takes O(N^3) time.
925 ///
926 /// - Basic -- checks if the tree is correct, but compares it to a freshly
927 /// constructed tree instead of checking the sibling property.
928 /// Takes O(N^2) time.
929 ///
930 /// - Fast -- checks basic tree structure and compares it with a freshly
931 /// constructed tree.
932 /// Takes O(N^2) time worst case, but is faster in practise (same
933 /// as tree construction).
935 return DomTreeBuilder::Verify(*this, VL);
936 }
937
938 void reset() {
939 DomTreeNodes.clear();
940 if constexpr (!GraphHasNodeNumbers<NodeT *>)
941 NodeNumberMap.clear();
942 Roots.clear();
943 RootNode = nullptr;
944 Parent = nullptr;
945 DFSInfoValid = false;
946 NodeAllocator.Reset();
947 SlowQueries = 0;
948 }
949
950protected:
951 inline void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
952
954 DomTreeNodeBase<NodeT> *IDom = nullptr) {
955 static_assert(std::is_trivially_destructible_v<DomTreeNodeBase<NodeT>>);
956 auto *Node = new (NodeAllocator) DomTreeNodeBase<NodeT>(BB, IDom);
957 unsigned NodeIdx = getNodeIndexForInsert(BB);
958 DomTreeNodes[NodeIdx] = Node;
959 if (IDom)
960 IDom->addChild(Node);
961 return Node;
962 }
963
964 // NewBB is split and now it has one successor. Update dominator tree to
965 // reflect this change.
966 template <class N>
967 void Split(typename GraphTraits<N>::NodeRef NewBB) {
968 using GraphT = GraphTraits<N>;
969 using NodeRef = typename GraphT::NodeRef;
971 "NewBB should have a single successor!");
972 NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
973
975
976 assert(!PredBlocks.empty() && "No predblocks?");
977
978 bool NewBBDominatesNewBBSucc = true;
979 for (auto *Pred : inverse_children<N>(NewBBSucc)) {
980 if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
981 isReachableFromEntry(Pred)) {
982 NewBBDominatesNewBBSucc = false;
983 break;
984 }
985 }
986
987 // Find NewBB's immediate dominator and create new dominator tree node for
988 // NewBB.
989 NodeT *NewBBIDom = nullptr;
990 unsigned i = 0;
991 for (i = 0; i < PredBlocks.size(); ++i)
992 if (isReachableFromEntry(PredBlocks[i])) {
993 NewBBIDom = PredBlocks[i];
994 break;
995 }
996
997 // It's possible that none of the predecessors of NewBB are reachable;
998 // in that case, NewBB itself is unreachable, so nothing needs to be
999 // changed.
1000 if (!NewBBIDom) return;
1001
1002 for (i = i + 1; i < PredBlocks.size(); ++i) {
1003 if (isReachableFromEntry(PredBlocks[i]))
1004 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
1005 }
1006
1007 // Create the new dominator tree node... and set the idom of NewBB.
1008 DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
1009
1010 // If NewBB strictly dominates other blocks, then it is now the immediate
1011 // dominator of NewBBSucc. Update the dominator tree as appropriate.
1012 if (NewBBDominatesNewBBSucc) {
1013 DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
1014 changeImmediateDominator(NewBBSuccNode, NewBBNode);
1015 }
1016 }
1017
1018 private:
1019 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
1020 const DomTreeNodeBase<NodeT> *B) const {
1021 assert(A != B);
1024
1025 const unsigned ALevel = A->getLevel();
1026 const DomTreeNodeBase<NodeT> *IDom;
1027
1028 // Don't walk nodes above A's subtree. When we reach A's level, we must
1029 // either find A or be in some other subtree not dominated by A.
1030 while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
1031 B = IDom; // Walk up the tree
1032
1033 return B == A;
1034 }
1035};
1036
1037template <typename T>
1039
1040template <typename T>
1042
1043// These two functions are declared out of line as a workaround for building
1044// with old (< r147295) versions of clang because of pr11642.
1045template <typename NodeT, bool IsPostDom>
1047 const NodeT *B) const {
1048 if (A == B)
1049 return true;
1050
1051 return dominates(getNode(A), getNode(B));
1052}
1053template <typename NodeT, bool IsPostDom>
1055 const NodeT *A, const NodeT *B) const {
1056 if (A == B)
1057 return false;
1058
1059 return dominates(getNode(A), getNode(B));
1060}
1061
1062} // end namespace llvm
1063
1064#endif // LLVM_SUPPORT_GENERICDOMTREE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
Unify divergent function exit nodes
This file defines the BumpPtrAllocator interface.
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 DenseMap class.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
#define I(x, y, z)
Definition MD5.cpp:57
ppc ctr loops PowerPC CTR Loops Verify
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Value * RHS
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
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
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition Allocator.h:71
bool operator==(const const_iterator &Other) const
DomTreeNodeBase * operator*() const
const_iterator(DomTreeNodeBase *Node=nullptr)
Base class for the actual dominator tree node.
iterator_range< iterator > children()
DomTreeNodeBase(const DomTreeNodeBase &)=delete
void setIDom(DomTreeNodeBase *NewIDom)
void removeChild(DomTreeNodeBase *C)
DomTreeNodeBase * getIDom() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
iterator begin() const
DomTreeNodeBase & operator=(const DomTreeNodeBase &)=delete
DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
bool compare(const DomTreeNodeBase *Other) const
NodeT * getBlock() const
unsigned getLevel() const
iterator end() const
iterator_range< const_iterator > children() const
unsigned getDFSNumOut() const
void addChild(DomTreeNodeBase *C)
Core dominator tree base class.
DominatorTreeBase(DominatorTreeBase &&Arg)=default
DomTreeNodeTraits< BlockT > NodeTrait
bool isReachableFromEntry(const DomTreeNodeBase< NodeT > *A) const
void print(raw_ostream &O) const
print - Convert to human readable form
typename NodeTrait::NodeType NodeType
DomTreeNodeBase< NodeT > * operator[](const NodeT *BB) const
See getNode.
typename SmallVectorImpl< BlockT * >::iterator root_iterator
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(NodeT *BB, NodeT *NewBB)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
void Split(typename GraphTraits< N >::NodeRef NewBB)
iterator_range< root_iterator > roots()
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
std::remove_pointer_t< ParentPtr > ParentType
NodeT * findNearestCommonDominator(iterator_range< IteratorTy > Nodes) const
BumpPtrAllocatorImpl< MallocAllocator, SlabSize, SlabSize, 2 > NodeAllocator
bool isPostDominator() const
isPostDominator - Returns true if analysis based of postdoms
bool dominates(const NodeT *A, const NodeT *B) const
const NodeT * findNearestCommonDominator(const NodeT *A, const NodeT *B) const
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * createNode(NodeT *BB, DomTreeNodeBase< NodeT > *IDom=nullptr)
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.
std::enable_if_t< GraphHasNodeNumbers< T * >, void > updateBlockNumbers()
Update dominator tree after renumbering blocks.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
iterator_range< const_root_iterator > roots() const
const_root_iterator root_end() const
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
void recalculate(ParentType &Func, ArrayRef< UpdateType > Updates)
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
typename SmallVectorImpl< BlockT * >::const_iterator const_root_iterator
bool compare(const DominatorTreeBase &Other) const
compare - Return false if the other dominator tree base matches this dominator tree base.
DominatorTreeBase & operator=(DominatorTreeBase &&RHS)=default
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
SmallVector< DomTreeNodeBase< BlockT > * > DomTreeNodeStorageTy
root_iterator root_begin()
DominatorTreeBase(const DominatorTreeBase &)=delete
const_root_iterator root_begin() const
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
SmallVector< BlockT *, IsPostDom ? 4 :1 > Roots
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
const DomTreeNodeBase< NodeT > * getRootNode() const
std::conditional_t<!GraphHasNodeNumbers< BlockT * >, DenseMap< const BlockT *, unsigned >, std::tuple<> > NodeNumberMap
DomTreeNodeBase< BlockT > * RootNode
typename NodeTrait::NodePtr NodePtr
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
void applyUpdates(ArrayRef< UpdateType > Updates, ArrayRef< UpdateType > PostViewUpdates)
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const NodeT *A, const NodeT *B) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool isVirtualRoot(const DomTreeNodeBase< NodeT > *A) const
typename NodeTrait::ParentPtr ParentPtr
DominatorTreeBase & operator=(const DominatorTreeBase &)=delete
This class builds and contains all of the top-level loop structures in the specified function.
size_type size() const
Definition SmallPtrSet.h:99
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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...
typename SuperClass::const_iterator const_iterator
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
IteratorT begin() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
void PrintDomTree(const DomTreeNodeBase< NodeT > *N, raw_ostream &O, unsigned Lev)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
DominatorTreeBase< T, true > PostDomTreeBase
DominatorTreeBase< T, false > DomTreeBase
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:299
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:551
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N
Default DomTreeNode traits for NodeT.
static NodeT * getEntryNode(ParentPtr Parent)
std::remove_pointer_t< ParentPtr > ParentType
static ParentPtr getParent(NodePtr BB)
decltype(std::declval< NodePtr >() ->getParent()) ParentPtr
typename GraphType::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95