[PM] Split DominatorTree into a concrete analysis result object which
[oota-llvm.git] / include / llvm / Support / GenericDomTree.h
1 //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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
14 /// graph types.
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_SUPPORT_GENERIC_DOM_TREE_H
19 #define LLVM_SUPPORT_GENERIC_DOM_TREE_H
20
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"
29 #include <algorithm>
30
31 namespace llvm {
32
33 //===----------------------------------------------------------------------===//
34 /// DominatorBase - Base class that other, more interesting dominator analyses
35 /// inherit from.
36 ///
37 template <class NodeT>
38 class DominatorBase {
39 protected:
40   std::vector<NodeT*> Roots;
41   const bool IsPostDominators;
42   inline explicit DominatorBase(bool isPostDom) :
43     Roots(), IsPostDominators(isPostDom) {}
44 public:
45
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).
49   ///
50   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
51
52   /// isPostDominator - Returns true if analysis based of postdoms
53   ///
54   bool isPostDominator() const { return IsPostDominators; }
55 };
56
57
58 //===----------------------------------------------------------------------===//
59 // DomTreeNodeBase - Dominator Tree Node
60 template<class NodeT> class DominatorTreeBase;
61 struct PostDominatorTree;
62
63 template <class NodeT>
64 class DomTreeNodeBase {
65   NodeT *TheBB;
66   DomTreeNodeBase<NodeT> *IDom;
67   std::vector<DomTreeNodeBase<NodeT> *> Children;
68   mutable int DFSNumIn, DFSNumOut;
69
70   template<class N> friend class DominatorTreeBase;
71   friend struct PostDominatorTree;
72 public:
73   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
75                    const_iterator;
76
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(); }
81
82   NodeT *getBlock() const { return TheBB; }
83   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
84   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
85     return Children;
86   }
87
88   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
89     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
90
91   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
92     Children.push_back(C);
93     return C;
94   }
95
96   size_t getNumChildren() const {
97     return Children.size();
98   }
99
100   void clearAllChildren() {
101     Children.clear();
102   }
103
104   bool compare(const DomTreeNodeBase<NodeT> *Other) const {
105     if (getNumChildren() != Other->getNumChildren())
106       return true;
107
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);
112     }
113
114     for (const_iterator I = begin(), E = end(); I != E; ++I) {
115       const NodeT *N = (*I)->getBlock();
116       if (OtherChildren.count(N) == 0)
117         return true;
118     }
119     return false;
120   }
121
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);
131
132       // Switch to new dominator
133       IDom = NewIDom;
134       IDom->Children.push_back(this);
135     }
136   }
137
138   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
139   /// not call them.
140   unsigned getDFSNumIn() const { return DFSNumIn; }
141   unsigned getDFSNumOut() const { return DFSNumOut; }
142 private:
143   // Return true if this node is dominated by other. Use this only if DFS info
144   // is valid.
145   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146     return this->DFSNumIn >= other->DFSNumIn &&
147       this->DFSNumOut <= other->DFSNumOut;
148   }
149 };
150
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);
156   else
157     o << " <<exit node>>";
158
159   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
160
161   return o << "\n";
162 }
163
164 template<class NodeT>
165 inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
166                          unsigned Lev) {
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);
171 }
172
173 //===----------------------------------------------------------------------===//
174 /// DominatorTree - Calculate the immediate dominator tree for a function.
175 ///
176
177 template<class FuncT, class N>
178 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
179                FuncT& F);
180
181 template<class NodeT>
182 class DominatorTreeBase : public DominatorBase<NodeT> {
183   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
184                                const DomTreeNodeBase<NodeT> *B) const {
185     assert(A != B);
186     assert(isReachableFromEntry(B));
187     assert(isReachableFromEntry(A));
188
189     const DomTreeNodeBase<NodeT> *IDom;
190     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
191       B = IDom;   // Walk up the tree
192     return IDom != 0;
193   }
194
195 protected:
196   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
197   DomTreeNodeMapType DomTreeNodes;
198   DomTreeNodeBase<NodeT> *RootNode;
199
200   mutable bool DFSInfoValid;
201   mutable unsigned int SlowQueries;
202   // Information record used during immediate dominators computation.
203   struct InfoRec {
204     unsigned DFSNum;
205     unsigned Parent;
206     unsigned Semi;
207     NodeT *Label;
208
209     InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
210   };
211
212   DenseMap<NodeT*, NodeT*> IDoms;
213
214   // Vertex - Map the DFS number to the NodeT*
215   std::vector<NodeT*> Vertex;
216
217   // Info - Collection of information used during the computation of idoms.
218   DenseMap<NodeT*, InfoRec> Info;
219
220   void reset() {
221     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
222            E = DomTreeNodes.end(); I != E; ++I)
223       delete I->second;
224     DomTreeNodes.clear();
225     IDoms.clear();
226     this->Roots.clear();
227     Vertex.clear();
228     RootNode = 0;
229   }
230
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);
240
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);
247
248     assert(!PredBlocks.empty() && "No predblocks?");
249
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;
258         break;
259       }
260     }
261
262     // Find NewBB's immediate dominator and create new dominator tree node for
263     // NewBB.
264     NodeT *NewBBIDom = 0;
265     unsigned i = 0;
266     for (i = 0; i < PredBlocks.size(); ++i)
267       if (DT.isReachableFromEntry(PredBlocks[i])) {
268         NewBBIDom = PredBlocks[i];
269         break;
270       }
271
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
274     // changed.
275     if (!NewBBIDom)
276       return;
277
278     for (i = i + 1; i < PredBlocks.size(); ++i) {
279       if (DT.isReachableFromEntry(PredBlocks[i]))
280         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
281     }
282
283     // Create the new dominator tree node... and set the idom of NewBB.
284     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
285
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);
291     }
292   }
293
294 public:
295   explicit DominatorTreeBase(bool isPostDom)
296     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
297   virtual ~DominatorTreeBase() { reset(); }
298
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 {
302
303     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
304     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
305       return true;
306
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())
313         return true;
314
315       DomTreeNodeBase<NodeT>* MyNd = I->second;
316       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
317
318       if (MyNd->compare(OtherNd))
319         return true;
320     }
321
322     return false;
323   }
324
325   virtual void releaseMemory() { reset(); }
326
327   /// getNode - return the (Post)DominatorTree node for the specified basic
328   /// block.  This is the same as using operator[] on this class.
329   ///
330   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
331     return DomTreeNodes.lookup(BB);
332   }
333
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
339   /// possibility.
340   ///
341   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
342   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
343
344   /// Get all nodes dominated by R, including R itself.
345   void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
346     Result.clear();
347     const DomTreeNodeBase<NodeT> *RN = getNode(R);
348     if (RN == NULL)
349       return; // If R is unreachable, it will not be present in the DOM tree.
350     SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
351     WL.push_back(RN);
352
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());
357     }
358   }
359
360   /// properlyDominates - Returns true iff A dominates B and A != B.
361   /// Note that this is not a constant time operation!
362   ///
363   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
364                          const DomTreeNodeBase<NodeT> *B) const {
365     if (A == 0 || B == 0)
366       return false;
367     if (A == B)
368       return false;
369     return dominates(A, B);
370   }
371
372   bool properlyDominates(const NodeT *A, const NodeT *B) const;
373
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)));
380   }
381
382   inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
383     return A;
384   }
385
386   /// dominates - Returns true iff A dominates B.  Note that this is not a
387   /// constant time operation!
388   ///
389   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
390                         const DomTreeNodeBase<NodeT> *B) const {
391     // A node trivially dominates itself.
392     if (B == A)
393       return true;
394
395     // An unreachable node is dominated by anything.
396     if (!isReachableFromEntry(B))
397       return true;
398
399     // And dominates nothing.
400     if (!isReachableFromEntry(A))
401       return false;
402
403     // Compare the result of the tree walk and the dfs numbers, if expensive
404     // checks are enabled.
405 #ifdef XDEBUG
406     assert((!DFSInfoValid ||
407             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
408            "Tree walk disagrees with dfs numbers!");
409 #endif
410
411     if (DFSInfoValid)
412       return B->DominatedBy(A);
413
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.
416     SlowQueries++;
417     if (SlowQueries > 32) {
418       updateDFSNumbers();
419       return B->DominatedBy(A);
420     }
421
422     return dominatedBySlowTreeWalk(A, B);
423   }
424
425   bool dominates(const NodeT *A, const NodeT *B) const;
426
427   NodeT *getRoot() const {
428     assert(this->Roots.size() == 1 && "Should always have entry node!");
429     return this->Roots[0];
430   }
431
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");
437
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)
443         return &Entry;
444     }
445
446     // If B dominates A then B is nearest common dominator.
447     if (dominates(B, A))
448       return B;
449
450     // If A dominates B then A is nearest common dominator.
451     if (dominates(A, B))
452       return A;
453
454     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
455     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
456
457     // Collect NodeA dominators set.
458     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
459     NodeADoms.insert(NodeA);
460     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
461     while (IDomA) {
462       NodeADoms.insert(IDomA);
463       IDomA = IDomA->getIDom();
464     }
465
466     // Walk NodeB immediate dominators chain and find common dominator node.
467     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
468     while (IDomB) {
469       if (NodeADoms.count(IDomB) != 0)
470         return IDomB->getBlock();
471
472       IDomB = IDomB->getIDom();
473     }
474
475     return NULL;
476   }
477
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));
483   }
484
485   //===--------------------------------------------------------------------===//
486   // API to update (Post)DominatorTree information based on modifications to
487   // the CFG...
488
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));
499   }
500
501   /// changeImmediateDominator - This method is used to update the dominator
502   /// tree information when a node's immediate dominator changes.
503   ///
504   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
505                                 DomTreeNodeBase<NodeT> *NewIDom) {
506     assert(N && NewIDom && "Cannot change null node pointers!");
507     DFSInfoValid = false;
508     N->setIDom(NewIDom);
509   }
510
511   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
512     changeImmediateDominator(getNode(BB), getNode(NewBB));
513   }
514
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.");
522
523       // Remove node from immediate dominator's children list.
524     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
525     if (IDom) {
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);
532     }
533
534     DomTreeNodes.erase(BB);
535     delete Node;
536   }
537
538   /// removeNode - Removes a node from the dominator tree.  Block must not
539   /// dominate any other blocks.  Invalidates any node pointing to removed
540   /// block.
541   void removeNode(NodeT *BB) {
542     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
543     DomTreeNodes.erase(BB);
544   }
545
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);
551     else
552       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
553   }
554
555   /// print - Convert to human readable form
556   ///
557   void print(raw_ostream &o) const {
558     o << "=============================--------------------------------\n";
559     if (this->isPostDominator())
560       o << "Inorder PostDominator Tree: ";
561     else
562       o << "Inorder Dominator Tree: ";
563     if (!this->DFSInfoValid)
564       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
565     o << "\n";
566
567     // The postdom tree can have a null root if there are no returns.
568     if (getRootNode())
569       PrintDomTree<NodeT>(getRootNode(), o, 1);
570   }
571
572 protected:
573   template<class GraphT>
574   friend typename GraphT::NodeType* Eval(
575                                DominatorTreeBase<typename GraphT::NodeType>& DT,
576                                          typename GraphT::NodeType* V,
577                                          unsigned LastLinked);
578
579   template<class GraphT>
580   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
581                           typename GraphT::NodeType* V,
582                           unsigned N);
583
584   template<class FuncT, class N>
585   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
586                         FuncT& F);
587
588   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
589   /// dominator tree in dfs order.
590   void updateDFSNumbers() const {
591     unsigned DFSNum = 0;
592
593     SmallVector<std::pair<const DomTreeNodeBase<NodeT>*,
594                 typename DomTreeNodeBase<NodeT>::const_iterator>, 32> WorkStack;
595
596     const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
597
598     if (!ThisRoot)
599       return;
600
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++;
607
608     while (!WorkStack.empty()) {
609       const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
610       typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
611         WorkStack.back().second;
612
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();
618       } else {
619         // Otherwise, recursively visit this child.
620         const DomTreeNodeBase<NodeT> *Child = *ChildIt;
621         ++WorkStack.back().second;
622
623         WorkStack.push_back(std::make_pair(Child, Child->begin()));
624         Child->DFSNumIn = DFSNum++;
625       }
626     }
627
628     SlowQueries = 0;
629     DFSInfoValid = true;
630   }
631
632   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
633     if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
634       return Node;
635
636     // Haven't calculated this node yet?  Get or calculate the node for the
637     // immediate dominator.
638     NodeT *IDom = getIDom(BB);
639
640     assert(IDom || this->DomTreeNodes[NULL]);
641     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
642
643     // Add a new tree node for this NodeT, and link it as a child of
644     // IDomNode
645     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
646     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
647   }
648
649   inline NodeT *getIDom(NodeT *BB) const {
650     return IDoms.lookup(BB);
651   }
652
653   inline void addRoot(NodeT* BB) {
654     this->Roots.push_back(BB);
655   }
656
657 public:
658   /// recalculate - compute a dominator tree for the given function
659   template<class FT>
660   void recalculate(FT& F) {
661     typedef GraphTraits<FT*> TraitsTy;
662     reset();
663     this->Vertex.push_back(0);
664
665     if (!this->IsPostDominators) {
666       // Initialize root
667       NodeT *entry = TraitsTy::getEntryNode(&F);
668       this->Roots.push_back(entry);
669       this->IDoms[entry] = 0;
670       this->DomTreeNodes[entry] = 0;
671
672       Calculate<FT, NodeT*>(*this, F);
673     } else {
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))
678           addRoot(I);
679
680         // Prepopulate maps so that we don't get iterator invalidation issues later.
681         this->IDoms[I] = 0;
682         this->DomTreeNodes[I] = 0;
683       }
684
685       Calculate<FT, Inverse<NodeT*> >(*this, F);
686     }
687   }
688 };
689
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 {
694   if (A == B)
695     return true;
696
697   // Cast away the const qualifiers here. This is ok since
698   // this function doesn't actually return the values returned
699   // from getNode.
700   return dominates(getNode(const_cast<NodeT *>(A)),
701                    getNode(const_cast<NodeT *>(B)));
702 }
703 template<class NodeT>
704 bool
705 DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) const {
706   if (A == B)
707     return false;
708
709   // Cast away the const qualifiers here. This is ok since
710   // this function doesn't actually return the values returned
711   // from getNode.
712   return dominates(getNode(const_cast<NodeT *>(A)),
713                    getNode(const_cast<NodeT *>(B)));
714 }
715
716 }
717
718 #endif