92d05dc7d588db1bcc460cf87aad34ca521b95c5
[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. DominanceFrontier: Calculate and hold the dominance frontier for a
13 //     function.
14 //
15 //  These data structures are listed in increasing order of complexity.  It
16 //  takes longer to calculate the dominator frontier, for example, than the
17 //  DominatorTree mapping.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
23
24 #include "llvm/Pass.h"
25 #include <set>
26
27 namespace llvm {
28
29 class Instruction;
30
31 template <typename GraphType> struct GraphTraits;
32
33 //===----------------------------------------------------------------------===//
34 /// DominatorBase - Base class that other, more interesting dominator analyses
35 /// inherit from.
36 ///
37 class DominatorBase : public FunctionPass {
38 protected:
39   std::vector<BasicBlock*> Roots;
40   const bool IsPostDominators;
41   inline DominatorBase(intptr_t ID, bool isPostDom) : 
42     FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
43 public:
44
45   /// getRoots -  Return the root blocks of the current CFG.  This may include
46   /// multiple blocks if we are computing post dominators.  For forward
47   /// dominators, this will always be a single block (the entry node).
48   ///
49   inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
50
51   /// isPostDominator - Returns true if analysis based of postdoms
52   ///
53   bool isPostDominator() const { return IsPostDominators; }
54 };
55
56
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 class DominatorTreeBase;
60 class PostDominatorTree;
61 class DomTreeNode {
62   BasicBlock *TheBB;
63   DomTreeNode *IDom;
64   std::vector<DomTreeNode*> Children;
65   int DFSNumIn, DFSNumOut;
66
67   friend class DominatorTreeBase;
68   friend class PostDominatorTree;
69 public:
70   typedef std::vector<DomTreeNode*>::iterator iterator;
71   typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
72   
73   iterator begin()             { return Children.begin(); }
74   iterator end()               { return Children.end(); }
75   const_iterator begin() const { return Children.begin(); }
76   const_iterator end()   const { return Children.end(); }
77   
78   inline BasicBlock *getBlock() const { return TheBB; }
79   inline DomTreeNode *getIDom() const { return IDom; }
80   inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
81   
82   inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
83     : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
84   inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
85   void setIDom(DomTreeNode *NewIDom);
86
87 private:
88   // Return true if this node is dominated by other. Use this only if DFS info is valid.
89   bool DominatedBy(const DomTreeNode *other) const {
90     return this->DFSNumIn >= other->DFSNumIn &&
91       this->DFSNumOut <= other->DFSNumOut;
92   }
93
94   /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
95   /// in dfs order.
96   void assignDFSNumber(int num);
97 };
98
99 //===----------------------------------------------------------------------===//
100 /// DominatorTree - Calculate the immediate dominator tree for a function.
101 ///
102 class DominatorTreeBase : public DominatorBase {
103
104 protected:
105   void reset();
106   typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
107   DomTreeNodeMapType DomTreeNodes;
108   DomTreeNode *RootNode;
109
110   bool DFSInfoValid;
111   unsigned int SlowQueries;
112   // Information record used during immediate dominators computation.
113   struct InfoRec {
114     unsigned Semi;
115     unsigned Size;
116     BasicBlock *Label, *Parent, *Child, *Ancestor;
117
118     std::vector<BasicBlock*> Bucket;
119
120     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
121   };
122
123   std::map<BasicBlock*, BasicBlock*> IDoms;
124
125   // Vertex - Map the DFS number to the BasicBlock*
126   std::vector<BasicBlock*> Vertex;
127
128   // Info - Collection of information used during the computation of idoms.
129   std::map<BasicBlock*, InfoRec> Info;
130
131   void updateDFSNumbers();
132
133   public:
134   DominatorTreeBase(intptr_t ID, bool isPostDom) 
135     : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
136   ~DominatorTreeBase() { reset(); }
137
138   virtual void releaseMemory() { reset(); }
139
140   /// getNode - return the (Post)DominatorTree node for the specified basic
141   /// block.  This is the same as using operator[] on this class.
142   ///
143   inline DomTreeNode *getNode(BasicBlock *BB) const {
144     DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
145     return (i != DomTreeNodes.end()) ? i->second : 0;
146   }
147
148   inline DomTreeNode *operator[](BasicBlock *BB) const {
149     return getNode(BB);
150   }
151
152   /// getIDomBlock - return basic block BB's immediate dominator basic block.
153   ///
154   BasicBlock *getIDomBlock(BasicBlock *BB) {
155     DomTreeNode *N = getNode(BB);
156     assert (N && "Missing dominator tree node");
157     DomTreeNode *I = N->getIDom();
158     assert (N && "Missing immediate dominator");
159     return I->getBlock();
160   }
161
162   /// getRootNode - This returns the entry node for the CFG of the function.  If
163   /// this tree represents the post-dominance relations for a function, however,
164   /// this root may be a node with the block == NULL.  This is the case when
165   /// there are multiple exit nodes from a particular function.  Consumers of
166   /// post-dominance information must be capable of dealing with this
167   /// possibility.
168   ///
169   DomTreeNode *getRootNode() { return RootNode; }
170   const DomTreeNode *getRootNode() const { return RootNode; }
171
172   /// properlyDominates - Returns true iff this dominates N and this != N.
173   /// Note that this is not a constant time operation!
174   ///
175   bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
176     if (A == 0 || B == 0) return false;
177     return dominatedBySlowTreeWalk(A, B);
178   }
179
180   inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
181     return properlyDominates(getNode(A), getNode(B));
182   }
183
184   bool dominatedBySlowTreeWalk(const DomTreeNode *A, 
185                                const DomTreeNode *B) const {
186     const DomTreeNode *IDom;
187     if (A == 0 || B == 0) return false;
188     while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
189       B = IDom;   // Walk up the tree
190     return IDom != 0;
191   }
192
193
194   /// isReachableFromEntry - Return true if A is dominated by the entry
195   /// block of the function containing it.
196   const bool isReachableFromEntry(BasicBlock* A);
197   
198   /// dominates - Returns true iff A dominates B.  Note that this is not a
199   /// constant time operation!
200   ///
201   inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
202     if (B == A) 
203       return true;  // A node trivially dominates itself.
204
205     if (A == 0 || B == 0)
206       return false;
207
208     if (DFSInfoValid)
209       return B->DominatedBy(A);
210
211     // If we end up with too many slow queries, just update the
212     // DFS numbers on the theory that we are going to keep querying.
213     SlowQueries++;
214     if (SlowQueries > 32) {
215       updateDFSNumbers();
216       return B->DominatedBy(A);
217     }
218
219     return dominatedBySlowTreeWalk(A, B);
220   }
221
222   inline bool dominates(BasicBlock *A, BasicBlock *B) {
223     if (A == B) 
224       return true;
225     
226     return dominates(getNode(A), getNode(B));
227   }
228
229   /// findNearestCommonDominator - Find nearest common dominator basic block
230   /// for basic block A and B. If there is no such block then return NULL.
231   BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
232
233   // dominates - Return true if A dominates B. This performs the
234   // special checks necessary if A and B are in the same basic block.
235   bool dominates(Instruction *A, Instruction *B);
236
237   //===--------------------------------------------------------------------===//
238   // API to update (Post)DominatorTree information based on modifications to
239   // the CFG...
240
241   /// addNewBlock - Add a new node to the dominator tree information.  This
242   /// creates a new node as a child of DomBB dominator node,linking it into 
243   /// the children list of the immediate dominator.
244   DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
245     assert(getNode(BB) == 0 && "Block already in dominator tree!");
246     DomTreeNode *IDomNode = getNode(DomBB);
247     // Check if BB dominates itself.
248     //if (!IDomNode && BB == DomBB) 
249     //  IDomNode = BB;
250     assert(IDomNode && "Not immediate dominator specified for block!");
251     DFSInfoValid = false;
252     return DomTreeNodes[BB] = 
253       IDomNode->addChild(new DomTreeNode(BB, IDomNode));
254   }
255
256   /// changeImmediateDominator - This method is used to update the dominator
257   /// tree information when a node's immediate dominator changes.
258   ///
259   void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
260     assert(N && NewIDom && "Cannot change null node pointers!");
261     DFSInfoValid = false;
262     N->setIDom(NewIDom);
263   }
264
265   void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
266     changeImmediateDominator(getNode(BB), getNode(NewBB));
267   }
268
269   /// removeNode - Removes a node from the dominator tree.  Block must not
270   /// dominate any other blocks.  Invalidates any node pointing to removed
271   /// block.
272   void removeNode(BasicBlock *BB) {
273     assert(getNode(BB) && "Removing node that isn't in dominator tree.");
274     DomTreeNodes.erase(BB);
275   }
276
277   /// print - Convert to human readable form
278   ///
279   virtual void print(std::ostream &OS, const Module* = 0) const;
280   void print(std::ostream *OS, const Module* M = 0) const {
281     if (OS) print(*OS, M);
282   }
283   virtual void dump();
284 };
285
286 //===-------------------------------------
287 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
288 /// compute a normal dominator tree.
289 ///
290 class DominatorTree : public DominatorTreeBase {
291 public:
292   static char ID; // Pass ID, replacement for typeid
293   DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
294   
295   BasicBlock *getRoot() const {
296     assert(Roots.size() == 1 && "Should always have entry node!");
297     return Roots[0];
298   }
299   
300   virtual bool runOnFunction(Function &F);
301   
302   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303     AU.setPreservesAll();
304   }
305
306   /// splitBlock
307   /// BB is split and now it has one successor. Update dominator tree to
308   /// reflect this change.
309   void splitBlock(BasicBlock *BB);
310 private:
311   void calculate(Function& F);
312   DomTreeNode *getNodeForBlock(BasicBlock *BB);
313   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
314   void Compress(BasicBlock *V);
315   BasicBlock *Eval(BasicBlock *v);
316   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
317   inline BasicBlock *getIDom(BasicBlock *BB) const {
318       std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
319       return I != IDoms.end() ? I->second : 0;
320     }
321 };
322
323 //===-------------------------------------
324 /// DominatorTree GraphTraits specialization so the DominatorTree can be
325 /// iterable by generic graph iterators.
326 ///
327 template <> struct GraphTraits<DomTreeNode*> {
328   typedef DomTreeNode NodeType;
329   typedef NodeType::iterator  ChildIteratorType;
330   
331   static NodeType *getEntryNode(NodeType *N) {
332     return N;
333   }
334   static inline ChildIteratorType child_begin(NodeType* N) {
335     return N->begin();
336   }
337   static inline ChildIteratorType child_end(NodeType* N) {
338     return N->end();
339   }
340 };
341
342 template <> struct GraphTraits<DominatorTree*>
343   : public GraphTraits<DomTreeNode*> {
344   static NodeType *getEntryNode(DominatorTree *DT) {
345     return DT->getRootNode();
346   }
347 };
348
349
350 //===----------------------------------------------------------------------===//
351 /// DominanceFrontierBase - Common base class for computing forward and inverse
352 /// dominance frontiers for a function.
353 ///
354 class DominanceFrontierBase : public DominatorBase {
355 public:
356   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
357   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
358 protected:
359   DomSetMapType Frontiers;
360 public:
361   DominanceFrontierBase(intptr_t ID, bool isPostDom) 
362     : DominatorBase(ID, isPostDom) {}
363
364   virtual void releaseMemory() { Frontiers.clear(); }
365
366   // Accessor interface:
367   typedef DomSetMapType::iterator iterator;
368   typedef DomSetMapType::const_iterator const_iterator;
369   iterator       begin()       { return Frontiers.begin(); }
370   const_iterator begin() const { return Frontiers.begin(); }
371   iterator       end()         { return Frontiers.end(); }
372   const_iterator end()   const { return Frontiers.end(); }
373   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
374   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
375
376   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
377     assert(find(BB) == end() && "Block already in DominanceFrontier!");
378     Frontiers.insert(std::make_pair(BB, frontier));
379   }
380
381   void addToFrontier(iterator I, BasicBlock *Node) {
382     assert(I != end() && "BB is not in DominanceFrontier!");
383     I->second.insert(Node);
384   }
385
386   void removeFromFrontier(iterator I, BasicBlock *Node) {
387     assert(I != end() && "BB is not in DominanceFrontier!");
388     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
389     I->second.erase(Node);
390   }
391
392   /// print - Convert to human readable form
393   ///
394   virtual void print(std::ostream &OS, const Module* = 0) const;
395   void print(std::ostream *OS, const Module* M = 0) const {
396     if (OS) print(*OS, M);
397   }
398   virtual void dump();
399 };
400
401
402 //===-------------------------------------
403 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
404 /// used to compute a forward dominator frontiers.
405 ///
406 class DominanceFrontier : public DominanceFrontierBase {
407 public:
408   static char ID; // Pass ID, replacement for typeid
409   DominanceFrontier() : 
410     DominanceFrontierBase((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 &) {
418     Frontiers.clear();
419     DominatorTree &DT = getAnalysis<DominatorTree>();
420     Roots = DT.getRoots();
421     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
422     calculate(DT, DT[Roots[0]]);
423     return false;
424   }
425
426   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
427     AU.setPreservesAll();
428     AU.addRequired<DominatorTree>();
429   }
430
431   /// splitBlock
432   /// BB is split and now it has one successor. Update dominace frontier to
433   /// reflect this change.
434   void splitBlock(BasicBlock *BB);
435
436 private:
437   const DomSetType &calculate(const DominatorTree &DT,
438                               const DomTreeNode *Node);
439 };
440
441
442 } // End llvm namespace
443
444 #endif