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