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