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