Fix a bunch of other places that used operator[] to test whether
[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     bool NewBBDominatesNewBBSucc = true;
255     for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
256          GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
257          E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
258       if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) &&
259           DT.isReachableFromEntry(*PI)) {
260         NewBBDominatesNewBBSucc = false;
261         break;
262       }
263
264     // Find NewBB's immediate dominator and create new dominator tree node for
265     // NewBB.
266     NodeT *NewBBIDom = 0;
267     unsigned i = 0;
268     for (i = 0; i < PredBlocks.size(); ++i)
269       if (DT.isReachableFromEntry(PredBlocks[i])) {
270         NewBBIDom = PredBlocks[i];
271         break;
272       }
273
274     // It's possible that none of the predecessors of NewBB are reachable;
275     // in that case, NewBB itself is unreachable, so nothing needs to be
276     // changed.
277     if (!NewBBIDom)
278       return;
279
280     for (i = i + 1; i < PredBlocks.size(); ++i) {
281       if (DT.isReachableFromEntry(PredBlocks[i]))
282         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
283     }
284
285     // Create the new dominator tree node... and set the idom of NewBB.
286     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
287
288     // If NewBB strictly dominates other blocks, then it is now the immediate
289     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
290     if (NewBBDominatesNewBBSucc) {
291       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
292       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
293     }
294   }
295
296 public:
297   explicit DominatorTreeBase(bool isPostDom)
298     : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
299   virtual ~DominatorTreeBase() { reset(); }
300
301   // FIXME: Should remove this
302   virtual bool runOnFunction(Function &F) { return false; }
303
304   /// compare - Return false if the other dominator tree base matches this
305   /// dominator tree base. Otherwise return true.
306   bool compare(DominatorTreeBase &Other) const {
307
308     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
309     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
310       return true;
311
312     SmallPtrSet<const NodeT *,4> MyBBs;
313     for (typename DomTreeNodeMapType::const_iterator 
314            I = this->DomTreeNodes.begin(),
315            E = this->DomTreeNodes.end(); I != E; ++I) {
316       NodeT *BB = I->first;
317       typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
318       if (OI == OtherDomTreeNodes.end())
319         return true;
320
321       DomTreeNodeBase<NodeT>* MyNd = I->second;
322       DomTreeNodeBase<NodeT>* OtherNd = OI->second;
323       
324       if (MyNd->compare(OtherNd))
325         return true;
326     }
327
328     return false;
329   }
330
331   virtual void releaseMemory() { reset(); }
332
333   /// getNode - return the (Post)DominatorTree node for the specified basic
334   /// block.  This is the same as using operator[] on this class.
335   ///
336   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
337     typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
338     return I != DomTreeNodes.end() ? I->second : 0;
339   }
340
341   /// getRootNode - This returns the entry node for the CFG of the function.  If
342   /// this tree represents the post-dominance relations for a function, however,
343   /// this root may be a node with the block == NULL.  This is the case when
344   /// there are multiple exit nodes from a particular function.  Consumers of
345   /// post-dominance information must be capable of dealing with this
346   /// possibility.
347   ///
348   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
349   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
350
351   /// properlyDominates - Returns true iff this dominates N and this != N.
352   /// Note that this is not a constant time operation!
353   ///
354   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
355                          DomTreeNodeBase<NodeT> *B) const {
356     if (A == 0 || B == 0) return false;
357     return dominatedBySlowTreeWalk(A, B);
358   }
359
360   inline bool properlyDominates(NodeT *A, NodeT *B) {
361     return properlyDominates(getNode(A), getNode(B));
362   }
363
364   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 
365                                const DomTreeNodeBase<NodeT> *B) const {
366     const DomTreeNodeBase<NodeT> *IDom;
367     if (A == 0 || B == 0) return false;
368     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
369       B = IDom;   // Walk up the tree
370     return IDom != 0;
371   }
372
373
374   /// isReachableFromEntry - Return true if A is dominated by the entry
375   /// block of the function containing it.
376   bool isReachableFromEntry(NodeT* A) {
377     assert (!this->isPostDominator() 
378             && "This is not implemented for post dominators");
379     return dominates(&A->getParent()->front(), A);
380   }
381   
382   /// dominates - Returns true iff A dominates B.  Note that this is not a
383   /// constant time operation!
384   ///
385   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
386                         DomTreeNodeBase<NodeT> *B) {
387     if (B == A) 
388       return true;  // A node trivially dominates itself.
389
390     if (A == 0 || B == 0)
391       return false;
392
393     if (DFSInfoValid)
394       return B->DominatedBy(A);
395
396     // If we end up with too many slow queries, just update the
397     // DFS numbers on the theory that we are going to keep querying.
398     SlowQueries++;
399     if (SlowQueries > 32) {
400       updateDFSNumbers();
401       return B->DominatedBy(A);
402     }
403
404     return dominatedBySlowTreeWalk(A, B);
405   }
406
407   inline bool dominates(NodeT *A, NodeT *B) {
408     if (A == B) 
409       return true;
410     
411     return dominates(getNode(A), getNode(B));
412   }
413   
414   NodeT *getRoot() const {
415     assert(this->Roots.size() == 1 && "Should always have entry node!");
416     return this->Roots[0];
417   }
418
419   /// findNearestCommonDominator - Find nearest common dominator basic block
420   /// for basic block A and B. If there is no such block then return NULL.
421   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
422
423     assert (!this->isPostDominator() 
424             && "This is not implemented for post dominators");
425     assert (A->getParent() == B->getParent() 
426             && "Two blocks are not in same function");
427
428     // If either A or B is a entry block then it is nearest common dominator.
429     NodeT &Entry  = A->getParent()->front();
430     if (A == &Entry || B == &Entry)
431       return &Entry;
432
433     // If B dominates A then B is nearest common dominator.
434     if (dominates(B, A))
435       return B;
436
437     // If A dominates B then A is nearest common dominator.
438     if (dominates(A, B))
439       return A;
440
441     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
442     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
443
444     // Collect NodeA dominators set.
445     SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
446     NodeADoms.insert(NodeA);
447     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
448     while (IDomA) {
449       NodeADoms.insert(IDomA);
450       IDomA = IDomA->getIDom();
451     }
452
453     // Walk NodeB immediate dominators chain and find common dominator node.
454     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
455     while(IDomB) {
456       if (NodeADoms.count(IDomB) != 0)
457         return IDomB->getBlock();
458
459       IDomB = IDomB->getIDom();
460     }
461
462     return NULL;
463   }
464
465   //===--------------------------------------------------------------------===//
466   // API to update (Post)DominatorTree information based on modifications to
467   // the CFG...
468
469   /// addNewBlock - Add a new node to the dominator tree information.  This
470   /// creates a new node as a child of DomBB dominator node,linking it into 
471   /// the children list of the immediate dominator.
472   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
473     assert(getNode(BB) == 0 && "Block already in dominator tree!");
474     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
475     assert(IDomNode && "Not immediate dominator specified for block!");
476     DFSInfoValid = false;
477     return DomTreeNodes[BB] = 
478       IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
479   }
480
481   /// changeImmediateDominator - This method is used to update the dominator
482   /// tree information when a node's immediate dominator changes.
483   ///
484   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
485                                 DomTreeNodeBase<NodeT> *NewIDom) {
486     assert(N && NewIDom && "Cannot change null node pointers!");
487     DFSInfoValid = false;
488     N->setIDom(NewIDom);
489   }
490
491   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
492     changeImmediateDominator(getNode(BB), getNode(NewBB));
493   }
494
495   /// eraseNode - Removes a node from  the dominator tree. Block must not
496   /// domiante any other blocks. Removes node from its immediate dominator's
497   /// children list. Deletes dominator node associated with basic block BB.
498   void eraseNode(NodeT *BB) {
499     DomTreeNodeBase<NodeT> *Node = getNode(BB);
500     assert (Node && "Removing node that isn't in dominator tree.");
501     assert (Node->getChildren().empty() && "Node is not a leaf node.");
502
503       // Remove node from immediate dominator's children list.
504     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
505     if (IDom) {
506       typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
507         std::find(IDom->Children.begin(), IDom->Children.end(), Node);
508       assert(I != IDom->Children.end() &&
509              "Not in immediate dominator children set!");
510       // I am no longer your child...
511       IDom->Children.erase(I);
512     }
513
514     DomTreeNodes.erase(BB);
515     delete Node;
516   }
517
518   /// removeNode - Removes a node from the dominator tree.  Block must not
519   /// dominate any other blocks.  Invalidates any node pointing to removed
520   /// block.
521   void removeNode(NodeT *BB) {
522     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
523     DomTreeNodes.erase(BB);
524   }
525   
526   /// splitBlock - BB is split and now it has one successor. Update dominator
527   /// tree to reflect this change.
528   void splitBlock(NodeT* NewBB) {
529     if (this->IsPostDominators)
530       this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
531     else
532       this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
533   }
534
535   /// print - Convert to human readable form
536   ///
537   virtual void print(std::ostream &o, const Module* ) const {
538     o << "=============================--------------------------------\n";
539     if (this->isPostDominator())
540       o << "Inorder PostDominator Tree: ";
541     else
542       o << "Inorder Dominator Tree: ";
543     if (this->DFSInfoValid)
544       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
545     o << "\n";
546
547     PrintDomTree<NodeT>(getRootNode(), o, 1);
548   }
549   
550   void print(std::ostream *OS, const Module* M = 0) const {
551     if (OS) print(*OS, M);
552   }
553   
554   virtual void dump() {
555     print(llvm::cerr);
556   }
557   
558 protected:
559   template<class GraphT>
560   friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
561                        typename GraphT::NodeType* VIn);
562
563   template<class GraphT>
564   friend typename GraphT::NodeType* Eval(
565                                DominatorTreeBase<typename GraphT::NodeType>& DT,
566                                          typename GraphT::NodeType* V);
567
568   template<class GraphT>
569   friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
570                    unsigned DFSNumV, typename GraphT::NodeType* W,
571          typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
572   
573   template<class GraphT>
574   friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
575                           typename GraphT::NodeType* V,
576                           unsigned N);
577   
578   template<class FuncT, class N>
579   friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
580                         FuncT& F);
581   
582   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
583   /// dominator tree in dfs order.
584   void updateDFSNumbers() {
585     unsigned DFSNum = 0;
586
587     SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
588                 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
589
590     for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
591       DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
592       WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
593       ThisRoot->DFSNumIn = DFSNum++;
594
595       while (!WorkStack.empty()) {
596         DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
597         typename DomTreeNodeBase<NodeT>::iterator ChildIt =
598                                                         WorkStack.back().second;
599
600         // If we visited all of the children of this node, "recurse" back up the
601         // stack setting the DFOutNum.
602         if (ChildIt == Node->end()) {
603           Node->DFSNumOut = DFSNum++;
604           WorkStack.pop_back();
605         } else {
606           // Otherwise, recursively visit this child.
607           DomTreeNodeBase<NodeT> *Child = *ChildIt;
608           ++WorkStack.back().second;
609           
610           WorkStack.push_back(std::make_pair(Child, Child->begin()));
611           Child->DFSNumIn = DFSNum++;
612         }
613       }
614     }
615     
616     SlowQueries = 0;
617     DFSInfoValid = true;
618   }
619   
620   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
621     typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
622     if (I != this->DomTreeNodes.end() && I->second)
623       return I->second;
624
625     // Haven't calculated this node yet?  Get or calculate the node for the
626     // immediate dominator.
627     NodeT *IDom = getIDom(BB);
628
629     assert(IDom || this->DomTreeNodes[NULL]);
630     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
631
632     // Add a new tree node for this BasicBlock, and link it as a child of
633     // IDomNode
634     DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
635     return this->DomTreeNodes[BB] = IDomNode->addChild(C);
636   }
637   
638   inline NodeT *getIDom(NodeT *BB) const {
639     typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
640     return I != IDoms.end() ? I->second : 0;
641   }
642   
643   inline void addRoot(NodeT* BB) {
644     this->Roots.push_back(BB);
645   }
646   
647 public:
648   /// recalculate - compute a dominator tree for the given function
649   template<class FT>
650   void recalculate(FT& F) {
651     if (!this->IsPostDominators) {
652       reset();
653       
654       // Initialize roots
655       this->Roots.push_back(&F.front());
656       this->IDoms[&F.front()] = 0;
657       this->DomTreeNodes[&F.front()] = 0;
658       this->Vertex.push_back(0);
659       
660       Calculate<FT, NodeT*>(*this, F);
661       
662       updateDFSNumbers();
663     } else {
664       reset();     // Reset from the last time we were run...
665
666       // Initialize the roots list
667       for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
668         if (std::distance(GraphTraits<FT*>::child_begin(I),
669                           GraphTraits<FT*>::child_end(I)) == 0)
670           addRoot(I);
671
672         // Prepopulate maps so that we don't get iterator invalidation issues later.
673         this->IDoms[I] = 0;
674         this->DomTreeNodes[I] = 0;
675       }
676
677       this->Vertex.push_back(0);
678       
679       Calculate<FT, Inverse<NodeT*> >(*this, F);
680     }
681   }
682 };
683
684 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
685
686 //===-------------------------------------
687 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
688 /// compute a normal dominator tree.
689 ///
690 class DominatorTree : public FunctionPass {
691 public:
692   static char ID; // Pass ID, replacement for typeid
693   DominatorTreeBase<BasicBlock>* DT;
694   
695   DominatorTree() : FunctionPass(&ID) {
696     DT = new DominatorTreeBase<BasicBlock>(false);
697   }
698   
699   ~DominatorTree() {
700     DT->releaseMemory();
701     delete DT;
702   }
703   
704   DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
705   
706   /// getRoots -  Return the root blocks of the current CFG.  This may include
707   /// multiple blocks if we are computing post dominators.  For forward
708   /// dominators, this will always be a single block (the entry node).
709   ///
710   inline const std::vector<BasicBlock*> &getRoots() const {
711     return DT->getRoots();
712   }
713   
714   inline BasicBlock *getRoot() const {
715     return DT->getRoot();
716   }
717   
718   inline DomTreeNode *getRootNode() const {
719     return DT->getRootNode();
720   }
721
722   /// compare - Return false if the other dominator tree matches this
723   /// dominator tree. Otherwise return true.
724   inline bool compare(DominatorTree &Other) const {
725     DomTreeNode *R = getRootNode();
726     DomTreeNode *OtherR = Other.getRootNode();
727     
728     if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
729       return true;
730     
731     if (DT->compare(Other.getBase()))
732       return true;
733
734     return false;
735   }
736
737   virtual bool runOnFunction(Function &F);
738   
739   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
740     AU.setPreservesAll();
741   }
742   
743   inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
744     return DT->dominates(A, B);
745   }
746   
747   inline bool dominates(BasicBlock* A, BasicBlock* B) const {
748     return DT->dominates(A, B);
749   }
750   
751   // dominates - Return true if A dominates B. This performs the
752   // special checks necessary if A and B are in the same basic block.
753   bool dominates(Instruction *A, Instruction *B) const {
754     BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
755     if (BBA != BBB) return DT->dominates(BBA, BBB);
756
757     // It is not possible to determine dominance between two PHI nodes 
758     // based on their ordering.
759     if (isa<PHINode>(A) && isa<PHINode>(B)) 
760       return false;
761
762     // Loop through the basic block until we find A or B.
763     BasicBlock::iterator I = BBA->begin();
764     for (; &*I != A && &*I != B; ++I) /*empty*/;
765
766     //if(!DT.IsPostDominators) {
767       // A dominates B if it is found first in the basic block.
768       return &*I == A;
769     //} else {
770     //  // A post-dominates B if B is found first in the basic block.
771     //  return &*I == B;
772     //}
773   }
774   
775   inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
776     return DT->properlyDominates(A, B);
777   }
778   
779   inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
780     return DT->properlyDominates(A, B);
781   }
782   
783   /// findNearestCommonDominator - Find nearest common dominator basic block
784   /// for basic block A and B. If there is no such block then return NULL.
785   inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
786     return DT->findNearestCommonDominator(A, B);
787   }
788   
789   inline DomTreeNode *operator[](BasicBlock *BB) const {
790     return DT->getNode(BB);
791   }
792   
793   /// getNode - return the (Post)DominatorTree node for the specified basic
794   /// block.  This is the same as using operator[] on this class.
795   ///
796   inline DomTreeNode *getNode(BasicBlock *BB) const {
797     return DT->getNode(BB);
798   }
799   
800   /// addNewBlock - Add a new node to the dominator tree information.  This
801   /// creates a new node as a child of DomBB dominator node,linking it into 
802   /// the children list of the immediate dominator.
803   inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
804     return DT->addNewBlock(BB, DomBB);
805   }
806   
807   /// changeImmediateDominator - This method is used to update the dominator
808   /// tree information when a node's immediate dominator changes.
809   ///
810   inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
811     DT->changeImmediateDominator(N, NewIDom);
812   }
813   
814   inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
815     DT->changeImmediateDominator(N, NewIDom);
816   }
817   
818   /// eraseNode - Removes a node from  the dominator tree. Block must not
819   /// domiante any other blocks. Removes node from its immediate dominator's
820   /// children list. Deletes dominator node associated with basic block BB.
821   inline void eraseNode(BasicBlock *BB) {
822     DT->eraseNode(BB);
823   }
824   
825   /// splitBlock - BB is split and now it has one successor. Update dominator
826   /// tree to reflect this change.
827   inline void splitBlock(BasicBlock* NewBB) {
828     DT->splitBlock(NewBB);
829   }
830   
831   bool isReachableFromEntry(BasicBlock* A) {
832     return DT->isReachableFromEntry(A);
833   }
834   
835   
836   virtual void releaseMemory() { 
837     DT->releaseMemory();
838   }
839   
840   virtual void print(std::ostream &OS, const Module* M= 0) const {
841     DT->print(OS, M);
842   }
843 };
844
845 //===-------------------------------------
846 /// DominatorTree GraphTraits specialization so the DominatorTree can be
847 /// iterable by generic graph iterators.
848 ///
849 template <> struct GraphTraits<DomTreeNode *> {
850   typedef DomTreeNode NodeType;
851   typedef NodeType::iterator  ChildIteratorType;
852   
853   static NodeType *getEntryNode(NodeType *N) {
854     return N;
855   }
856   static inline ChildIteratorType child_begin(NodeType* N) {
857     return N->begin();
858   }
859   static inline ChildIteratorType child_end(NodeType* N) {
860     return N->end();
861   }
862 };
863
864 template <> struct GraphTraits<DominatorTree*>
865   : public GraphTraits<DomTreeNode *> {
866   static NodeType *getEntryNode(DominatorTree *DT) {
867     return DT->getRootNode();
868   }
869 };
870
871
872 //===----------------------------------------------------------------------===//
873 /// DominanceFrontierBase - Common base class for computing forward and inverse
874 /// dominance frontiers for a function.
875 ///
876 class DominanceFrontierBase : public FunctionPass {
877 public:
878   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
879   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
880 protected:
881   DomSetMapType Frontiers;
882   std::vector<BasicBlock*> Roots;
883   const bool IsPostDominators;
884   
885 public:
886   DominanceFrontierBase(void *ID, bool isPostDom) 
887     : FunctionPass(ID), IsPostDominators(isPostDom) {}
888
889   /// getRoots -  Return the root blocks of the current CFG.  This may include
890   /// multiple blocks if we are computing post dominators.  For forward
891   /// dominators, this will always be a single block (the entry node).
892   ///
893   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
894   
895   /// isPostDominator - Returns true if analysis based of postdoms
896   ///
897   bool isPostDominator() const { return IsPostDominators; }
898
899   virtual void releaseMemory() { Frontiers.clear(); }
900
901   // Accessor interface:
902   typedef DomSetMapType::iterator iterator;
903   typedef DomSetMapType::const_iterator const_iterator;
904   iterator       begin()       { return Frontiers.begin(); }
905   const_iterator begin() const { return Frontiers.begin(); }
906   iterator       end()         { return Frontiers.end(); }
907   const_iterator end()   const { return Frontiers.end(); }
908   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
909   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
910
911   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
912     assert(find(BB) == end() && "Block already in DominanceFrontier!");
913     Frontiers.insert(std::make_pair(BB, frontier));
914   }
915
916   /// removeBlock - Remove basic block BB's frontier.
917   void removeBlock(BasicBlock *BB) {
918     assert(find(BB) != end() && "Block is not in DominanceFrontier!");
919     for (iterator I = begin(), E = end(); I != E; ++I)
920       I->second.erase(BB);
921     Frontiers.erase(BB);
922   }
923
924   void addToFrontier(iterator I, BasicBlock *Node) {
925     assert(I != end() && "BB is not in DominanceFrontier!");
926     I->second.insert(Node);
927   }
928
929   void removeFromFrontier(iterator I, BasicBlock *Node) {
930     assert(I != end() && "BB is not in DominanceFrontier!");
931     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
932     I->second.erase(Node);
933   }
934
935   /// compareDomSet - Return false if two domsets match. Otherwise
936   /// return true;
937   bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
938     std::set<BasicBlock *> tmpSet;
939     for (DomSetType::const_iterator I = DS2.begin(),
940            E = DS2.end(); I != E; ++I) 
941       tmpSet.insert(*I);
942
943     for (DomSetType::const_iterator I = DS1.begin(),
944            E = DS1.end(); I != E; ) {
945       BasicBlock *Node = *I++;
946
947       if (tmpSet.erase(Node) == 0)
948         // Node is in DS1 but not in DS2.
949         return true;
950     }
951
952     if(!tmpSet.empty())
953       // There are nodes that are in DS2 but not in DS1.
954       return true;
955
956     // DS1 and DS2 matches.
957     return false;
958   }
959
960   /// compare - Return true if the other dominance frontier base matches
961   /// this dominance frontier base. Otherwise return false.
962   bool compare(DominanceFrontierBase &Other) const {
963     DomSetMapType tmpFrontiers;
964     for (DomSetMapType::const_iterator I = Other.begin(),
965            E = Other.end(); I != E; ++I) 
966       tmpFrontiers.insert(std::make_pair(I->first, I->second));
967
968     for (DomSetMapType::iterator I = tmpFrontiers.begin(),
969            E = tmpFrontiers.end(); I != E; ) {
970       BasicBlock *Node = I->first;
971       const_iterator DFI = find(Node);
972       if (DFI == end()) 
973         return true;
974
975       if (compareDomSet(I->second, DFI->second))
976         return true;
977
978       ++I;
979       tmpFrontiers.erase(Node);
980     }
981
982     if (!tmpFrontiers.empty())
983       return true;
984
985     return false;
986   }
987
988   /// print - Convert to human readable form
989   ///
990   virtual void print(std::ostream &OS, const Module* = 0) const;
991   void print(std::ostream *OS, const Module* M = 0) const {
992     if (OS) print(*OS, M);
993   }
994   virtual void dump();
995 };
996
997
998 //===-------------------------------------
999 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
1000 /// used to compute a forward dominator frontiers.
1001 ///
1002 class DominanceFrontier : public DominanceFrontierBase {
1003 public:
1004   static char ID; // Pass ID, replacement for typeid
1005   DominanceFrontier() : 
1006     DominanceFrontierBase(&ID, false) {}
1007
1008   BasicBlock *getRoot() const {
1009     assert(Roots.size() == 1 && "Should always have entry node!");
1010     return Roots[0];
1011   }
1012
1013   virtual bool runOnFunction(Function &) {
1014     Frontiers.clear();
1015     DominatorTree &DT = getAnalysis<DominatorTree>();
1016     Roots = DT.getRoots();
1017     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1018     calculate(DT, DT[Roots[0]]);
1019     return false;
1020   }
1021
1022   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1023     AU.setPreservesAll();
1024     AU.addRequired<DominatorTree>();
1025   }
1026
1027   /// splitBlock - BB is split and now it has one successor. Update dominance
1028   /// frontier to reflect this change.
1029   void splitBlock(BasicBlock *BB);
1030
1031   /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1032   /// to reflect this change.
1033   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1034                                 DominatorTree *DT) {
1035     // NewBB is now  dominating BB. Which means BB's dominance
1036     // frontier is now part of NewBB's dominance frontier. However, BB
1037     // itself is not member of NewBB's dominance frontier.
1038     DominanceFrontier::iterator NewDFI = find(NewBB);
1039     DominanceFrontier::iterator DFI = find(BB);
1040     // If BB was an entry block then its frontier is empty.
1041     if (DFI == end())
1042       return;
1043     DominanceFrontier::DomSetType BBSet = DFI->second;
1044     for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1045            BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1046       BasicBlock *DFMember = *BBSetI;
1047       // Insert only if NewBB dominates DFMember.
1048       if (!DT->dominates(NewBB, DFMember))
1049         NewDFI->second.insert(DFMember);
1050     }
1051     NewDFI->second.erase(BB);
1052   }
1053
1054   const DomSetType &calculate(const DominatorTree &DT,
1055                               const DomTreeNode *Node);
1056 };
1057
1058
1059 } // End llvm namespace
1060
1061 #endif