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