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