Maintain ETNode as part of DomTreeNode.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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. ETForest: Efficient data structure for dominance comparisons and 
13 //     nearest-common-ancestor queries.
14 //  3. DominanceFrontier: Calculate and hold the dominance frontier for a
15 //     function.
16 //
17 //  These data structures are listed in increasing order of complexity.  It
18 //  takes longer to calculate the dominator frontier, for example, than the
19 //  DominatorTree mapping.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #ifndef LLVM_ANALYSIS_DOMINATORS_H
24 #define LLVM_ANALYSIS_DOMINATORS_H
25
26 #include "llvm/Analysis/ET-Forest.h"
27 #include "llvm/Pass.h"
28 #include <set>
29
30 namespace llvm {
31
32 class Instruction;
33
34 template <typename GraphType> struct GraphTraits;
35
36 //===----------------------------------------------------------------------===//
37 /// DominatorBase - Base class that other, more interesting dominator analyses
38 /// inherit from.
39 ///
40 class DominatorBase : public FunctionPass {
41 protected:
42   std::vector<BasicBlock*> Roots;
43   const bool IsPostDominators;
44   inline DominatorBase(intptr_t ID, bool isPostDom) : 
45     FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
46 public:
47
48   /// getRoots -  Return the root blocks of the current CFG.  This may include
49   /// multiple blocks if we are computing post dominators.  For forward
50   /// dominators, this will always be a single block (the entry node).
51   ///
52   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
53
54   /// isPostDominator - Returns true if analysis based of postdoms
55   ///
56   bool isPostDominator() const { return IsPostDominators; }
57 };
58
59
60 //===----------------------------------------------------------------------===//
61 // DomTreeNode - Dominator Tree Node
62
63 class DomTreeNode {
64   BasicBlock *TheBB;
65   DomTreeNode *IDom;
66   ETNode *ETN;
67   std::vector<DomTreeNode*> Children;
68 public:
69   typedef std::vector<DomTreeNode*>::iterator iterator;
70   typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
71   
72   iterator begin()             { return Children.begin(); }
73   iterator end()               { return Children.end(); }
74   const_iterator begin() const { return Children.begin(); }
75   const_iterator end()   const { return Children.end(); }
76   
77   inline BasicBlock *getBlock() const { return TheBB; }
78   inline DomTreeNode *getIDom() const { return IDom; }
79   inline ETNode *getETNode() const { return ETN; }
80   inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
81   
82   inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom, ETNode *E) 
83     : TheBB(BB), IDom(iDom), ETN(E) {
84     if (IDom)
85       ETN->setFather(IDom->getETNode());
86   }
87   inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
88   void setIDom(DomTreeNode *NewIDom);
89 };
90
91 //===----------------------------------------------------------------------===//
92 /// DominatorTree - Calculate the immediate dominator tree for a function.
93 ///
94 class DominatorTreeBase : public DominatorBase {
95
96 protected:
97   void reset();
98   typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
99   DomTreeNodeMapType DomTreeNodes;
100   DomTreeNode *RootNode;
101
102   typedef std::map<BasicBlock*, ETNode*> ETMapType;
103   ETMapType ETNodes;
104
105   bool DFSInfoValid;
106   unsigned int SlowQueries;
107   // Information record used during immediate dominators computation.
108   struct InfoRec {
109     unsigned Semi;
110     unsigned Size;
111     BasicBlock *Label, *Parent, *Child, *Ancestor;
112
113     std::vector<BasicBlock*> Bucket;
114
115     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
116   };
117
118   std::map<BasicBlock*, BasicBlock*> IDoms;
119
120   // Vertex - Map the DFS number to the BasicBlock*
121   std::vector<BasicBlock*> Vertex;
122
123   // Info - Collection of information used during the computation of idoms.
124   std::map<BasicBlock*, InfoRec> Info;
125
126   public:
127   DominatorTreeBase(intptr_t ID, bool isPostDom) 
128     : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
129   ~DominatorTreeBase() { reset(); }
130
131   virtual void releaseMemory() { reset(); }
132
133   /// getNode - return the (Post)DominatorTree node for the specified basic
134   /// block.  This is the same as using operator[] on this class.
135   ///
136   inline DomTreeNode *getNode(BasicBlock *BB) const {
137     DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
138     return (i != DomTreeNodes.end()) ? i->second : 0;
139   }
140
141   inline DomTreeNode *operator[](BasicBlock *BB) const {
142     return getNode(BB);
143   }
144
145   /// getRootNode - This returns the entry node for the CFG of the function.  If
146   /// this tree represents the post-dominance relations for a function, however,
147   /// this root may be a node with the block == NULL.  This is the case when
148   /// there are multiple exit nodes from a particular function.  Consumers of
149   /// post-dominance information must be capable of dealing with this
150   /// possibility.
151   ///
152   DomTreeNode *getRootNode() { return RootNode; }
153   const DomTreeNode *getRootNode() const { return RootNode; }
154
155   /// properlyDominates - Returns true iff this dominates N and this != N.
156   /// Note that this is not a constant time operation!
157   ///
158   bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
159     if (A == 0 || B == 0) return false;
160     return dominatedBySlowTreeWalk(A, B);
161   }
162
163   bool dominatedBySlowTreeWalk(const DomTreeNode *A, 
164                                const DomTreeNode *B) const {
165     const DomTreeNode *IDom;
166     if (A == 0 || B == 0) return false;
167     while ((IDom = B->getIDom()) != 0 && IDom != A)
168       B = IDom;   // Walk up the tree
169     return IDom != 0;
170   }
171
172   void updateDFSNumbers();  
173   /// dominates - Returns true iff this dominates N.  Note that this is not a
174   /// constant time operation!
175   ///
176   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
177     if (B == A) return true;  // A node trivially dominates itself.
178
179     ETNode *NodeA = A->getETNode();
180     ETNode *NodeB = B->getETNode();
181     
182     if (DFSInfoValid)
183       return NodeB->DominatedBy(NodeA);
184
185     // If we end up with too many slow queries, just update the
186     // DFS numbers on the theory that we are going to keep querying.
187     SlowQueries++;
188     if (SlowQueries > 32) {
189       updateDFSNumbers();
190       return NodeB->DominatedBy(NodeA);
191     }
192     //return NodeB->DominatedBySlow(NodeA);
193     return dominatedBySlowTreeWalk(A, B);
194   }
195   
196   //===--------------------------------------------------------------------===//
197   // API to update (Post)DominatorTree information based on modifications to
198   // the CFG...
199
200   /// addNewBlock - Add a new node to the dominator tree information.  This
201   /// creates a new node as a child of DomBB dominator node,linking it into 
202   /// the children list of the immediate dominator.
203   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
204     assert(getNode(BB) == 0 && "Block already in dominator tree!");
205     DomTreeNode *IDomNode = getNode(DomBB);
206     assert(IDomNode && "Not immediate dominator specified for block!");
207     DFSInfoValid = false;
208     ETNode *E = new ETNode(BB);
209     ETNodes[BB] = E;
210     return DomTreeNodes[BB] = 
211       IDomNode->addChild(new DomTreeNode(BB, IDomNode, E));
212   }
213
214   /// changeImmediateDominator - This method is used to update the dominator
215   /// tree information when a node's immediate dominator changes.
216   ///
217   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
218     assert(N && NewIDom && "Cannot change null node pointers!");
219     DFSInfoValid = false;
220     N->setIDom(NewIDom);
221   }
222
223   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
224     changeImmediateDominator(getNode(BB), getNode(NewBB));
225   }
226
227   /// removeNode - Removes a node from the dominator tree.  Block must not
228   /// dominate any other blocks.  Invalidates any node pointing to removed
229   /// block.
230   void removeNode(BasicBlock *BB) {
231     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
232     DomTreeNodes.erase(BB);
233   }
234
235   /// print - Convert to human readable form
236   ///
237   virtual void print(std::ostream &OS, const Module* = 0) const;
238   void print(std::ostream *OS, const Module* M = 0) const {
239     if (OS) print(*OS, M);
240   }
241   virtual void dump();
242 };
243
244 //===-------------------------------------
245 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
246 /// compute a normal dominator tree.
247 ///
248 class DominatorTree : public DominatorTreeBase {
249 public:
250   static char ID; // Pass ID, replacement for typeid
251   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
252   
253   BasicBlock *getRoot() const {
254     assert(Roots.size() == 1 && "Should always have entry node!");
255     return Roots[0];
256   }
257   
258   virtual bool runOnFunction(Function &F);
259   
260   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
261     AU.setPreservesAll();
262   }
263 private:
264   void calculate(Function& F);
265   DomTreeNode *getNodeForBlock(BasicBlock *BB);
266   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
267   void Compress(BasicBlock *V);
268   BasicBlock *Eval(BasicBlock *v);
269   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
270   inline BasicBlock *getIDom(BasicBlock *BB) const {
271       std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
272       return I != IDoms.end() ? I->second : 0;
273     }
274 };
275
276 //===-------------------------------------
277 /// DominatorTree GraphTraits specialization so the DominatorTree can be
278 /// iterable by generic graph iterators.
279 ///
280 template <> struct GraphTraits<DomTreeNode*> {
281   typedef DomTreeNode NodeType;
282   typedef NodeType::iterator  ChildIteratorType;
283   
284   static NodeType *getEntryNode(NodeType *N) {
285     return N;
286   }
287   static inline ChildIteratorType child_begin(NodeType* N) {
288     return N->begin();
289   }
290   static inline ChildIteratorType child_end(NodeType* N) {
291     return N->end();
292   }
293 };
294
295 template <> struct GraphTraits<DominatorTree*>
296   : public GraphTraits<DomTreeNode*> {
297   static NodeType *getEntryNode(DominatorTree *DT) {
298     return DT->getRootNode();
299   }
300 };
301
302
303 //===-------------------------------------
304 /// ET-Forest Class - Class used to construct forwards and backwards 
305 /// ET-Forests
306 ///
307 class ETForestBase : public DominatorBase {
308 public:
309   ETForestBase(intptr_t ID, bool isPostDom) 
310     : DominatorBase(ID, isPostDom), Nodes(), 
311       DFSInfoValid(false), SlowQueries(0) {}
312   
313   virtual void releaseMemory() { reset(); }
314
315   typedef std::map<BasicBlock*, ETNode*> ETMapType;
316
317   // FIXME : There is no need to make this interface public. 
318   // Fix predicate simplifier.
319   void updateDFSNumbers();
320     
321   /// dominates - Return true if A dominates B.
322   ///
323   inline bool dominates(BasicBlock *A, BasicBlock *B) {
324     if (A == B)
325       return true;
326     
327     ETNode *NodeA = getNode(A);
328     ETNode *NodeB = getNode(B);
329     
330     if (DFSInfoValid)
331       return NodeB->DominatedBy(NodeA);
332     else {
333       // If we end up with too many slow queries, just update the
334       // DFS numbers on the theory that we are going to keep querying.
335       SlowQueries++;
336       if (SlowQueries > 32) {
337         updateDFSNumbers();
338         return NodeB->DominatedBy(NodeA);
339       }
340       return NodeB->DominatedBySlow(NodeA);
341     }
342   }
343
344   // dominates - Return true if A dominates B. This performs the
345   // special checks necessary if A and B are in the same basic block.
346   bool dominates(Instruction *A, Instruction *B);
347
348   /// properlyDominates - Return true if A dominates B and A != B.
349   ///
350   bool properlyDominates(BasicBlock *A, BasicBlock *B) {
351     return dominates(A, B) && A != B;
352   }
353
354   /// isReachableFromEntry - Return true if A is dominated by the entry
355   /// block of the function containing it.
356   const bool isReachableFromEntry(BasicBlock* A);
357   
358   /// Return the nearest common dominator of A and B.
359   BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
360     ETNode *NodeA = getNode(A);
361     ETNode *NodeB = getNode(B);
362     
363     ETNode *Common = NodeA->NCA(NodeB);
364     if (!Common)
365       return NULL;
366     return Common->getData<BasicBlock>();
367   }
368   
369   /// Return the immediate dominator of A.
370   BasicBlock *getIDom(BasicBlock *A) const {
371     ETNode *NodeA = getNode(A);
372     if (!NodeA) return 0;
373     const ETNode *idom = NodeA->getFather();
374     return idom ? idom->getData<BasicBlock>() : 0;
375   }
376   
377   void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
378     ETNode *NodeA = getNode(A);
379     if (!NodeA) return;
380     const ETNode* son = NodeA->getSon();
381     
382     if (!son) return;
383     children.push_back(son->getData<BasicBlock>());
384         
385     const ETNode* brother = son->getBrother();
386     while (brother != son) {
387       children.push_back(brother->getData<BasicBlock>());
388       brother = brother->getBrother();
389     }
390   }
391
392   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
393     AU.setPreservesAll();
394     AU.addRequired<DominatorTree>();
395   }
396   //===--------------------------------------------------------------------===//
397   // API to update Forest information based on modifications
398   // to the CFG...
399
400   /// addNewBlock - Add a new block to the CFG, with the specified immediate
401   /// dominator.
402   ///
403   void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
404
405   /// setImmediateDominator - Update the immediate dominator information to
406   /// change the current immediate dominator for the specified block
407   /// to another block.  This method requires that BB for NewIDom
408   /// already have an ETNode, otherwise just use addNewBlock.
409   ///
410   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
411   /// print - Convert to human readable form
412   ///
413   virtual void print(std::ostream &OS, const Module* = 0) const;
414   void print(std::ostream *OS, const Module* M = 0) const {
415     if (OS) print(*OS, M);
416   }
417   virtual void dump();
418 protected:
419   /// getNode - return the (Post)DominatorTree node for the specified basic
420   /// block.  This is the same as using operator[] on this class.
421   ///
422   inline ETNode *getNode(BasicBlock *BB) const {
423     ETMapType::const_iterator i = Nodes.find(BB);
424     return (i != Nodes.end()) ? i->second : 0;
425   }
426
427   inline ETNode *operator[](BasicBlock *BB) const {
428     return getNode(BB);
429   }
430
431   void reset();
432   ETMapType Nodes;
433   bool DFSInfoValid;
434   unsigned int SlowQueries;
435
436 };
437
438 //==-------------------------------------
439 /// ETForest Class - Concrete subclass of ETForestBase that is used to
440 /// compute a forwards ET-Forest.
441
442 class ETForest : public ETForestBase {
443 public:
444   static char ID; // Pass identification, replacement for typeid
445
446   ETForest() : ETForestBase((intptr_t)&ID, false) {}
447
448   BasicBlock *getRoot() const {
449     assert(Roots.size() == 1 && "Should always have entry node!");
450     return Roots[0];
451   }
452
453   virtual bool runOnFunction(Function &F) {
454     reset();     // Reset from the last time we were run...
455     DominatorTree &DT = getAnalysis<DominatorTree>();
456     Roots = DT.getRoots();
457     calculate(DT);
458     return false;
459   }
460
461   void calculate(const DominatorTree &DT);
462   // FIXME : There is no need to make getNodeForBlock public. Fix
463   // predicate simplifier.
464   ETNode *getNodeForBlock(BasicBlock *BB);
465 };
466
467 //===----------------------------------------------------------------------===//
468 /// DominanceFrontierBase - Common base class for computing forward and inverse
469 /// dominance frontiers for a function.
470 ///
471 class DominanceFrontierBase : public DominatorBase {
472 public:
473   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
474   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
475 protected:
476   DomSetMapType Frontiers;
477 public:
478   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
479     : DominatorBase(ID, isPostDom) {}
480
481   virtual void releaseMemory() { Frontiers.clear(); }
482
483   // Accessor interface:
484   typedef DomSetMapType::iterator iterator;
485   typedef DomSetMapType::const_iterator const_iterator;
486   iterator       begin()       { return Frontiers.begin(); }
487   const_iterator begin() const { return Frontiers.begin(); }
488   iterator       end()         { return Frontiers.end(); }
489   const_iterator end()   const { return Frontiers.end(); }
490   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
491   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
492
493   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
494     assert(find(BB) == end() && "Block already in DominanceFrontier!");
495     Frontiers.insert(std::make_pair(BB, frontier));
496   }
497
498   void addToFrontier(iterator I, BasicBlock *Node) {
499     assert(I != end() && "BB is not in DominanceFrontier!");
500     I->second.insert(Node);
501   }
502
503   void removeFromFrontier(iterator I, BasicBlock *Node) {
504     assert(I != end() && "BB is not in DominanceFrontier!");
505     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
506     I->second.erase(Node);
507   }
508
509   /// print - Convert to human readable form
510   ///
511   virtual void print(std::ostream &OS, const Module* = 0) const;
512   void print(std::ostream *OS, const Module* M = 0) const {
513     if (OS) print(*OS, M);
514   }
515   virtual void dump();
516 };
517
518
519 //===-------------------------------------
520 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
521 /// used to compute a forward dominator frontiers.
522 ///
523 class DominanceFrontier : public DominanceFrontierBase {
524 public:
525   static char ID; // Pass ID, replacement for typeid
526   DominanceFrontier() : 
527     DominanceFrontierBase((intptr_t)& ID, false) {}
528
529   BasicBlock *getRoot() const {
530     assert(Roots.size() == 1 && "Should always have entry node!");
531     return Roots[0];
532   }
533
534   virtual bool runOnFunction(Function &) {
535     Frontiers.clear();
536     DominatorTree &DT = getAnalysis<DominatorTree>();
537     Roots = DT.getRoots();
538     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
539     calculate(DT, DT[Roots[0]]);
540     return false;
541   }
542
543   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
544     AU.setPreservesAll();
545     AU.addRequired<DominatorTree>();
546   }
547
548 private:
549   const DomSetType &calculate(const DominatorTree &DT,
550                               const DomTreeNode *Node);
551 };
552
553
554 } // End llvm namespace
555
556 #endif