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