Tidy up #includes, deleting a bunch of unnecessary #includes.
[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 following classes:
11 //  1. DominatorTree: Represent dominators as an explicit tree structure.
12 //  2. DominanceFrontier: Calculate and hold the dominance frontier for a
13 //     function.
14 //
15 //  These data structures are listed in increasing order of complexity.  It
16 //  takes longer to calculate the dominator frontier, for example, than the
17 //  DominatorTree mapping.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
23
24 #include "llvm/Pass.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/GraphTraits.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
35 #include <algorithm>
36 #include <map>
37 #include <set>
38
39 namespace llvm {
40
41 //===----------------------------------------------------------------------===//
42 /// DominatorBase - Base class that other, more interesting dominator analyses
43 /// inherit from.
44 ///
45 template <class NodeT>
46 class DominatorBase {
47 protected:
48   std::vector<NodeT*> Roots;
49   const bool IsPostDominators;
50   inline explicit DominatorBase(bool isPostDom) :
51     Roots(), IsPostDominators(isPostDom) {}
52 public:
53
54   /// getRoots -  Return the root blocks of the current CFG.  This may include
55   /// multiple blocks if we are computing post dominators.  For forward
56   /// dominators, this will always be a single block (the entry node).
57   ///
58   inline const std::vector<NodeT*> &getRoots() const { return Roots; }
59
60   /// isPostDominator - Returns true if analysis based of postdoms
61   ///
62   bool isPostDominator() const { return IsPostDominators; }
63 };
64
65
66 //===----------------------------------------------------------------------===//
67 // DomTreeNode - Dominator Tree Node
68 template<class NodeT> class DominatorTreeBase;
69 struct PostDominatorTree;
70 class MachineBasicBlock;
71
72 template <class NodeT>
73 class DomTreeNodeBase {
74   NodeT *TheBB;
75   DomTreeNodeBase<NodeT> *IDom;
76   std::vector<DomTreeNodeBase<NodeT> *> Children;
77   int DFSNumIn, DFSNumOut;
78
79   template<class N> friend class DominatorTreeBase;
80   friend struct PostDominatorTree;
81 public:
82   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
83   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
84                    const_iterator;
85   
86   iterator begin()             { return Children.begin(); }
87   iterator end()               { return Children.end(); }
88   const_iterator begin() const { return Children.begin(); }
89   const_iterator end()   const { return Children.end(); }
90   
91   NodeT *getBlock() const { return TheBB; }
92   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
93   const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
94     return Children;
95   }
96
97   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
98     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
99   
100   DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
101     Children.push_back(C);
102     return C;
103   }
104
105   size_t getNumChildren() const {
106     return Children.size();
107   }
108
109   void clearAllChildren() {
110     Children.clear();
111   }
112   
113   bool compare(DomTreeNodeBase<NodeT> *Other) {
114     if (getNumChildren() != Other->getNumChildren())
115       return true;
116
117     SmallPtrSet<NodeT *, 4> OtherChildren;
118     for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
119       NodeT *Nd = (*I)->getBlock();
120       OtherChildren.insert(Nd);
121     }
122
123     for(iterator I = begin(), E = end(); I != E; ++I) {
124       NodeT *N = (*I)->getBlock();
125       if (OtherChildren.count(N) == 0)
126         return true;
127     }
128     return false;
129   }
130
131   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
132     assert(IDom && "No immediate dominator?");
133     if (IDom != NewIDom) {
134       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
135                   std::find(IDom->Children.begin(), IDom->Children.end(), this);
136       assert(I != IDom->Children.end() &&
137              "Not in immediate dominator children set!");
138       // I am no longer your child...
139       IDom->Children.erase(I);
140
141       // Switch to new dominator
142       IDom = NewIDom;
143       IDom->Children.push_back(this);
144     }
145   }
146   
147   /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
148   /// not call them.
149   unsigned getDFSNumIn() const { return DFSNumIn; }
150   unsigned getDFSNumOut() const { return DFSNumOut; }
151 private:
152   // Return true if this node is dominated by other. Use this only if DFS info
153   // is valid.
154   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
155     return this->DFSNumIn >= other->DFSNumIn &&
156       this->DFSNumOut <= other->DFSNumOut;
157   }
158 };
159
160 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
162
163 template<class NodeT>
164 static std::ostream &operator<<(std::ostream &o,
165                                 const DomTreeNodeBase<NodeT> *Node) {
166   if (Node->getBlock())
167     WriteAsOperand(o, Node->getBlock(), false);
168   else
169     o << " <<exit node>>";
170   
171   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
172   
173   return o << "\n";
174 }
175
176 template<class NodeT>
177 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
178                          unsigned Lev) {
179   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
180   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
181        E = N->end(); I != E; ++I)
182     PrintDomTree<NodeT>(*I, o, Lev+1);
183 }
184
185 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
186
187 //===----------------------------------------------------------------------===//
188 /// DominatorTree - Calculate the immediate dominator tree for a function.
189 ///
190
191 template<class FuncT, class N>
192 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
193                FuncT& F);
194
195 template<class NodeT>
196 class DominatorTreeBase : public DominatorBase<NodeT> {
197 protected:
198   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
199   DomTreeNodeMapType DomTreeNodes;
200   DomTreeNodeBase<NodeT> *RootNode;
201
202   bool DFSInfoValid;
203   unsigned int SlowQueries;
204   // Information record used during immediate dominators computation.
205   struct InfoRec {
206     unsigned DFSNum;
207     unsigned Semi;
208     unsigned Size;
209     NodeT *Label, *Child;
210     unsigned Parent, Ancestor;
211
212     std::vector<NodeT*> Bucket;
213
214     InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
215                 Ancestor(0) {}
216   };
217
218   DenseMap<NodeT*, NodeT*> IDoms;
219
220   // Vertex - Map the DFS number to the BasicBlock*
221   std::vector<NodeT*> Vertex;
222
223   // Info - Collection of information used during the computation of idoms.
224   DenseMap<NodeT*, InfoRec> Info;
225
226   void reset() {
227     for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 
228            E = DomTreeNodes.end(); I != E; ++I)
229       delete I->second;
230     DomTreeNodes.clear();
231     IDoms.clear();
232     this->Roots.clear();
233     Vertex.clear();
234     RootNode = 0;
235   }
236   
237   // NewBB is split and now it has one successor. Update dominator tree to
238   // reflect this change.
239   template<class N, class GraphT>
240   void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
241              typename GraphT::NodeType* NewBB) {
242     assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
243            && "NewBB should have a single successor!");
244     typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
245
246     std::vector<typename GraphT::NodeType*> PredBlocks;
247     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
248          GraphTraits<Inverse<N> >::child_begin(NewBB),
249          PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
250       PredBlocks.push_back(*PI);  
251
252       assert(!PredBlocks.empty() && "No predblocks??");
253
254       // The newly inserted basic block will dominate existing basic blocks iff the
255       // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
256       // the non-pred blocks, then they all must be the same block!
257       //
258       bool NewBBDominatesNewBBSucc = true;
259       {
260         typename GraphT::NodeType* OnePred = PredBlocks[0];
261         size_t i = 1, e = PredBlocks.size();
262         for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
263           assert(i != e && "Didn't find reachable pred?");
264           OnePred = PredBlocks[i];
265         }
266
267         for (; i != e; ++i)
268           if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
269             NewBBDominatesNewBBSucc = false;
270             break;
271           }
272
273       if (NewBBDominatesNewBBSucc)
274         for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
275              GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
276              E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
277           if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
278             NewBBDominatesNewBBSucc = false;
279             break;
280           }
281     }
282
283     // The other scenario where the new block can dominate its successors are when
284     // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
285     // already.
286     if (!NewBBDominatesNewBBSucc) {
287       NewBBDominatesNewBBSucc = true;
288       for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 
289            GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
290            E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
291          if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
292           NewBBDominatesNewBBSucc = false;
293           break;
294         }
295     }
296
297     // Find NewBB's immediate dominator and create new dominator tree node for
298     // NewBB.
299     NodeT *NewBBIDom = 0;
300     unsigned i = 0;
301     for (i = 0; i < PredBlocks.size(); ++i)
302       if (DT.isReachableFromEntry(PredBlocks[i])) {
303         NewBBIDom = PredBlocks[i];
304         break;
305       }
306     assert(i != PredBlocks.size() && "No reachable preds?");
307     for (i = i + 1; i < PredBlocks.size(); ++i) {
308       if (DT.isReachableFromEntry(PredBlocks[i]))
309         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
310     }
311     assert(NewBBIDom && "No immediate dominator found??");
312
313     // Create the new dominator tree node... and set the idom of NewBB.
314     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
315
316     // If NewBB strictly dominates other blocks, then it is now the immediate
317     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
318     if (NewBBDominatesNewBBSucc) {
319       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
320       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
321     }
322   }
323
324 public:
325   explicit DominatorTreeBase(bool isPostDom)
326     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
327   virtual ~DominatorTreeBase() { reset(); }
328
329   // FIXME: Should remove this
330   virtual bool runOnFunction(Function &F) { return false; }
331
332   /// compare - Return false if the other dominator tree base matches this
333   /// dominator tree base. Otherwise return true.
334   bool compare(DominatorTreeBase &Other) const {
335
336     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
337     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
338       return true;
339
340     SmallPtrSet<const NodeT *,4> MyBBs;
341     for (typename DomTreeNodeMapType::const_iterator 
342            I = this->DomTreeNodes.begin(),
343            E = this->DomTreeNodes.end(); I != E; ++I) {
344       NodeT *BB = I->first;
345       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
346       if (OI == OtherDomTreeNodes.end())
347         return true;
348
349       DomTreeNodeBase<NodeT>* MyNd = I->second;
350       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
351       
352       if (MyNd->compare(OtherNd))
353         return true;
354     }
355
356     return false;
357   }
358
359   virtual void releaseMemory() { reset(); }
360
361   /// getNode - return the (Post)DominatorTree node for the specified basic
362   /// block.  This is the same as using operator[] on this class.
363   ///
364   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
365     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
366     return I != DomTreeNodes.end() ? I->second : 0;
367   }
368
369   /// getRootNode - This returns the entry node for the CFG of the function.  If
370   /// this tree represents the post-dominance relations for a function, however,
371   /// this root may be a node with the block == NULL.  This is the case when
372   /// there are multiple exit nodes from a particular function.  Consumers of
373   /// post-dominance information must be capable of dealing with this
374   /// possibility.
375   ///
376   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
377   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
378
379   /// properlyDominates - Returns true iff this dominates N and this != N.
380   /// Note that this is not a constant time operation!
381   ///
382   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
383                          DomTreeNodeBase<NodeT> *B) const {
384     if (A == 0 || B == 0) return false;
385     return dominatedBySlowTreeWalk(A, B);
386   }
387
388   inline bool properlyDominates(NodeT *A, NodeT *B) {
389     return properlyDominates(getNode(A), getNode(B));
390   }
391
392   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 
393                                const DomTreeNodeBase<NodeT> *B) const {
394     const DomTreeNodeBase<NodeT> *IDom;
395     if (A == 0 || B == 0) return false;
396     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
397       B = IDom;   // Walk up the tree
398     return IDom != 0;
399   }
400
401
402   /// isReachableFromEntry - Return true if A is dominated by the entry
403   /// block of the function containing it.
404   bool isReachableFromEntry(NodeT* A) {
405     assert (!this->isPostDominator() 
406             && "This is not implemented for post dominators");
407     return dominates(&A->getParent()->front(), A);
408   }
409   
410   /// dominates - Returns true iff A dominates B.  Note that this is not a
411   /// constant time operation!
412   ///
413   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
414                         DomTreeNodeBase<NodeT> *B) {
415     if (B == A) 
416       return true;  // A node trivially dominates itself.
417
418     if (A == 0 || B == 0)
419       return false;
420
421     if (DFSInfoValid)
422       return B->DominatedBy(A);
423
424     // If we end up with too many slow queries, just update the
425     // DFS numbers on the theory that we are going to keep querying.
426     SlowQueries++;
427     if (SlowQueries > 32) {
428       updateDFSNumbers();
429       return B->DominatedBy(A);
430     }
431
432     return dominatedBySlowTreeWalk(A, B);
433   }
434
435   inline bool dominates(NodeT *A, NodeT *B) {
436     if (A == B) 
437       return true;
438     
439     return dominates(getNode(A), getNode(B));
440   }
441   
442   NodeT *getRoot() const {
443     assert(this->Roots.size() == 1 && "Should always have entry node!");
444     return this->Roots[0];
445   }
446
447   /// findNearestCommonDominator - Find nearest common dominator basic block
448   /// for basic block A and B. If there is no such block then return NULL.
449   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
450
451     assert (!this->isPostDominator() 
452             && "This is not implemented for post dominators");
453     assert (A->getParent() == B->getParent() 
454             && "Two blocks are not in same function");
455
456     // If either A or B is a entry block then it is nearest common dominator.
457     NodeT &Entry  = A->getParent()->front();
458     if (A == &Entry || B == &Entry)
459       return &Entry;
460
461     // If B dominates A then B is nearest common dominator.
462     if (dominates(B, A))
463       return B;
464
465     // If A dominates B then A is nearest common dominator.
466     if (dominates(A, B))
467       return A;
468
469     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
470     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
471
472     // Collect NodeA dominators set.
473     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
474     NodeADoms.insert(NodeA);
475     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
476     while (IDomA) {
477       NodeADoms.insert(IDomA);
478       IDomA = IDomA->getIDom();
479     }
480
481     // Walk NodeB immediate dominators chain and find common dominator node.
482     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
483     while(IDomB) {
484       if (NodeADoms.count(IDomB) != 0)
485         return IDomB->getBlock();
486
487       IDomB = IDomB->getIDom();
488     }
489
490     return NULL;
491   }
492
493   //===--------------------------------------------------------------------===//
494   // API to update (Post)DominatorTree information based on modifications to
495   // the CFG...
496
497   /// addNewBlock - Add a new node to the dominator tree information.  This
498   /// creates a new node as a child of DomBB dominator node,linking it into 
499   /// the children list of the immediate dominator.
500   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
501     assert(getNode(BB) == 0 && "Block already in dominator tree!");
502     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
503     assert(IDomNode && "Not immediate dominator specified for block!");
504     DFSInfoValid = false;
505     return DomTreeNodes[BB] = 
506       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
507   }
508
509   /// changeImmediateDominator - This method is used to update the dominator
510   /// tree information when a node's immediate dominator changes.
511   ///
512   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
513                                 DomTreeNodeBase<NodeT> *NewIDom) {
514     assert(N && NewIDom && "Cannot change null node pointers!");
515     DFSInfoValid = false;
516     N->setIDom(NewIDom);
517   }
518
519   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
520     changeImmediateDominator(getNode(BB), getNode(NewBB));
521   }
522
523   /// eraseNode - Removes a node from  the dominator tree. Block must not
524   /// domiante any other blocks. Removes node from its immediate dominator's
525   /// children list. Deletes dominator node associated with basic block BB.
526   void eraseNode(NodeT *BB) {
527     DomTreeNodeBase<NodeT> *Node = getNode(BB);
528     assert (Node && "Removing node that isn't in dominator tree.");
529     assert (Node->getChildren().empty() && "Node is not a leaf node.");
530
531       // Remove node from immediate dominator's children list.
532     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
533     if (IDom) {
534       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
535         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
536       assert(I != IDom->Children.end() &&
537              "Not in immediate dominator children set!");
538       // I am no longer your child...
539       IDom->Children.erase(I);
540     }
541
542     DomTreeNodes.erase(BB);
543     delete Node;
544   }
545
546   /// removeNode - Removes a node from the dominator tree.  Block must not
547   /// dominate any other blocks.  Invalidates any node pointing to removed
548   /// block.
549   void removeNode(NodeT *BB) {
550     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
551     DomTreeNodes.erase(BB);
552   }
553   
554   /// splitBlock - BB is split and now it has one successor. Update dominator
555   /// tree to reflect this change.
556   void splitBlock(NodeT* NewBB) {
557     if (this->IsPostDominators)
558       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
559     else
560       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
561   }
562
563   /// print - Convert to human readable form
564   ///
565   virtual void print(std::ostream &o, const Module* ) const {
566     o << "=============================--------------------------------\n";
567     if (this->isPostDominator())
568       o << "Inorder PostDominator Tree: ";
569     else
570       o << "Inorder Dominator Tree: ";
571     if (this->DFSInfoValid)
572       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
573     o << "\n";
574
575     PrintDomTree<NodeT>(getRootNode(), o, 1);
576   }
577   
578   void print(std::ostream *OS, const Module* M = 0) const {
579     if (OS) print(*OS, M);
580   }
581   
582   virtual void dump() {
583     print(llvm::cerr);
584   }
585   
586 protected:
587   template<class GraphT>
588   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
589                        typename GraphT::NodeType* VIn);
590
591   template<class GraphT>
592   friend typename GraphT::NodeType* Eval(
593                                DominatorTreeBase<typename GraphT::NodeType>& DT,
594                                          typename GraphT::NodeType* V);
595
596   template<class GraphT>
597   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
598                    unsigned DFSNumV, typename GraphT::NodeType* W,
599          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
600   
601   template<class GraphT>
602   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
603                           typename GraphT::NodeType* V,
604                           unsigned N);
605   
606   template<class FuncT, class N>
607   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
608                         FuncT& F);
609   
610   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
611   /// dominator tree in dfs order.
612   void updateDFSNumbers() {
613     unsigned DFSNum = 0;
614
615     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
616                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
617
618     for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
619       DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
620       WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
621       ThisRoot->DFSNumIn = DFSNum++;
622
623       while (!WorkStack.empty()) {
624         DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
625         typename DomTreeNodeBase<NodeT>::iterator ChildIt =
626                                                         WorkStack.back().second;
627
628         // If we visited all of the children of this node, "recurse" back up the
629         // stack setting the DFOutNum.
630         if (ChildIt == Node->end()) {
631           Node->DFSNumOut = DFSNum++;
632           WorkStack.pop_back();
633         } else {
634           // Otherwise, recursively visit this child.
635           DomTreeNodeBase<NodeT> *Child = *ChildIt;
636           ++WorkStack.back().second;
637           
638           WorkStack.push_back(std::make_pair(Child, Child->begin()));
639           Child->DFSNumIn = DFSNum++;
640         }
641       }
642     }
643     
644     SlowQueries = 0;
645     DFSInfoValid = true;
646   }
647   
648   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
649     if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
650       return BBNode;
651
652     // Haven't calculated this node yet?  Get or calculate the node for the
653     // immediate dominator.
654     NodeT *IDom = getIDom(BB);
655
656     assert(IDom || this->DomTreeNodes[NULL]);
657     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
658
659     // Add a new tree node for this BasicBlock, and link it as a child of
660     // IDomNode
661     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
662     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
663   }
664   
665   inline NodeT *getIDom(NodeT *BB) const {
666     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
667     return I != IDoms.end() ? I->second : 0;
668   }
669   
670   inline void addRoot(NodeT* BB) {
671     this->Roots.push_back(BB);
672   }
673   
674 public:
675   /// recalculate - compute a dominator tree for the given function
676   template<class FT>
677   void recalculate(FT& F) {
678     if (!this->IsPostDominators) {
679       reset();
680       
681       // Initialize roots
682       this->Roots.push_back(&F.front());
683       this->IDoms[&F.front()] = 0;
684       this->DomTreeNodes[&F.front()] = 0;
685       this->Vertex.push_back(0);
686       
687       Calculate<FT, NodeT*>(*this, F);
688       
689       updateDFSNumbers();
690     } else {
691       reset();     // Reset from the last time we were run...
692
693       // Initialize the roots list
694       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
695         if (std::distance(GraphTraits<FT*>::child_begin(I),
696                           GraphTraits<FT*>::child_end(I)) == 0)
697           addRoot(I);
698
699         // Prepopulate maps so that we don't get iterator invalidation issues later.
700         this->IDoms[I] = 0;
701         this->DomTreeNodes[I] = 0;
702       }
703
704       this->Vertex.push_back(0);
705       
706       Calculate<FT, Inverse<NodeT*> >(*this, F);
707     }
708   }
709 };
710
711 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
712
713 //===-------------------------------------
714 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
715 /// compute a normal dominator tree.
716 ///
717 class DominatorTree : public FunctionPass {
718 public:
719   static char ID; // Pass ID, replacement for typeid
720   DominatorTreeBase<BasicBlock>* DT;
721   
722   DominatorTree() : FunctionPass(&ID) {
723     DT = new DominatorTreeBase<BasicBlock>(false);
724   }
725   
726   ~DominatorTree() {
727     DT->releaseMemory();
728     delete DT;
729   }
730   
731   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
732   
733   /// getRoots -  Return the root blocks of the current CFG.  This may include
734   /// multiple blocks if we are computing post dominators.  For forward
735   /// dominators, this will always be a single block (the entry node).
736   ///
737   inline const std::vector<BasicBlock*> &getRoots() const {
738     return DT->getRoots();
739   }
740   
741   inline BasicBlock *getRoot() const {
742     return DT->getRoot();
743   }
744   
745   inline DomTreeNode *getRootNode() const {
746     return DT->getRootNode();
747   }
748
749   /// compare - Return false if the other dominator tree matches this
750   /// dominator tree. Otherwise return true.
751   inline bool compare(DominatorTree &Other) const {
752     DomTreeNode *R = getRootNode();
753     DomTreeNode *OtherR = Other.getRootNode();
754     
755     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
756       return true;
757     
758     if (DT->compare(Other.getBase()))
759       return true;
760
761     return false;
762   }
763
764   virtual bool runOnFunction(Function &F);
765   
766   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
767     AU.setPreservesAll();
768   }
769   
770   inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
771     return DT->dominates(A, B);
772   }
773   
774   inline bool dominates(BasicBlock* A, BasicBlock* B) const {
775     return DT->dominates(A, B);
776   }
777   
778   // dominates - Return true if A dominates B. This performs the
779   // special checks necessary if A and B are in the same basic block.
780   bool dominates(Instruction *A, Instruction *B) const {
781     BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
782     if (BBA != BBB) return DT->dominates(BBA, BBB);
783
784     // It is not possible to determine dominance between two PHI nodes 
785     // based on their ordering.
786     if (isa<PHINode>(A) && isa<PHINode>(B)) 
787       return false;
788
789     // Loop through the basic block until we find A or B.
790     BasicBlock::iterator I = BBA->begin();
791     for (; &*I != A && &*I != B; ++I) /*empty*/;
792
793     //if(!DT.IsPostDominators) {
794       // A dominates B if it is found first in the basic block.
795       return &*I == A;
796     //} else {
797     //  // A post-dominates B if B is found first in the basic block.
798     //  return &*I == B;
799     //}
800   }
801   
802   inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
803     return DT->properlyDominates(A, B);
804   }
805   
806   inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
807     return DT->properlyDominates(A, B);
808   }
809   
810   /// findNearestCommonDominator - Find nearest common dominator basic block
811   /// for basic block A and B. If there is no such block then return NULL.
812   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
813     return DT->findNearestCommonDominator(A, B);
814   }
815   
816   inline DomTreeNode *operator[](BasicBlock *BB) const {
817     return DT->getNode(BB);
818   }
819   
820   /// getNode - return the (Post)DominatorTree node for the specified basic
821   /// block.  This is the same as using operator[] on this class.
822   ///
823   inline DomTreeNode *getNode(BasicBlock *BB) const {
824     return DT->getNode(BB);
825   }
826   
827   /// addNewBlock - Add a new node to the dominator tree information.  This
828   /// creates a new node as a child of DomBB dominator node,linking it into 
829   /// the children list of the immediate dominator.
830   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
831     return DT->addNewBlock(BB, DomBB);
832   }
833   
834   /// changeImmediateDominator - This method is used to update the dominator
835   /// tree information when a node's immediate dominator changes.
836   ///
837   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
838     DT->changeImmediateDominator(N, NewIDom);
839   }
840   
841   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
842     DT->changeImmediateDominator(N, NewIDom);
843   }
844   
845   /// eraseNode - Removes a node from  the dominator tree. Block must not
846   /// domiante any other blocks. Removes node from its immediate dominator's
847   /// children list. Deletes dominator node associated with basic block BB.
848   inline void eraseNode(BasicBlock *BB) {
849     DT->eraseNode(BB);
850   }
851   
852   /// splitBlock - BB is split and now it has one successor. Update dominator
853   /// tree to reflect this change.
854   inline void splitBlock(BasicBlock* NewBB) {
855     DT->splitBlock(NewBB);
856   }
857   
858   bool isReachableFromEntry(BasicBlock* A) {
859     return DT->isReachableFromEntry(A);
860   }
861   
862   
863   virtual void releaseMemory() { 
864     DT->releaseMemory();
865   }
866   
867   virtual void print(std::ostream &OS, const Module* M= 0) const {
868     DT->print(OS, M);
869   }
870 };
871
872 //===-------------------------------------
873 /// DominatorTree GraphTraits specialization so the DominatorTree can be
874 /// iterable by generic graph iterators.
875 ///
876 template <> struct GraphTraits<DomTreeNode *> {
877   typedef DomTreeNode NodeType;
878   typedef NodeType::iterator  ChildIteratorType;
879   
880   static NodeType *getEntryNode(NodeType *N) {
881     return N;
882   }
883   static inline ChildIteratorType child_begin(NodeType* N) {
884     return N->begin();
885   }
886   static inline ChildIteratorType child_end(NodeType* N) {
887     return N->end();
888   }
889 };
890
891 template <> struct GraphTraits<DominatorTree*>
892   : public GraphTraits<DomTreeNode *> {
893   static NodeType *getEntryNode(DominatorTree *DT) {
894     return DT->getRootNode();
895   }
896 };
897
898
899 //===----------------------------------------------------------------------===//
900 /// DominanceFrontierBase - Common base class for computing forward and inverse
901 /// dominance frontiers for a function.
902 ///
903 class DominanceFrontierBase : public FunctionPass {
904 public:
905   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
906   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
907 protected:
908   DomSetMapType Frontiers;
909   std::vector<BasicBlock*> Roots;
910   const bool IsPostDominators;
911   
912 public:
913   DominanceFrontierBase(void *ID, bool isPostDom) 
914     : FunctionPass(ID), IsPostDominators(isPostDom) {}
915
916   /// getRoots -  Return the root blocks of the current CFG.  This may include
917   /// multiple blocks if we are computing post dominators.  For forward
918   /// dominators, this will always be a single block (the entry node).
919   ///
920   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
921   
922   /// isPostDominator - Returns true if analysis based of postdoms
923   ///
924   bool isPostDominator() const { return IsPostDominators; }
925
926   virtual void releaseMemory() { Frontiers.clear(); }
927
928   // Accessor interface:
929   typedef DomSetMapType::iterator iterator;
930   typedef DomSetMapType::const_iterator const_iterator;
931   iterator       begin()       { return Frontiers.begin(); }
932   const_iterator begin() const { return Frontiers.begin(); }
933   iterator       end()         { return Frontiers.end(); }
934   const_iterator end()   const { return Frontiers.end(); }
935   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
936   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
937
938   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
939     assert(find(BB) == end() && "Block already in DominanceFrontier!");
940     Frontiers.insert(std::make_pair(BB, frontier));
941   }
942
943   /// removeBlock - Remove basic block BB's frontier.
944   void removeBlock(BasicBlock *BB) {
945     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
946     for (iterator I = begin(), E = end(); I != E; ++I)
947       I->second.erase(BB);
948     Frontiers.erase(BB);
949   }
950
951   void addToFrontier(iterator I, BasicBlock *Node) {
952     assert(I != end() && "BB is not in DominanceFrontier!");
953     I->second.insert(Node);
954   }
955
956   void removeFromFrontier(iterator I, BasicBlock *Node) {
957     assert(I != end() && "BB is not in DominanceFrontier!");
958     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
959     I->second.erase(Node);
960   }
961
962   /// compareDomSet - Return false if two domsets match. Otherwise
963   /// return true;
964   bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
965     std::set<BasicBlock *> tmpSet;
966     for (DomSetType::const_iterator I = DS2.begin(),
967            E = DS2.end(); I != E; ++I) 
968       tmpSet.insert(*I);
969
970     for (DomSetType::const_iterator I = DS1.begin(),
971            E = DS1.end(); I != E; ++I) {
972       BasicBlock *Node = *I;
973
974       if (tmpSet.erase(Node) == 0)
975         // Node is in DS1 but not in DS2.
976         return true;
977     }
978
979     if(!tmpSet.empty())
980       // There are nodes that are in DS2 but not in DS1.
981       return true;
982
983     // DS1 and DS2 matches.
984     return false;
985   }
986
987   /// compare - Return true if the other dominance frontier base matches
988   /// this dominance frontier base. Otherwise return false.
989   bool compare(DominanceFrontierBase &Other) const {
990     DomSetMapType tmpFrontiers;
991     for (DomSetMapType::const_iterator I = Other.begin(),
992            E = Other.end(); I != E; ++I) 
993       tmpFrontiers.insert(std::make_pair(I->first, I->second));
994
995     for (DomSetMapType::iterator I = tmpFrontiers.begin(),
996            E = tmpFrontiers.end(); I != E; ++I) {
997       BasicBlock *Node = I->first;
998       const_iterator DFI = find(Node);
999       if (DFI == end()) 
1000         return true;
1001
1002       if (compareDomSet(I->second, DFI->second))
1003         return true;
1004
1005       tmpFrontiers.erase(Node);
1006     }
1007
1008     if (!tmpFrontiers.empty())
1009       return true;
1010
1011     return false;
1012   }
1013
1014   /// print - Convert to human readable form
1015   ///
1016   virtual void print(std::ostream &OS, const Module* = 0) const;
1017   void print(std::ostream *OS, const Module* M = 0) const {
1018     if (OS) print(*OS, M);
1019   }
1020   virtual void dump();
1021 };
1022
1023
1024 //===-------------------------------------
1025 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
1026 /// used to compute a forward dominator frontiers.
1027 ///
1028 class DominanceFrontier : public DominanceFrontierBase {
1029 public:
1030   static char ID; // Pass ID, replacement for typeid
1031   DominanceFrontier() : 
1032     DominanceFrontierBase(&ID, false) {}
1033
1034   BasicBlock *getRoot() const {
1035     assert(Roots.size() == 1 && "Should always have entry node!");
1036     return Roots[0];
1037   }
1038
1039   virtual bool runOnFunction(Function &) {
1040     Frontiers.clear();
1041     DominatorTree &DT = getAnalysis<DominatorTree>();
1042     Roots = DT.getRoots();
1043     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1044     calculate(DT, DT[Roots[0]]);
1045     return false;
1046   }
1047
1048   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1049     AU.setPreservesAll();
1050     AU.addRequired<DominatorTree>();
1051   }
1052
1053   /// splitBlock - BB is split and now it has one successor. Update dominance
1054   /// frontier to reflect this change.
1055   void splitBlock(BasicBlock *BB);
1056
1057   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1058   /// to reflect this change.
1059   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1060                                 DominatorTree *DT) {
1061     // NewBB is now  dominating BB. Which means BB's dominance
1062     // frontier is now part of NewBB's dominance frontier. However, BB
1063     // itself is not member of NewBB's dominance frontier.
1064     DominanceFrontier::iterator NewDFI = find(NewBB);
1065     DominanceFrontier::iterator DFI = find(BB);
1066     // If BB was an entry block then its frontier is empty.
1067     if (DFI == end())
1068       return;
1069     DominanceFrontier::DomSetType BBSet = DFI->second;
1070     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1071            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1072       BasicBlock *DFMember = *BBSetI;
1073       // Insert only if NewBB dominates DFMember.
1074       if (!DT->dominates(NewBB, DFMember))
1075         NewDFI->second.insert(DFMember);
1076     }
1077     NewDFI->second.erase(BB);
1078   }
1079
1080   const DomSetType &calculate(const DominatorTree &DT,
1081                               const DomTreeNode *Node);
1082 };
1083
1084
1085 } // End llvm namespace
1086
1087 #endif