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