1 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file defines a set of templates that efficiently compute a dominator
12 /// tree over a generic graph. This is used typically in LLVM for fast
13 /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_SUPPORT_GENERIC_DOM_TREE_H
19 #define LLVM_SUPPORT_GENERIC_DOM_TREE_H
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/GraphTraits.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/raw_ostream.h"
33 //===----------------------------------------------------------------------===//
34 /// DominatorBase - Base class that other, more interesting dominator analyses
37 template <class NodeT>
40 std::vector<NodeT*> Roots;
41 const bool IsPostDominators;
42 inline explicit DominatorBase(bool isPostDom) :
43 Roots(), IsPostDominators(isPostDom) {}
46 /// getRoots - Return the root blocks of the current CFG. This may include
47 /// multiple blocks if we are computing post dominators. For forward
48 /// dominators, this will always be a single block (the entry node).
50 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
52 /// isPostDominator - Returns true if analysis based of postdoms
54 bool isPostDominator() const { return IsPostDominators; }
58 //===----------------------------------------------------------------------===//
59 // DomTreeNodeBase - Dominator Tree Node
60 template<class NodeT> class DominatorTreeBase;
61 struct PostDominatorTree;
63 template <class NodeT>
64 class DomTreeNodeBase {
66 DomTreeNodeBase<NodeT> *IDom;
67 std::vector<DomTreeNodeBase<NodeT> *> Children;
68 mutable int DFSNumIn, DFSNumOut;
70 template<class N> friend class DominatorTreeBase;
71 friend struct PostDominatorTree;
73 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
77 iterator begin() { return Children.begin(); }
78 iterator end() { return Children.end(); }
79 const_iterator begin() const { return Children.begin(); }
80 const_iterator end() const { return Children.end(); }
82 NodeT *getBlock() const { return TheBB; }
83 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
84 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
88 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
89 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
91 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
92 Children.push_back(C);
96 size_t getNumChildren() const {
97 return Children.size();
100 void clearAllChildren() {
104 bool compare(const DomTreeNodeBase<NodeT> *Other) const {
105 if (getNumChildren() != Other->getNumChildren())
108 SmallPtrSet<const NodeT *, 4> OtherChildren;
109 for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110 const NodeT *Nd = (*I)->getBlock();
111 OtherChildren.insert(Nd);
114 for (const_iterator I = begin(), E = end(); I != E; ++I) {
115 const NodeT *N = (*I)->getBlock();
116 if (OtherChildren.count(N) == 0)
122 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
123 assert(IDom && "No immediate dominator?");
124 if (IDom != NewIDom) {
125 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
126 std::find(IDom->Children.begin(), IDom->Children.end(), this);
127 assert(I != IDom->Children.end() &&
128 "Not in immediate dominator children set!");
129 // I am no longer your child...
130 IDom->Children.erase(I);
132 // Switch to new dominator
134 IDom->Children.push_back(this);
138 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
140 unsigned getDFSNumIn() const { return DFSNumIn; }
141 unsigned getDFSNumOut() const { return DFSNumOut; }
143 // Return true if this node is dominated by other. Use this only if DFS info
145 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146 return this->DFSNumIn >= other->DFSNumIn &&
147 this->DFSNumOut <= other->DFSNumOut;
151 template<class NodeT>
152 inline raw_ostream &operator<<(raw_ostream &o,
153 const DomTreeNodeBase<NodeT> *Node) {
154 if (Node->getBlock())
155 Node->getBlock()->printAsOperand(o, false);
157 o << " <<exit node>>";
159 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
164 template<class NodeT>
165 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
167 o.indent(2*Lev) << "[" << Lev << "] " << N;
168 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
169 E = N->end(); I != E; ++I)
170 PrintDomTree<NodeT>(*I, o, Lev+1);
173 //===----------------------------------------------------------------------===//
174 /// DominatorTree - Calculate the immediate dominator tree for a function.
177 template<class FuncT, class N>
178 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
181 template<class NodeT>
182 class DominatorTreeBase : public DominatorBase<NodeT> {
183 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
184 const DomTreeNodeBase<NodeT> *B) const {
186 assert(isReachableFromEntry(B));
187 assert(isReachableFromEntry(A));
189 const DomTreeNodeBase<NodeT> *IDom;
190 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
191 B = IDom; // Walk up the tree
196 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
197 DomTreeNodeMapType DomTreeNodes;
198 DomTreeNodeBase<NodeT> *RootNode;
200 mutable bool DFSInfoValid;
201 mutable unsigned int SlowQueries;
202 // Information record used during immediate dominators computation.
209 InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
212 DenseMap<NodeT*, NodeT*> IDoms;
214 // Vertex - Map the DFS number to the NodeT*
215 std::vector<NodeT*> Vertex;
217 // Info - Collection of information used during the computation of idoms.
218 DenseMap<NodeT*, InfoRec> Info;
221 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
222 E = DomTreeNodes.end(); I != E; ++I)
224 DomTreeNodes.clear();
231 // NewBB is split and now it has one successor. Update dominator tree to
232 // reflect this change.
233 template<class N, class GraphT>
234 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
235 typename GraphT::NodeType* NewBB) {
236 assert(std::distance(GraphT::child_begin(NewBB),
237 GraphT::child_end(NewBB)) == 1 &&
238 "NewBB should have a single successor!");
239 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
241 std::vector<typename GraphT::NodeType*> PredBlocks;
242 typedef GraphTraits<Inverse<N> > InvTraits;
243 for (typename InvTraits::ChildIteratorType PI =
244 InvTraits::child_begin(NewBB),
245 PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
246 PredBlocks.push_back(*PI);
248 assert(!PredBlocks.empty() && "No predblocks?");
250 bool NewBBDominatesNewBBSucc = true;
251 for (typename InvTraits::ChildIteratorType PI =
252 InvTraits::child_begin(NewBBSucc),
253 E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
254 typename InvTraits::NodeType *ND = *PI;
255 if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
256 DT.isReachableFromEntry(ND)) {
257 NewBBDominatesNewBBSucc = false;
262 // Find NewBB's immediate dominator and create new dominator tree node for
264 NodeT *NewBBIDom = 0;
266 for (i = 0; i < PredBlocks.size(); ++i)
267 if (DT.isReachableFromEntry(PredBlocks[i])) {
268 NewBBIDom = PredBlocks[i];
272 // It's possible that none of the predecessors of NewBB are reachable;
273 // in that case, NewBB itself is unreachable, so nothing needs to be
278 for (i = i + 1; i < PredBlocks.size(); ++i) {
279 if (DT.isReachableFromEntry(PredBlocks[i]))
280 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
283 // Create the new dominator tree node... and set the idom of NewBB.
284 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
286 // If NewBB strictly dominates other blocks, then it is now the immediate
287 // dominator of NewBBSucc. Update the dominator tree as appropriate.
288 if (NewBBDominatesNewBBSucc) {
289 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
290 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
295 explicit DominatorTreeBase(bool isPostDom)
296 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
297 virtual ~DominatorTreeBase() { reset(); }
299 /// compare - Return false if the other dominator tree base matches this
300 /// dominator tree base. Otherwise return true.
301 bool compare(const DominatorTreeBase &Other) const {
303 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
304 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
307 for (typename DomTreeNodeMapType::const_iterator
308 I = this->DomTreeNodes.begin(),
309 E = this->DomTreeNodes.end(); I != E; ++I) {
310 NodeT *BB = I->first;
311 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
312 if (OI == OtherDomTreeNodes.end())
315 DomTreeNodeBase<NodeT>* MyNd = I->second;
316 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
318 if (MyNd->compare(OtherNd))
325 virtual void releaseMemory() { reset(); }
327 /// getNode - return the (Post)DominatorTree node for the specified basic
328 /// block. This is the same as using operator[] on this class.
330 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
331 return DomTreeNodes.lookup(BB);
334 /// getRootNode - This returns the entry node for the CFG of the function. If
335 /// this tree represents the post-dominance relations for a function, however,
336 /// this root may be a node with the block == NULL. This is the case when
337 /// there are multiple exit nodes from a particular function. Consumers of
338 /// post-dominance information must be capable of dealing with this
341 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
342 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
344 /// Get all nodes dominated by R, including R itself.
345 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
347 const DomTreeNodeBase<NodeT> *RN = getNode(R);
349 return; // If R is unreachable, it will not be present in the DOM tree.
350 SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
353 while (!WL.empty()) {
354 const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
355 Result.push_back(N->getBlock());
356 WL.append(N->begin(), N->end());
360 /// properlyDominates - Returns true iff A dominates B and A != B.
361 /// Note that this is not a constant time operation!
363 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
364 const DomTreeNodeBase<NodeT> *B) const {
365 if (A == 0 || B == 0)
369 return dominates(A, B);
372 bool properlyDominates(const NodeT *A, const NodeT *B) const;
374 /// isReachableFromEntry - Return true if A is dominated by the entry
375 /// block of the function containing it.
376 bool isReachableFromEntry(const NodeT* A) const {
377 assert(!this->isPostDominator() &&
378 "This is not implemented for post dominators");
379 return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
382 inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
386 /// dominates - Returns true iff A dominates B. Note that this is not a
387 /// constant time operation!
389 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
390 const DomTreeNodeBase<NodeT> *B) const {
391 // A node trivially dominates itself.
395 // An unreachable node is dominated by anything.
396 if (!isReachableFromEntry(B))
399 // And dominates nothing.
400 if (!isReachableFromEntry(A))
403 // Compare the result of the tree walk and the dfs numbers, if expensive
404 // checks are enabled.
406 assert((!DFSInfoValid ||
407 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
408 "Tree walk disagrees with dfs numbers!");
412 return B->DominatedBy(A);
414 // If we end up with too many slow queries, just update the
415 // DFS numbers on the theory that we are going to keep querying.
417 if (SlowQueries > 32) {
419 return B->DominatedBy(A);
422 return dominatedBySlowTreeWalk(A, B);
425 bool dominates(const NodeT *A, const NodeT *B) const;
427 NodeT *getRoot() const {
428 assert(this->Roots.size() == 1 && "Should always have entry node!");
429 return this->Roots[0];
432 /// findNearestCommonDominator - Find nearest common dominator basic block
433 /// for basic block A and B. If there is no such block then return NULL.
434 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
435 assert(A->getParent() == B->getParent() &&
436 "Two blocks are not in same function");
438 // If either A or B is a entry block then it is nearest common dominator
439 // (for forward-dominators).
440 if (!this->isPostDominator()) {
441 NodeT &Entry = A->getParent()->front();
442 if (A == &Entry || B == &Entry)
446 // If B dominates A then B is nearest common dominator.
450 // If A dominates B then A is nearest common dominator.
454 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
455 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
457 // Collect NodeA dominators set.
458 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
459 NodeADoms.insert(NodeA);
460 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
462 NodeADoms.insert(IDomA);
463 IDomA = IDomA->getIDom();
466 // Walk NodeB immediate dominators chain and find common dominator node.
467 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
469 if (NodeADoms.count(IDomB) != 0)
470 return IDomB->getBlock();
472 IDomB = IDomB->getIDom();
478 const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
479 // Cast away the const qualifiers here. This is ok since
480 // const is re-introduced on the return type.
481 return findNearestCommonDominator(const_cast<NodeT *>(A),
482 const_cast<NodeT *>(B));
485 //===--------------------------------------------------------------------===//
486 // API to update (Post)DominatorTree information based on modifications to
489 /// addNewBlock - Add a new node to the dominator tree information. This
490 /// creates a new node as a child of DomBB dominator node,linking it into
491 /// the children list of the immediate dominator.
492 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
493 assert(getNode(BB) == 0 && "Block already in dominator tree!");
494 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
495 assert(IDomNode && "Not immediate dominator specified for block!");
496 DFSInfoValid = false;
497 return DomTreeNodes[BB] =
498 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
501 /// changeImmediateDominator - This method is used to update the dominator
502 /// tree information when a node's immediate dominator changes.
504 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
505 DomTreeNodeBase<NodeT> *NewIDom) {
506 assert(N && NewIDom && "Cannot change null node pointers!");
507 DFSInfoValid = false;
511 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
512 changeImmediateDominator(getNode(BB), getNode(NewBB));
515 /// eraseNode - Removes a node from the dominator tree. Block must not
516 /// dominate any other blocks. Removes node from its immediate dominator's
517 /// children list. Deletes dominator node associated with basic block BB.
518 void eraseNode(NodeT *BB) {
519 DomTreeNodeBase<NodeT> *Node = getNode(BB);
520 assert(Node && "Removing node that isn't in dominator tree.");
521 assert(Node->getChildren().empty() && "Node is not a leaf node.");
523 // Remove node from immediate dominator's children list.
524 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
526 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
527 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
528 assert(I != IDom->Children.end() &&
529 "Not in immediate dominator children set!");
530 // I am no longer your child...
531 IDom->Children.erase(I);
534 DomTreeNodes.erase(BB);
538 /// removeNode - Removes a node from the dominator tree. Block must not
539 /// dominate any other blocks. Invalidates any node pointing to removed
541 void removeNode(NodeT *BB) {
542 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
543 DomTreeNodes.erase(BB);
546 /// splitBlock - BB is split and now it has one successor. Update dominator
547 /// tree to reflect this change.
548 void splitBlock(NodeT* NewBB) {
549 if (this->IsPostDominators)
550 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
552 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
555 /// print - Convert to human readable form
557 void print(raw_ostream &o) const {
558 o << "=============================--------------------------------\n";
559 if (this->isPostDominator())
560 o << "Inorder PostDominator Tree: ";
562 o << "Inorder Dominator Tree: ";
563 if (!this->DFSInfoValid)
564 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
567 // The postdom tree can have a null root if there are no returns.
569 PrintDomTree<NodeT>(getRootNode(), o, 1);
573 template<class GraphT>
574 friend typename GraphT::NodeType* Eval(
575 DominatorTreeBase<typename GraphT::NodeType>& DT,
576 typename GraphT::NodeType* V,
577 unsigned LastLinked);
579 template<class GraphT>
580 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
581 typename GraphT::NodeType* V,
584 template<class FuncT, class N>
585 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
588 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
589 /// dominator tree in dfs order.
590 void updateDFSNumbers() const {
593 SmallVector<std::pair<const DomTreeNodeBase<NodeT>*,
594 typename DomTreeNodeBase<NodeT>::const_iterator>, 32> WorkStack;
596 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
601 // Even in the case of multiple exits that form the post dominator root
602 // nodes, do not iterate over all exits, but start from the virtual root
603 // node. Otherwise bbs, that are not post dominated by any exit but by the
604 // virtual root node, will never be assigned a DFS number.
605 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
606 ThisRoot->DFSNumIn = DFSNum++;
608 while (!WorkStack.empty()) {
609 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
610 typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
611 WorkStack.back().second;
613 // If we visited all of the children of this node, "recurse" back up the
614 // stack setting the DFOutNum.
615 if (ChildIt == Node->end()) {
616 Node->DFSNumOut = DFSNum++;
617 WorkStack.pop_back();
619 // Otherwise, recursively visit this child.
620 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
621 ++WorkStack.back().second;
623 WorkStack.push_back(std::make_pair(Child, Child->begin()));
624 Child->DFSNumIn = DFSNum++;
632 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
633 if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
636 // Haven't calculated this node yet? Get or calculate the node for the
637 // immediate dominator.
638 NodeT *IDom = getIDom(BB);
640 assert(IDom || this->DomTreeNodes[NULL]);
641 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
643 // Add a new tree node for this NodeT, and link it as a child of
645 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
646 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
649 inline NodeT *getIDom(NodeT *BB) const {
650 return IDoms.lookup(BB);
653 inline void addRoot(NodeT* BB) {
654 this->Roots.push_back(BB);
658 /// recalculate - compute a dominator tree for the given function
660 void recalculate(FT& F) {
661 typedef GraphTraits<FT*> TraitsTy;
663 this->Vertex.push_back(0);
665 if (!this->IsPostDominators) {
667 NodeT *entry = TraitsTy::getEntryNode(&F);
668 this->Roots.push_back(entry);
669 this->IDoms[entry] = 0;
670 this->DomTreeNodes[entry] = 0;
672 Calculate<FT, NodeT*>(*this, F);
674 // Initialize the roots list
675 for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
676 E = TraitsTy::nodes_end(&F); I != E; ++I) {
677 if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
680 // Prepopulate maps so that we don't get iterator invalidation issues later.
682 this->DomTreeNodes[I] = 0;
685 Calculate<FT, Inverse<NodeT*> >(*this, F);
690 // These two functions are declared out of line as a workaround for building
691 // with old (< r147295) versions of clang because of pr11642.
692 template<class NodeT>
693 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
697 // Cast away the const qualifiers here. This is ok since
698 // this function doesn't actually return the values returned
700 return dominates(getNode(const_cast<NodeT *>(A)),
701 getNode(const_cast<NodeT *>(B)));
703 template<class NodeT>
705 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) const {
709 // Cast away the const qualifiers here. This is ok since
710 // this function doesn't actually return the values returned
712 return dominates(getNode(const_cast<NodeT *>(A)),
713 getNode(const_cast<NodeT *>(B)));