Fix the dominates method to return true if the two nodes are the same. Add
[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. ImmediateDominators: Calculates and holds a mapping between BasicBlocks
12 //     and their immediate dominator.
13 //  2. DominatorSet: Calculates the [reverse] dominator set for a function
14 //  3. DominatorTree: Represent the ImmediateDominator as an explicit tree
15 //     structure.
16 //  4. DominanceFrontier: Calculate and hold the dominance frontier for a
17 //     function.
18 //
19 //  These data structures are listed in increasing order of complexity.  It
20 //  takes longer to calculate the dominator frontier, for example, than the
21 //  ImmediateDominator mapping.
22 //
23 //===----------------------------------------------------------------------===//
24
25 #ifndef LLVM_ANALYSIS_DOMINATORS_H
26 #define LLVM_ANALYSIS_DOMINATORS_H
27
28 #include "llvm/Pass.h"
29 #include <set>
30
31 namespace llvm {
32
33 class Instruction;
34
35 template <typename GraphType> struct GraphTraits;
36
37 //===----------------------------------------------------------------------===//
38 /// DominatorBase - Base class that other, more interesting dominator analyses
39 /// inherit from.
40 ///
41 class DominatorBase : public FunctionPass {
42 protected:
43   std::vector<BasicBlock*> Roots;
44   const bool IsPostDominators;
45
46   inline DominatorBase(bool isPostDom) : Roots(), IsPostDominators(isPostDom) {}
47 public:
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 /// ImmediateDominators - Calculate the immediate dominator for each node in a
62 /// function.
63 ///
64 class ImmediateDominatorsBase : public DominatorBase {
65 protected:
66   std::map<BasicBlock*, BasicBlock*> IDoms;
67 public:
68   ImmediateDominatorsBase(bool isPostDom) : DominatorBase(isPostDom) {}
69
70   virtual void releaseMemory() { IDoms.clear(); }
71
72   // Accessor interface:
73   typedef std::map<BasicBlock*, BasicBlock*> IDomMapType;
74   typedef IDomMapType::const_iterator const_iterator;
75   inline const_iterator begin() const { return IDoms.begin(); }
76   inline const_iterator end()   const { return IDoms.end(); }
77   inline const_iterator find(BasicBlock* B) const { return IDoms.find(B);}
78
79   /// operator[] - Return the idom for the specified basic block.  The start
80   /// node returns null, because it does not have an immediate dominator.
81   ///
82   inline BasicBlock *operator[](BasicBlock *BB) const {
83     return get(BB);
84   }
85
86   /// get() - Synonym for operator[].
87   ///
88   inline BasicBlock *get(BasicBlock *BB) const {
89     std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
90     return I != IDoms.end() ? I->second : 0;
91   }
92
93   //===--------------------------------------------------------------------===//
94   // API to update Immediate(Post)Dominators information based on modifications
95   // to the CFG...
96
97   /// addNewBlock - Add a new block to the CFG, with the specified immediate
98   /// dominator.
99   ///
100   void addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
101     assert(get(BB) == 0 && "BasicBlock already in idom info!");
102     IDoms[BB] = IDom;
103   }
104
105   /// setImmediateDominator - Update the immediate dominator information to
106   /// change the current immediate dominator for the specified block to another
107   /// block.  This method requires that BB already have an IDom, otherwise just
108   /// use addNewBlock.
109   ///
110   void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom) {
111     assert(IDoms.find(BB) != IDoms.end() && "BB doesn't have idom yet!");
112     IDoms[BB] = NewIDom;
113   }
114
115   /// print - Convert to human readable form
116   ///
117   virtual void print(std::ostream &OS, const Module* = 0) const;
118 };
119
120 //===-------------------------------------
121 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
122 /// that is used to compute a normal immediate dominator set.
123 ///
124 struct ImmediateDominators : public ImmediateDominatorsBase {
125   ImmediateDominators() : ImmediateDominatorsBase(false) {}
126
127   BasicBlock *getRoot() const {
128     assert(Roots.size() == 1 && "Should always have entry node!");
129     return Roots[0];
130   }
131
132   virtual bool runOnFunction(Function &F);
133
134   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
135     AU.setPreservesAll();
136   }
137
138 private:
139   struct InfoRec {
140     unsigned Semi;
141     unsigned Size;
142     BasicBlock *Label, *Parent, *Child, *Ancestor;
143
144     std::vector<BasicBlock*> Bucket;
145
146     InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
147   };
148
149   // Vertex - Map the DFS number to the BasicBlock*
150   std::vector<BasicBlock*> Vertex;
151
152   // Info - Collection of information used during the computation of idoms.
153   std::map<BasicBlock*, InfoRec> Info;
154
155   unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
156   void Compress(BasicBlock *V, InfoRec &VInfo);
157   BasicBlock *Eval(BasicBlock *v);
158   void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
159 };
160
161
162
163 //===----------------------------------------------------------------------===//
164 /// DominatorSet - Maintain a set<BasicBlock*> for every basic block in a
165 /// function, that represents the blocks that dominate the block.  If the block
166 /// is unreachable in this function, the set will be empty.  This cannot happen
167 /// for reachable code, because every block dominates at least itself.
168 ///
169 struct DominatorSetBase : public DominatorBase {
170   typedef std::set<BasicBlock*> DomSetType;    // Dom set for a bb
171   // Map of dom sets
172   typedef std::map<BasicBlock*, DomSetType> DomSetMapType;
173 protected:
174   DomSetMapType Doms;
175 public:
176   DominatorSetBase(bool isPostDom) : DominatorBase(isPostDom) {}
177
178   virtual void releaseMemory() { Doms.clear(); }
179
180   // Accessor interface:
181   typedef DomSetMapType::const_iterator const_iterator;
182   typedef DomSetMapType::iterator iterator;
183   inline const_iterator begin() const { return Doms.begin(); }
184   inline       iterator begin()       { return Doms.begin(); }
185   inline const_iterator end()   const { return Doms.end(); }
186   inline       iterator end()         { return Doms.end(); }
187   inline const_iterator find(BasicBlock* B) const { return Doms.find(B); }
188   inline       iterator find(BasicBlock* B)       { return Doms.find(B); }
189
190
191   /// getDominators - Return the set of basic blocks that dominate the specified
192   /// block.
193   ///
194   inline const DomSetType &getDominators(BasicBlock *BB) const {
195     const_iterator I = find(BB);
196     assert(I != end() && "BB not in function!");
197     return I->second;
198   }
199
200   /// isReachable - Return true if the specified basicblock is reachable.  If
201   /// the block is reachable, we have dominator set information for it.
202   ///
203   bool isReachable(BasicBlock *BB) const {
204     return !getDominators(BB).empty();
205   }
206
207   /// dominates - Return true if A dominates B.
208   ///
209   inline bool dominates(BasicBlock *A, BasicBlock *B) const {
210     return getDominators(B).count(A) != 0;
211   }
212
213   /// properlyDominates - Return true if A dominates B and A != B.
214   ///
215   bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
216     return dominates(A, B) && A != B;
217   }
218
219   /// print - Convert to human readable form
220   ///
221   virtual void print(std::ostream &OS, const Module* = 0) const;
222
223   /// dominates - Return true if A dominates B.  This performs the special
224   /// checks necessary if A and B are in the same basic block.
225   ///
226   bool dominates(Instruction *A, Instruction *B) const;
227
228   //===--------------------------------------------------------------------===//
229   // API to update (Post)DominatorSet information based on modifications to
230   // the CFG...
231
232   /// addBasicBlock - Call to update the dominator set with information about a
233   /// new block that was inserted into the function.
234   ///
235   void addBasicBlock(BasicBlock *BB, const DomSetType &Dominators) {
236     assert(find(BB) == end() && "Block already in DominatorSet!");
237     Doms.insert(std::make_pair(BB, Dominators));
238   }
239
240   /// addDominator - If a new block is inserted into the CFG, then method may be
241   /// called to notify the blocks it dominates that it is in their set.
242   ///
243   void addDominator(BasicBlock *BB, BasicBlock *NewDominator) {
244     iterator I = find(BB);
245     assert(I != end() && "BB is not in DominatorSet!");
246     I->second.insert(NewDominator);
247   }
248 };
249
250
251 //===-------------------------------------
252 /// DominatorSet Class - Concrete subclass of DominatorSetBase that is used to
253 /// compute a normal dominator set.
254 ///
255 struct DominatorSet : public DominatorSetBase {
256   DominatorSet() : DominatorSetBase(false) {}
257
258   virtual bool runOnFunction(Function &F);
259
260   BasicBlock *getRoot() const {
261     assert(Roots.size() == 1 && "Should always have entry node!");
262     return Roots[0];
263   }
264
265   /// getAnalysisUsage - This simply provides a dominator set
266   ///
267   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
268     AU.addRequired<ImmediateDominators>();
269     AU.setPreservesAll();
270   }
271
272   // stub - dummy function, just ignore it
273   static void stub();
274 };
275
276
277 //===----------------------------------------------------------------------===//
278 /// DominatorTree - Calculate the immediate dominator tree for a function.
279 ///
280 struct DominatorTreeBase : public DominatorBase {
281   class Node;
282 protected:
283   std::map<BasicBlock*, Node*> Nodes;
284   void reset();
285   typedef std::map<BasicBlock*, Node*> NodeMapType;
286
287   Node *RootNode;
288 public:
289   class Node {
290     friend struct DominatorTree;
291     friend struct PostDominatorTree;
292     friend struct DominatorTreeBase;
293     BasicBlock *TheBB;
294     Node *IDom;
295     std::vector<Node*> Children;
296   public:
297     typedef std::vector<Node*>::iterator iterator;
298     typedef std::vector<Node*>::const_iterator const_iterator;
299
300     iterator begin()             { return Children.begin(); }
301     iterator end()               { return Children.end(); }
302     const_iterator begin() const { return Children.begin(); }
303     const_iterator end()   const { return Children.end(); }
304
305     inline BasicBlock *getBlock() const { return TheBB; }
306     inline Node *getIDom() const { return IDom; }
307     inline const std::vector<Node*> &getChildren() const { return Children; }
308
309     /// properlyDominates - Returns true iff this dominates N and this != N.
310     /// Note that this is not a constant time operation!
311     ///
312     bool properlyDominates(const Node *N) const {
313       const Node *IDom;
314       while ((IDom = N->getIDom()) != 0 && IDom != this)
315         N = IDom;   // Walk up the tree
316       return IDom != 0;
317     }
318
319     /// dominates - Returns true iff this dominates N.  Note that this is not a
320     /// constant time operation!
321     ///
322     inline bool dominates(const Node *N) const {
323       if (N == this) return true;  // A node trivially dominates itself.
324       return properlyDominates(N);
325     }
326     
327   private:
328     inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
329     inline Node *addChild(Node *C) { Children.push_back(C); return C; }
330
331     void setIDom(Node *NewIDom);
332   };
333
334 public:
335   DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
336   ~DominatorTreeBase() { reset(); }
337
338   virtual void releaseMemory() { reset(); }
339
340   /// getNode - return the (Post)DominatorTree node for the specified basic
341   /// block.  This is the same as using operator[] on this class.
342   ///
343   inline Node *getNode(BasicBlock *BB) const {
344     NodeMapType::const_iterator i = Nodes.find(BB);
345     return (i != Nodes.end()) ? i->second : 0;
346   }
347
348   inline Node *operator[](BasicBlock *BB) const {
349     return getNode(BB);
350   }
351
352   /// getRootNode - This returns the entry node for the CFG of the function.  If
353   /// this tree represents the post-dominance relations for a function, however,
354   /// this root may be a node with the block == NULL.  This is the case when
355   /// there are multiple exit nodes from a particular function.  Consumers of
356   /// post-dominance information must be capable of dealing with this
357   /// possibility.
358   ///
359   Node *getRootNode() { return RootNode; }
360   const Node *getRootNode() const { return RootNode; }
361
362   //===--------------------------------------------------------------------===//
363   // API to update (Post)DominatorTree information based on modifications to
364   // the CFG...
365
366   /// createNewNode - Add a new node to the dominator tree information.  This
367   /// creates a new node as a child of IDomNode, linking it into the children
368   /// list of the immediate dominator.
369   ///
370   Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
371     assert(getNode(BB) == 0 && "Block already in dominator tree!");
372     assert(IDomNode && "Not immediate dominator specified for block!");
373     return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
374   }
375
376   /// changeImmediateDominator - This method is used to update the dominator
377   /// tree information when a node's immediate dominator changes.
378   ///
379   void changeImmediateDominator(Node *N, Node *NewIDom) {
380     assert(N && NewIDom && "Cannot change null node pointers!");
381     N->setIDom(NewIDom);
382   }
383
384   /// print - Convert to human readable form
385   ///
386   virtual void print(std::ostream &OS, const Module* = 0) const;
387 };
388
389
390 //===-------------------------------------
391 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
392 /// compute a normal dominator tree.
393 ///
394 struct DominatorTree : public DominatorTreeBase {
395   DominatorTree() : DominatorTreeBase(false) {}
396
397   BasicBlock *getRoot() const {
398     assert(Roots.size() == 1 && "Should always have entry node!");
399     return Roots[0];
400   }
401
402   virtual bool runOnFunction(Function &F) {
403     reset();     // Reset from the last time we were run...
404     ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
405     Roots = ID.getRoots();
406     calculate(ID);
407     return false;
408   }
409
410   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
411     AU.setPreservesAll();
412     AU.addRequired<ImmediateDominators>();
413   }
414 private:
415   void calculate(const ImmediateDominators &ID);
416   Node *getNodeForBlock(BasicBlock *BB);
417 };
418
419 //===-------------------------------------
420 /// DominatorTree GraphTraits specialization so the DominatorTree can be
421 /// iterable by generic graph iterators.
422 ///
423 template <> struct GraphTraits<DominatorTree::Node*> {
424   typedef DominatorTree::Node NodeType;
425   typedef NodeType::iterator  ChildIteratorType;
426
427   static NodeType *getEntryNode(NodeType *N) {
428     return N;
429   }
430   static inline ChildIteratorType child_begin(NodeType* N) {
431     return N->begin();
432   }
433   static inline ChildIteratorType child_end(NodeType* N) {
434     return N->end();
435   }
436 };
437
438 template <> struct GraphTraits<DominatorTree*>
439   : public GraphTraits<DominatorTree::Node*> {
440   static NodeType *getEntryNode(DominatorTree *DT) {
441     return DT->getRootNode();
442   }
443 };
444
445 //===----------------------------------------------------------------------===//
446 /// DominanceFrontier - Calculate the dominance frontiers for a function.
447 ///
448 struct DominanceFrontierBase : public DominatorBase {
449   typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
450   typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
451 protected:
452   DomSetMapType Frontiers;
453 public:
454   DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
455
456   virtual void releaseMemory() { Frontiers.clear(); }
457
458   // Accessor interface:
459   typedef DomSetMapType::iterator iterator;
460   typedef DomSetMapType::const_iterator const_iterator;
461   iterator       begin()       { return Frontiers.begin(); }
462   const_iterator begin() const { return Frontiers.begin(); }
463   iterator       end()         { return Frontiers.end(); }
464   const_iterator end()   const { return Frontiers.end(); }
465   iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
466   const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
467
468   void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
469     assert(find(BB) == end() && "Block already in DominanceFrontier!");
470     Frontiers.insert(std::make_pair(BB, frontier));
471   }
472
473   void addToFrontier(iterator I, BasicBlock *Node) {
474     assert(I != end() && "BB is not in DominanceFrontier!");
475     I->second.insert(Node);
476   }
477
478   void removeFromFrontier(iterator I, BasicBlock *Node) {
479     assert(I != end() && "BB is not in DominanceFrontier!");
480     assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
481     I->second.erase(Node);
482   }
483
484   /// print - Convert to human readable form
485   ///
486   virtual void print(std::ostream &OS, const Module* = 0) const;
487 };
488
489
490 //===-------------------------------------
491 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
492 /// compute a normal dominator tree.
493 ///
494 struct DominanceFrontier : public DominanceFrontierBase {
495   DominanceFrontier() : DominanceFrontierBase(false) {}
496
497   BasicBlock *getRoot() const {
498     assert(Roots.size() == 1 && "Should always have entry node!");
499     return Roots[0];
500   }
501
502   virtual bool runOnFunction(Function &) {
503     Frontiers.clear();
504     DominatorTree &DT = getAnalysis<DominatorTree>();
505     Roots = DT.getRoots();
506     assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
507     calculate(DT, DT[Roots[0]]);
508     return false;
509   }
510
511   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
512     AU.setPreservesAll();
513     AU.addRequired<DominatorTree>();
514   }
515 private:
516   const DomSetType &calculate(const DominatorTree &DT,
517                               const DominatorTree::Node *Node);
518 };
519
520 // Make sure that any clients of this file link in Dominators.cpp
521 static IncludeFile
522 DOMINATORS_INCLUDE_FILE((void*)&DominatorSet::stub);
523 } // End llvm namespace
524
525 #endif