Add BasicBlock level dominates(A,B) interface.
[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
174   /// dominates - Returns true iff this dominates N.  Note that this is not a
175   /// constant time operation!
176   ///
177   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
178     if (B == A) 
179       return true;  // A node trivially dominates itself.
180
181     if (A == 0 || B == 0)
182       return false;
183
184     ETNode *NodeA = A->getETNode();
185     ETNode *NodeB = B->getETNode();
186     
187     if (DFSInfoValid)
188       return NodeB->DominatedBy(NodeA);
189
190     // If we end up with too many slow queries, just update the
191     // DFS numbers on the theory that we are going to keep querying.
192     SlowQueries++;
193     if (SlowQueries > 32) {
194       updateDFSNumbers();
195       return NodeB->DominatedBy(NodeA);
196     }
197     //return NodeB->DominatedBySlow(NodeA);
198     return dominatedBySlowTreeWalk(A, B);
199   }
200
201   inline bool dominates(BasicBlock *A, BasicBlock *B) {
202     if (A == B) 
203       return true;
204     
205     return dominates(getNode(A), getNode(B));
206   }
207
208   //===--------------------------------------------------------------------===//
209   // API to update (Post)DominatorTree information based on modifications to
210   // the CFG...
211
212   /// addNewBlock - Add a new node to the dominator tree information.  This
213   /// creates a new node as a child of DomBB dominator node,linking it into 
214   /// the children list of the immediate dominator.
215   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
216     assert(getNode(BB) == 0 && "Block already in dominator tree!");
217     DomTreeNode *IDomNode = getNode(DomBB);
218     assert(IDomNode && "Not immediate dominator specified for block!");
219     DFSInfoValid = false;
220     ETNode *E = new ETNode(BB);
221     ETNodes[BB] = E;
222     return DomTreeNodes[BB] = 
223       IDomNode->addChild(new DomTreeNode(BB, IDomNode, E));
224   }
225
226   /// changeImmediateDominator - This method is used to update the dominator
227   /// tree information when a node's immediate dominator changes.
228   ///
229   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
230     assert(N && NewIDom && "Cannot change null node pointers!");
231     DFSInfoValid = false;
232     N->setIDom(NewIDom);
233   }
234
235   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
236     changeImmediateDominator(getNode(BB), getNode(NewBB));
237   }
238
239   /// removeNode - Removes a node from the dominator tree.  Block must not
240   /// dominate any other blocks.  Invalidates any node pointing to removed
241   /// block.
242   void removeNode(BasicBlock *BB) {
243     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
244     DomTreeNodes.erase(BB);
245   }
246
247   /// print - Convert to human readable form
248   ///
249   virtual void print(std::ostream &OS, const Module* = 0) const;
250   void print(std::ostream *OS, const Module* M = 0) const {
251     if (OS) print(*OS, M);
252   }
253   virtual void dump();
254 };
255
256 //===-------------------------------------
257 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
258 /// compute a normal dominator tree.
259 ///
260 class DominatorTree : public DominatorTreeBase {
261 public:
262   static char ID; // Pass ID, replacement for typeid
263   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
264   
265   BasicBlock *getRoot() const {
266     assert(Roots.size() == 1 && "Should always have entry node!");
267     return Roots[0];
268   }
269   
270   virtual bool runOnFunction(Function &F);
271   
272   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
273     AU.setPreservesAll();
274   }
275 private:
276   void calculate(Function& F);
277   DomTreeNode *getNodeForBlock(BasicBlock *BB);
278   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
279   void Compress(BasicBlock *V);
280   BasicBlock *Eval(BasicBlock *v);
281   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
282   inline BasicBlock *getIDom(BasicBlock *BB) const {
283       std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
284       return I != IDoms.end() ? I->second : 0;
285     }
286 };
287
288 //===-------------------------------------
289 /// DominatorTree GraphTraits specialization so the DominatorTree can be
290 /// iterable by generic graph iterators.
291 ///
292 template <> struct GraphTraits<DomTreeNode*> {
293   typedef DomTreeNode NodeType;
294   typedef NodeType::iterator  ChildIteratorType;
295   
296   static NodeType *getEntryNode(NodeType *N) {
297     return N;
298   }
299   static inline ChildIteratorType child_begin(NodeType* N) {
300     return N->begin();
301   }
302   static inline ChildIteratorType child_end(NodeType* N) {
303     return N->end();
304   }
305 };
306
307 template <> struct GraphTraits<DominatorTree*>
308   : public GraphTraits<DomTreeNode*> {
309   static NodeType *getEntryNode(DominatorTree *DT) {
310     return DT->getRootNode();
311   }
312 };
313
314
315 //===-------------------------------------
316 /// ET-Forest Class - Class used to construct forwards and backwards 
317 /// ET-Forests
318 ///
319 class ETForestBase : public DominatorBase {
320 public:
321   ETForestBase(intptr_t ID, bool isPostDom) 
322     : DominatorBase(ID, isPostDom), Nodes(), 
323       DFSInfoValid(false), SlowQueries(0) {}
324   
325   virtual void releaseMemory() { reset(); }
326
327   typedef std::map<BasicBlock*, ETNode*> ETMapType;
328
329   // FIXME : There is no need to make this interface public. 
330   // Fix predicate simplifier.
331   void updateDFSNumbers();
332     
333   /// dominates - Return true if A dominates B.
334   ///
335   inline bool dominates(BasicBlock *A, BasicBlock *B) {
336     if (A == B)
337       return true;
338     
339     ETNode *NodeA = getNode(A);
340     ETNode *NodeB = getNode(B);
341     
342     if (DFSInfoValid)
343       return NodeB->DominatedBy(NodeA);
344     else {
345       // If we end up with too many slow queries, just update the
346       // DFS numbers on the theory that we are going to keep querying.
347       SlowQueries++;
348       if (SlowQueries > 32) {
349         updateDFSNumbers();
350         return NodeB->DominatedBy(NodeA);
351       }
352       return NodeB->DominatedBySlow(NodeA);
353     }
354   }
355
356   // dominates - Return true if A dominates B. This performs the
357   // special checks necessary if A and B are in the same basic block.
358   bool dominates(Instruction *A, Instruction *B);
359
360   /// properlyDominates - Return true if A dominates B and A != B.
361   ///
362   bool properlyDominates(BasicBlock *A, BasicBlock *B) {
363     return dominates(A, B) && A != B;
364   }
365
366   /// isReachableFromEntry - Return true if A is dominated by the entry
367   /// block of the function containing it.
368   const bool isReachableFromEntry(BasicBlock* A);
369   
370   /// Return the nearest common dominator of A and B.
371   BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const  {
372     ETNode *NodeA = getNode(A);
373     ETNode *NodeB = getNode(B);
374     
375     ETNode *Common = NodeA->NCA(NodeB);
376     if (!Common)
377       return NULL;
378     return Common->getData<BasicBlock>();
379   }
380   
381   /// Return the immediate dominator of A.
382   BasicBlock *getIDom(BasicBlock *A) const {
383     ETNode *NodeA = getNode(A);
384     if (!NodeA) return 0;
385     const ETNode *idom = NodeA->getFather();
386     return idom ? idom->getData<BasicBlock>() : 0;
387   }
388   
389   void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
390     ETNode *NodeA = getNode(A);
391     if (!NodeA) return;
392     const ETNode* son = NodeA->getSon();
393     
394     if (!son) return;
395     children.push_back(son->getData<BasicBlock>());
396         
397     const ETNode* brother = son->getBrother();
398     while (brother != son) {
399       children.push_back(brother->getData<BasicBlock>());
400       brother = brother->getBrother();
401     }
402   }
403
404   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
405     AU.setPreservesAll();
406     AU.addRequired<DominatorTree>();
407   }
408   //===--------------------------------------------------------------------===//
409   // API to update Forest information based on modifications
410   // to the CFG...
411
412   /// addNewBlock - Add a new block to the CFG, with the specified immediate
413   /// dominator.
414   ///
415   void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
416
417   /// setImmediateDominator - Update the immediate dominator information to
418   /// change the current immediate dominator for the specified block
419   /// to another block.  This method requires that BB for NewIDom
420   /// already have an ETNode, otherwise just use addNewBlock.
421   ///
422   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
423   /// print - Convert to human readable form
424   ///
425   virtual void print(std::ostream &OS, const Module* = 0) const;
426   void print(std::ostream *OS, const Module* M = 0) const {
427     if (OS) print(*OS, M);
428   }
429   virtual void dump();
430 protected:
431   /// getNode - return the (Post)DominatorTree node for the specified basic
432   /// block.  This is the same as using operator[] on this class.
433   ///
434   inline ETNode *getNode(BasicBlock *BB) const {
435     ETMapType::const_iterator i = Nodes.find(BB);
436     return (i != Nodes.end()) ? i->second : 0;
437   }
438
439   inline ETNode *operator[](BasicBlock *BB) const {
440     return getNode(BB);
441   }
442
443   void reset();
444   ETMapType Nodes;
445   bool DFSInfoValid;
446   unsigned int SlowQueries;
447
448 };
449
450 //==-------------------------------------
451 /// ETForest Class - Concrete subclass of ETForestBase that is used to
452 /// compute a forwards ET-Forest.
453
454 class ETForest : public ETForestBase {
455 public:
456   static char ID; // Pass identification, replacement for typeid
457
458   ETForest() : ETForestBase((intptr_t)&ID, false) {}
459
460   BasicBlock *getRoot() const {
461     assert(Roots.size() == 1 && "Should always have entry node!");
462     return Roots[0];
463   }
464
465   virtual bool runOnFunction(Function &F) {
466     reset();     // Reset from the last time we were run...
467     DominatorTree &DT = getAnalysis<DominatorTree>();
468     Roots = DT.getRoots();
469     calculate(DT);
470     return false;
471   }
472
473   void calculate(const DominatorTree &DT);
474   // FIXME : There is no need to make getNodeForBlock public. Fix
475   // predicate simplifier.
476   ETNode *getNodeForBlock(BasicBlock *BB);
477 };
478
479 //===----------------------------------------------------------------------===//
480 /// DominanceFrontierBase - Common base class for computing forward and inverse
481 /// dominance frontiers for a function.
482 ///
483 class DominanceFrontierBase : public DominatorBase {
484 public:
485   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
486   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
487 protected:
488   DomSetMapType Frontiers;
489 public:
490   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
491     : DominatorBase(ID, isPostDom) {}
492
493   virtual void releaseMemory() { Frontiers.clear(); }
494
495   // Accessor interface:
496   typedef DomSetMapType::iterator iterator;
497   typedef DomSetMapType::const_iterator const_iterator;
498   iterator       begin()       { return Frontiers.begin(); }
499   const_iterator begin() const { return Frontiers.begin(); }
500   iterator       end()         { return Frontiers.end(); }
501   const_iterator end()   const { return Frontiers.end(); }
502   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
503   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
504
505   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
506     assert(find(BB) == end() && "Block already in DominanceFrontier!");
507     Frontiers.insert(std::make_pair(BB, frontier));
508   }
509
510   void addToFrontier(iterator I, BasicBlock *Node) {
511     assert(I != end() && "BB is not in DominanceFrontier!");
512     I->second.insert(Node);
513   }
514
515   void removeFromFrontier(iterator I, BasicBlock *Node) {
516     assert(I != end() && "BB is not in DominanceFrontier!");
517     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
518     I->second.erase(Node);
519   }
520
521   /// print - Convert to human readable form
522   ///
523   virtual void print(std::ostream &OS, const Module* = 0) const;
524   void print(std::ostream *OS, const Module* M = 0) const {
525     if (OS) print(*OS, M);
526   }
527   virtual void dump();
528 };
529
530
531 //===-------------------------------------
532 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
533 /// used to compute a forward dominator frontiers.
534 ///
535 class DominanceFrontier : public DominanceFrontierBase {
536 public:
537   static char ID; // Pass ID, replacement for typeid
538   DominanceFrontier() : 
539     DominanceFrontierBase((intptr_t)& ID, false) {}
540
541   BasicBlock *getRoot() const {
542     assert(Roots.size() == 1 && "Should always have entry node!");
543     return Roots[0];
544   }
545
546   virtual bool runOnFunction(Function &) {
547     Frontiers.clear();
548     DominatorTree &DT = getAnalysis<DominatorTree>();
549     Roots = DT.getRoots();
550     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
551     calculate(DT, DT[Roots[0]]);
552     return false;
553   }
554
555   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
556     AU.setPreservesAll();
557     AU.addRequired<DominatorTree>();
558   }
559
560 private:
561   const DomSetType &calculate(const DominatorTree &DT,
562                               const DomTreeNode *Node);
563 };
564
565
566 } // End llvm namespace
567
568 #endif