split dom frontier handling stuff out to its own DominanceFrontier header,
[oota-llvm.git] / include / llvm / Analysis / Dominators.h
1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- 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 //
10 // This file defines the DominatorTree class, which provides fast and efficient
11 // dominance queries.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_DOMINATORS_H
16 #define LLVM_ANALYSIS_DOMINATORS_H
17
18 #include "llvm/Pass.h"
19 #include "llvm/Function.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/GraphTraits.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29
30 namespace llvm {
31
32 //===----------------------------------------------------------------------===//
33 /// DominatorBase - Base class that other, more interesting dominator analyses
34 /// inherit from.
35 ///
36 template <class NodeT>
37 class DominatorBase {
38 protected:
39   std::vector<NodeT*> Roots;
40   const bool IsPostDominators;
41   inline explicit DominatorBase(bool isPostDom) :
42     Roots(), IsPostDominators(isPostDom) {}
43 public:
44
45   /// getRoots - Return the root blocks of the current CFG.  This may include
46   /// multiple blocks if we are computing post dominators.  For forward
47   /// dominators, this will always be a single block (the entry node).
48   ///
49   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
50
51   /// isPostDominator - Returns true if analysis based of postdoms
52   ///
53   bool isPostDominator() const { return IsPostDominators; }
54 };
55
56
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 template<class NodeT> class DominatorTreeBase;
60 struct PostDominatorTree;
61 class MachineBasicBlock;
62
63 template <class NodeT>
64 class DomTreeNodeBase {
65   NodeT *TheBB;
66   DomTreeNodeBase<NodeT> *IDom;
67   std::vector<DomTreeNodeBase<NodeT> *> Children;
68   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(DomTreeNodeBase<NodeT> *Other) {
105     if (getNumChildren() != Other->getNumChildren())
106       return true;
107
108     SmallPtrSet<NodeT *, 4> OtherChildren;
109     for (iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110       NodeT *Nd = (*I)->getBlock();
111       OtherChildren.insert(Nd);
112     }
113
114     for (iterator I = begin(), E = end(); I != E; ++I) {
115       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 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
152 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
153
154 template<class NodeT>
155 static raw_ostream &operator<<(raw_ostream &o,
156                                const DomTreeNodeBase<NodeT> *Node) {
157   if (Node->getBlock())
158     WriteAsOperand(o, Node->getBlock(), false);
159   else
160     o << " <<exit node>>";
161
162   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
163
164   return o << "\n";
165 }
166
167 template<class NodeT>
168 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
169                          unsigned Lev) {
170   o.indent(2*Lev) << "[" << Lev << "] " << N;
171   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172        E = N->end(); I != E; ++I)
173     PrintDomTree<NodeT>(*I, o, Lev+1);
174 }
175
176 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
177
178 //===----------------------------------------------------------------------===//
179 /// DominatorTree - Calculate the immediate dominator tree for a function.
180 ///
181
182 template<class FuncT, class N>
183 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
184                FuncT& F);
185
186 template<class NodeT>
187 class DominatorTreeBase : public DominatorBase<NodeT> {
188 protected:
189   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
190   DomTreeNodeMapType DomTreeNodes;
191   DomTreeNodeBase<NodeT> *RootNode;
192
193   bool DFSInfoValid;
194   unsigned int SlowQueries;
195   // Information record used during immediate dominators computation.
196   struct InfoRec {
197     unsigned DFSNum;
198     unsigned Semi;
199     unsigned Size;
200     NodeT *Label, *Child;
201     unsigned Parent, Ancestor;
202
203     InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
204                 Ancestor(0) {}
205   };
206
207   DenseMap<NodeT*, NodeT*> IDoms;
208
209   // Vertex - Map the DFS number to the BasicBlock*
210   std::vector<NodeT*> Vertex;
211
212   // Info - Collection of information used during the computation of idoms.
213   DenseMap<NodeT*, InfoRec> Info;
214
215   void reset() {
216     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
217            E = DomTreeNodes.end(); I != E; ++I)
218       delete I->second;
219     DomTreeNodes.clear();
220     IDoms.clear();
221     this->Roots.clear();
222     Vertex.clear();
223     RootNode = 0;
224   }
225
226   // NewBB is split and now it has one successor. Update dominator tree to
227   // reflect this change.
228   template<class N, class GraphT>
229   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
230              typename GraphT::NodeType* NewBB) {
231     assert(std::distance(GraphT::child_begin(NewBB),
232                          GraphT::child_end(NewBB)) == 1 &&
233            "NewBB should have a single successor!");
234     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
235
236     std::vector<typename GraphT::NodeType*> PredBlocks;
237     typedef GraphTraits<Inverse<N> > InvTraits;
238     for (typename InvTraits::ChildIteratorType PI =
239          InvTraits::child_begin(NewBB),
240          PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
241       PredBlocks.push_back(*PI);
242
243     assert(!PredBlocks.empty() && "No predblocks?");
244
245     bool NewBBDominatesNewBBSucc = true;
246     for (typename InvTraits::ChildIteratorType PI =
247          InvTraits::child_begin(NewBBSucc),
248          E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
249       typename InvTraits::NodeType *ND = *PI;
250       if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
251           DT.isReachableFromEntry(ND)) {
252         NewBBDominatesNewBBSucc = false;
253         break;
254       }
255     }
256
257     // Find NewBB's immediate dominator and create new dominator tree node for
258     // NewBB.
259     NodeT *NewBBIDom = 0;
260     unsigned i = 0;
261     for (i = 0; i < PredBlocks.size(); ++i)
262       if (DT.isReachableFromEntry(PredBlocks[i])) {
263         NewBBIDom = PredBlocks[i];
264         break;
265       }
266
267     // It's possible that none of the predecessors of NewBB are reachable;
268     // in that case, NewBB itself is unreachable, so nothing needs to be
269     // changed.
270     if (!NewBBIDom)
271       return;
272
273     for (i = i + 1; i < PredBlocks.size(); ++i) {
274       if (DT.isReachableFromEntry(PredBlocks[i]))
275         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
276     }
277
278     // Create the new dominator tree node... and set the idom of NewBB.
279     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
280
281     // If NewBB strictly dominates other blocks, then it is now the immediate
282     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
283     if (NewBBDominatesNewBBSucc) {
284       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
285       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
286     }
287   }
288
289 public:
290   explicit DominatorTreeBase(bool isPostDom)
291     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
292   virtual ~DominatorTreeBase() { reset(); }
293
294   /// compare - Return false if the other dominator tree base matches this
295   /// dominator tree base. Otherwise return true.
296   bool compare(DominatorTreeBase &Other) const {
297
298     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
299     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
300       return true;
301
302     for (typename DomTreeNodeMapType::const_iterator
303            I = this->DomTreeNodes.begin(),
304            E = this->DomTreeNodes.end(); I != E; ++I) {
305       NodeT *BB = I->first;
306       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
307       if (OI == OtherDomTreeNodes.end())
308         return true;
309
310       DomTreeNodeBase<NodeT>* MyNd = I->second;
311       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
312
313       if (MyNd->compare(OtherNd))
314         return true;
315     }
316
317     return false;
318   }
319
320   virtual void releaseMemory() { reset(); }
321
322   /// getNode - return the (Post)DominatorTree node for the specified basic
323   /// block.  This is the same as using operator[] on this class.
324   ///
325   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
326     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
327     return I != DomTreeNodes.end() ? I->second : 0;
328   }
329
330   /// getRootNode - This returns the entry node for the CFG of the function.  If
331   /// this tree represents the post-dominance relations for a function, however,
332   /// this root may be a node with the block == NULL.  This is the case when
333   /// there are multiple exit nodes from a particular function.  Consumers of
334   /// post-dominance information must be capable of dealing with this
335   /// possibility.
336   ///
337   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
338   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
339
340   /// properlyDominates - Returns true iff this dominates N and this != N.
341   /// Note that this is not a constant time operation!
342   ///
343   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
344                          const DomTreeNodeBase<NodeT> *B) const {
345     if (A == 0 || B == 0) return false;
346     return dominatedBySlowTreeWalk(A, B);
347   }
348
349   inline bool properlyDominates(const NodeT *A, const NodeT *B) {
350     if (A == B)
351       return false;
352
353     // Cast away the const qualifiers here. This is ok since
354     // this function doesn't actually return the values returned
355     // from getNode.
356     return properlyDominates(getNode(const_cast<NodeT *>(A)),
357                              getNode(const_cast<NodeT *>(B)));
358   }
359
360   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
361                                const DomTreeNodeBase<NodeT> *B) const {
362     const DomTreeNodeBase<NodeT> *IDom;
363     if (A == 0 || B == 0) return false;
364     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
365       B = IDom;   // Walk up the tree
366     return IDom != 0;
367   }
368
369
370   /// isReachableFromEntry - Return true if A is dominated by the entry
371   /// block of the function containing it.
372   bool isReachableFromEntry(const NodeT* A) {
373     assert(!this->isPostDominator() &&
374            "This is not implemented for post dominators");
375     return dominates(&A->getParent()->front(), A);
376   }
377
378   /// dominates - Returns true iff A dominates B.  Note that this is not a
379   /// constant time operation!
380   ///
381   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
382                         const DomTreeNodeBase<NodeT> *B) {
383     if (B == A)
384       return true;  // A node trivially dominates itself.
385
386     if (A == 0 || B == 0)
387       return false;
388
389     // Compare the result of the tree walk and the dfs numbers, if expensive
390     // checks are enabled.
391 #ifdef XDEBUG
392     assert((!DFSInfoValid ||
393             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
394            "Tree walk disagrees with dfs numbers!");
395 #endif
396
397     if (DFSInfoValid)
398       return B->DominatedBy(A);
399
400     // If we end up with too many slow queries, just update the
401     // DFS numbers on the theory that we are going to keep querying.
402     SlowQueries++;
403     if (SlowQueries > 32) {
404       updateDFSNumbers();
405       return B->DominatedBy(A);
406     }
407
408     return dominatedBySlowTreeWalk(A, B);
409   }
410
411   inline bool dominates(const NodeT *A, const NodeT *B) {
412     if (A == B)
413       return true;
414
415     // Cast away the const qualifiers here. This is ok since
416     // this function doesn't actually return the values returned
417     // from getNode.
418     return dominates(getNode(const_cast<NodeT *>(A)),
419                      getNode(const_cast<NodeT *>(B)));
420   }
421
422   NodeT *getRoot() const {
423     assert(this->Roots.size() == 1 && "Should always have entry node!");
424     return this->Roots[0];
425   }
426
427   /// findNearestCommonDominator - Find nearest common dominator basic block
428   /// for basic block A and B. If there is no such block then return NULL.
429   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
430     assert(A->getParent() == B->getParent() &&
431            "Two blocks are not in same function");
432
433     // If either A or B is a entry block then it is nearest common dominator
434     // (for forward-dominators).
435     if (!this->isPostDominator()) {
436       NodeT &Entry = A->getParent()->front();
437       if (A == &Entry || B == &Entry)
438         return &Entry;
439     }
440
441     // If B dominates A then B is nearest common dominator.
442     if (dominates(B, A))
443       return B;
444
445     // If A dominates B then A is nearest common dominator.
446     if (dominates(A, B))
447       return A;
448
449     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
450     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
451
452     // Collect NodeA dominators set.
453     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
454     NodeADoms.insert(NodeA);
455     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
456     while (IDomA) {
457       NodeADoms.insert(IDomA);
458       IDomA = IDomA->getIDom();
459     }
460
461     // Walk NodeB immediate dominators chain and find common dominator node.
462     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
463     while (IDomB) {
464       if (NodeADoms.count(IDomB) != 0)
465         return IDomB->getBlock();
466
467       IDomB = IDomB->getIDom();
468     }
469
470     return NULL;
471   }
472
473   const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
474     // Cast away the const qualifiers here. This is ok since
475     // const is re-introduced on the return type.
476     return findNearestCommonDominator(const_cast<NodeT *>(A),
477                                       const_cast<NodeT *>(B));
478   }
479
480   //===--------------------------------------------------------------------===//
481   // API to update (Post)DominatorTree information based on modifications to
482   // the CFG...
483
484   /// addNewBlock - Add a new node to the dominator tree information.  This
485   /// creates a new node as a child of DomBB dominator node,linking it into
486   /// the children list of the immediate dominator.
487   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
488     assert(getNode(BB) == 0 && "Block already in dominator tree!");
489     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
490     assert(IDomNode && "Not immediate dominator specified for block!");
491     DFSInfoValid = false;
492     return DomTreeNodes[BB] =
493       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
494   }
495
496   /// changeImmediateDominator - This method is used to update the dominator
497   /// tree information when a node's immediate dominator changes.
498   ///
499   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
500                                 DomTreeNodeBase<NodeT> *NewIDom) {
501     assert(N && NewIDom && "Cannot change null node pointers!");
502     DFSInfoValid = false;
503     N->setIDom(NewIDom);
504   }
505
506   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
507     changeImmediateDominator(getNode(BB), getNode(NewBB));
508   }
509
510   /// eraseNode - Removes a node from the dominator tree. Block must not
511   /// dominate any other blocks. Removes node from its immediate dominator's
512   /// children list. Deletes dominator node associated with basic block BB.
513   void eraseNode(NodeT *BB) {
514     DomTreeNodeBase<NodeT> *Node = getNode(BB);
515     assert(Node && "Removing node that isn't in dominator tree.");
516     assert(Node->getChildren().empty() && "Node is not a leaf node.");
517
518       // Remove node from immediate dominator's children list.
519     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
520     if (IDom) {
521       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
522         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
523       assert(I != IDom->Children.end() &&
524              "Not in immediate dominator children set!");
525       // I am no longer your child...
526       IDom->Children.erase(I);
527     }
528
529     DomTreeNodes.erase(BB);
530     delete Node;
531   }
532
533   /// removeNode - Removes a node from the dominator tree.  Block must not
534   /// dominate any other blocks.  Invalidates any node pointing to removed
535   /// block.
536   void removeNode(NodeT *BB) {
537     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
538     DomTreeNodes.erase(BB);
539   }
540
541   /// splitBlock - BB is split and now it has one successor. Update dominator
542   /// tree to reflect this change.
543   void splitBlock(NodeT* NewBB) {
544     if (this->IsPostDominators)
545       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
546     else
547       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
548   }
549
550   /// print - Convert to human readable form
551   ///
552   void print(raw_ostream &o) const {
553     o << "=============================--------------------------------\n";
554     if (this->isPostDominator())
555       o << "Inorder PostDominator Tree: ";
556     else
557       o << "Inorder Dominator Tree: ";
558     if (this->DFSInfoValid)
559       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
560     o << "\n";
561
562     // The postdom tree can have a null root if there are no returns.
563     if (getRootNode())
564       PrintDomTree<NodeT>(getRootNode(), o, 1);
565   }
566
567 protected:
568   template<class GraphT>
569   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
570                        typename GraphT::NodeType* VIn);
571
572   template<class GraphT>
573   friend typename GraphT::NodeType* Eval(
574                                DominatorTreeBase<typename GraphT::NodeType>& DT,
575                                          typename GraphT::NodeType* V);
576
577   template<class GraphT>
578   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
579                    unsigned DFSNumV, typename GraphT::NodeType* W,
580          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
581
582   template<class GraphT>
583   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
584                           typename GraphT::NodeType* V,
585                           unsigned N);
586
587   template<class FuncT, class N>
588   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
589                         FuncT& F);
590
591   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
592   /// dominator tree in dfs order.
593   void updateDFSNumbers() {
594     unsigned DFSNum = 0;
595
596     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
597                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
598
599     DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
600
601     if (!ThisRoot)
602       return;
603
604     // Even in the case of multiple exits that form the post dominator root
605     // nodes, do not iterate over all exits, but start from the virtual root
606     // node. Otherwise bbs, that are not post dominated by any exit but by the
607     // virtual root node, will never be assigned a DFS number.
608     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
609     ThisRoot->DFSNumIn = DFSNum++;
610
611     while (!WorkStack.empty()) {
612       DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
613       typename DomTreeNodeBase<NodeT>::iterator ChildIt =
614         WorkStack.back().second;
615
616       // If we visited all of the children of this node, "recurse" back up the
617       // stack setting the DFOutNum.
618       if (ChildIt == Node->end()) {
619         Node->DFSNumOut = DFSNum++;
620         WorkStack.pop_back();
621       } else {
622         // Otherwise, recursively visit this child.
623         DomTreeNodeBase<NodeT> *Child = *ChildIt;
624         ++WorkStack.back().second;
625
626         WorkStack.push_back(std::make_pair(Child, Child->begin()));
627         Child->DFSNumIn = DFSNum++;
628       }
629     }
630
631     SlowQueries = 0;
632     DFSInfoValid = true;
633   }
634
635   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
636     typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
637     if (I != this->DomTreeNodes.end() && I->second)
638       return I->second;
639
640     // Haven't calculated this node yet?  Get or calculate the node for the
641     // immediate dominator.
642     NodeT *IDom = getIDom(BB);
643
644     assert(IDom || this->DomTreeNodes[NULL]);
645     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
646
647     // Add a new tree node for this BasicBlock, and link it as a child of
648     // IDomNode
649     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
650     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
651   }
652
653   inline NodeT *getIDom(NodeT *BB) const {
654     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
655     return I != IDoms.end() ? I->second : 0;
656   }
657
658   inline void addRoot(NodeT* BB) {
659     this->Roots.push_back(BB);
660   }
661
662 public:
663   /// recalculate - compute a dominator tree for the given function
664   template<class FT>
665   void recalculate(FT& F) {
666     reset();
667     this->Vertex.push_back(0);
668
669     if (!this->IsPostDominators) {
670       // Initialize root
671       this->Roots.push_back(&F.front());
672       this->IDoms[&F.front()] = 0;
673       this->DomTreeNodes[&F.front()] = 0;
674
675       Calculate<FT, NodeT*>(*this, F);
676     } else {
677       // Initialize the roots list
678       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
679         if (std::distance(GraphTraits<FT*>::child_begin(I),
680                           GraphTraits<FT*>::child_end(I)) == 0)
681           addRoot(I);
682
683         // Prepopulate maps so that we don't get iterator invalidation issues later.
684         this->IDoms[I] = 0;
685         this->DomTreeNodes[I] = 0;
686       }
687
688       Calculate<FT, Inverse<NodeT*> >(*this, F);
689     }
690   }
691 };
692
693 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
694
695 //===-------------------------------------
696 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
697 /// compute a normal dominator tree.
698 ///
699 class DominatorTree : public FunctionPass {
700 public:
701   static char ID; // Pass ID, replacement for typeid
702   DominatorTreeBase<BasicBlock>* DT;
703
704   DominatorTree() : FunctionPass(ID) {
705     initializeDominatorTreePass(*PassRegistry::getPassRegistry());
706     DT = new DominatorTreeBase<BasicBlock>(false);
707   }
708
709   ~DominatorTree() {
710     delete DT;
711   }
712
713   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
714
715   /// getRoots - Return the root blocks of the current CFG.  This may include
716   /// multiple blocks if we are computing post dominators.  For forward
717   /// dominators, this will always be a single block (the entry node).
718   ///
719   inline const std::vector<BasicBlock*> &getRoots() const {
720     return DT->getRoots();
721   }
722
723   inline BasicBlock *getRoot() const {
724     return DT->getRoot();
725   }
726
727   inline DomTreeNode *getRootNode() const {
728     return DT->getRootNode();
729   }
730
731   /// compare - Return false if the other dominator tree matches this
732   /// dominator tree. Otherwise return true.
733   inline bool compare(DominatorTree &Other) const {
734     DomTreeNode *R = getRootNode();
735     DomTreeNode *OtherR = Other.getRootNode();
736
737     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
738       return true;
739
740     if (DT->compare(Other.getBase()))
741       return true;
742
743     return false;
744   }
745
746   virtual bool runOnFunction(Function &F);
747
748   virtual void verifyAnalysis() const;
749
750   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
751     AU.setPreservesAll();
752   }
753
754   inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
755     return DT->dominates(A, B);
756   }
757
758   inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
759     return DT->dominates(A, B);
760   }
761
762   // dominates - Return true if A dominates B. This performs the
763   // special checks necessary if A and B are in the same basic block.
764   bool dominates(const Instruction *A, const Instruction *B) const;
765
766   bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
767     return DT->properlyDominates(A, B);
768   }
769
770   bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
771     return DT->properlyDominates(A, B);
772   }
773
774   /// findNearestCommonDominator - Find nearest common dominator basic block
775   /// for basic block A and B. If there is no such block then return NULL.
776   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
777     return DT->findNearestCommonDominator(A, B);
778   }
779
780   inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
781                                                       const BasicBlock *B) {
782     return DT->findNearestCommonDominator(A, B);
783   }
784
785   inline DomTreeNode *operator[](BasicBlock *BB) const {
786     return DT->getNode(BB);
787   }
788
789   /// getNode - return the (Post)DominatorTree node for the specified basic
790   /// block.  This is the same as using operator[] on this class.
791   ///
792   inline DomTreeNode *getNode(BasicBlock *BB) const {
793     return DT->getNode(BB);
794   }
795
796   /// addNewBlock - Add a new node to the dominator tree information.  This
797   /// creates a new node as a child of DomBB dominator node,linking it into
798   /// the children list of the immediate dominator.
799   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
800     return DT->addNewBlock(BB, DomBB);
801   }
802
803   /// changeImmediateDominator - This method is used to update the dominator
804   /// tree information when a node's immediate dominator changes.
805   ///
806   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
807     DT->changeImmediateDominator(N, NewIDom);
808   }
809
810   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
811     DT->changeImmediateDominator(N, NewIDom);
812   }
813
814   /// eraseNode - Removes a node from the dominator tree. Block must not
815   /// dominate any other blocks. Removes node from its immediate dominator's
816   /// children list. Deletes dominator node associated with basic block BB.
817   inline void eraseNode(BasicBlock *BB) {
818     DT->eraseNode(BB);
819   }
820
821   /// splitBlock - BB is split and now it has one successor. Update dominator
822   /// tree to reflect this change.
823   inline void splitBlock(BasicBlock* NewBB) {
824     DT->splitBlock(NewBB);
825   }
826
827   bool isReachableFromEntry(const BasicBlock* A) {
828     return DT->isReachableFromEntry(A);
829   }
830
831
832   virtual void releaseMemory() {
833     DT->releaseMemory();
834   }
835
836   virtual void print(raw_ostream &OS, const Module* M= 0) const;
837 };
838
839 //===-------------------------------------
840 /// DominatorTree GraphTraits specialization so the DominatorTree can be
841 /// iterable by generic graph iterators.
842 ///
843 template <> struct GraphTraits<DomTreeNode*> {
844   typedef DomTreeNode NodeType;
845   typedef NodeType::iterator  ChildIteratorType;
846
847   static NodeType *getEntryNode(NodeType *N) {
848     return N;
849   }
850   static inline ChildIteratorType child_begin(NodeType *N) {
851     return N->begin();
852   }
853   static inline ChildIteratorType child_end(NodeType *N) {
854     return N->end();
855   }
856
857   typedef df_iterator<DomTreeNode*> nodes_iterator;
858
859   static nodes_iterator nodes_begin(DomTreeNode *N) {
860     return df_begin(getEntryNode(N));
861   }
862
863   static nodes_iterator nodes_end(DomTreeNode *N) {
864     return df_end(getEntryNode(N));
865   }
866 };
867
868 template <> struct GraphTraits<DominatorTree*>
869   : public GraphTraits<DomTreeNode*> {
870   static NodeType *getEntryNode(DominatorTree *DT) {
871     return DT->getRootNode();
872   }
873
874   static nodes_iterator nodes_begin(DominatorTree *N) {
875     return df_begin(getEntryNode(N));
876   }
877
878   static nodes_iterator nodes_end(DominatorTree *N) {
879     return df_end(getEntryNode(N));
880   }
881 };
882
883
884 } // End llvm namespace
885
886 #endif