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