1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines the following classes:
11 // 1. ImmediateDominators: Calculates and holds a mapping between BasicBlocks
12 // and their immediate dominator.
13 // 2. DominatorTree: Represent the ImmediateDominator as an explicit tree
15 // 3. ETForest: Efficient data structure for dominance comparisons and
16 // nearest-common-ancestor queries.
17 // 4. DominanceFrontier: Calculate and hold the dominance frontier for a
20 // These data structures are listed in increasing order of complexity. It
21 // takes longer to calculate the dominator frontier, for example, than the
22 // ImmediateDominator mapping.
24 //===----------------------------------------------------------------------===//
26 #ifndef LLVM_ANALYSIS_DOMINATORS_H
27 #define LLVM_ANALYSIS_DOMINATORS_H
29 #include "llvm/Analysis/ET-Forest.h"
30 #include "llvm/Function.h"
31 #include "llvm/Pass.h"
38 template <typename GraphType> struct GraphTraits;
40 //===----------------------------------------------------------------------===//
41 /// DominatorBase - Base class that other, more interesting dominator analyses
44 class DominatorBase : public FunctionPass {
46 std::vector<BasicBlock*> Roots;
47 const bool IsPostDominators;
49 inline DominatorBase(bool isPostDom) : Roots(), IsPostDominators(isPostDom) {}
51 /// getRoots - Return the root blocks of the current CFG. This may include
52 /// multiple blocks if we are computing post dominators. For forward
53 /// dominators, this will always be a single block (the entry node).
55 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
57 /// isPostDominator - Returns true if analysis based of postdoms
59 bool isPostDominator() const { return IsPostDominators; }
63 //===----------------------------------------------------------------------===//
64 /// ImmediateDominators - Calculate the immediate dominator for each node in a
67 class ImmediateDominatorsBase : public DominatorBase {
72 BasicBlock *Label, *Parent, *Child, *Ancestor;
74 std::vector<BasicBlock*> Bucket;
76 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
79 std::map<BasicBlock*, BasicBlock*> IDoms;
81 // Vertex - Map the DFS number to the BasicBlock*
82 std::vector<BasicBlock*> Vertex;
84 // Info - Collection of information used during the computation of idoms.
85 std::map<BasicBlock*, InfoRec> Info;
87 ImmediateDominatorsBase(bool isPostDom) : DominatorBase(isPostDom) {}
89 virtual void releaseMemory() { IDoms.clear(); }
91 // Accessor interface:
92 typedef std::map<BasicBlock*, BasicBlock*> IDomMapType;
93 typedef IDomMapType::const_iterator const_iterator;
94 inline const_iterator begin() const { return IDoms.begin(); }
95 inline const_iterator end() const { return IDoms.end(); }
96 inline const_iterator find(BasicBlock* B) const { return IDoms.find(B);}
98 /// operator[] - Return the idom for the specified basic block. The start
99 /// node returns null, because it does not have an immediate dominator.
101 inline BasicBlock *operator[](BasicBlock *BB) const {
105 /// dominates - Return true if A dominates B.
107 bool dominates(BasicBlock *A, BasicBlock *B) const;
109 /// properlyDominates - Return true if A dominates B and A != B.
111 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
112 return A != B || properlyDominates(A, B);
115 /// get() - Synonym for operator[].
117 inline BasicBlock *get(BasicBlock *BB) const {
118 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
119 return I != IDoms.end() ? I->second : 0;
122 //===--------------------------------------------------------------------===//
123 // API to update Immediate(Post)Dominators information based on modifications
126 /// addNewBlock - Add a new block to the CFG, with the specified immediate
129 void addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
130 assert(get(BB) == 0 && "BasicBlock already in idom info!");
134 /// setImmediateDominator - Update the immediate dominator information to
135 /// change the current immediate dominator for the specified block to another
136 /// block. This method requires that BB already have an IDom, otherwise just
139 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom) {
140 assert(IDoms.find(BB) != IDoms.end() && "BB doesn't have idom yet!");
144 /// print - Convert to human readable form
146 virtual void print(std::ostream &OS, const Module* = 0) const;
147 void print(std::ostream *OS, const Module* M = 0) const {
148 if (OS) print(*OS, M);
152 //===-------------------------------------
153 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
154 /// that is used to compute a normal immediate dominator set.
156 class ImmediateDominators : public ImmediateDominatorsBase {
158 ImmediateDominators() : ImmediateDominatorsBase(false) {}
160 BasicBlock *getRoot() const {
161 assert(Roots.size() == 1 && "Should always have entry node!");
165 virtual bool runOnFunction(Function &F);
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.setPreservesAll();
172 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
173 void Compress(BasicBlock *V, InfoRec &VInfo);
174 BasicBlock *Eval(BasicBlock *v);
175 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
179 //===----------------------------------------------------------------------===//
180 /// DominatorTree - Calculate the immediate dominator tree for a function.
182 class DominatorTreeBase : public DominatorBase {
186 std::map<BasicBlock*, Node*> Nodes;
188 typedef std::map<BasicBlock*, Node*> NodeMapType;
193 friend class DominatorTree;
194 friend struct PostDominatorTree;
195 friend class DominatorTreeBase;
198 std::vector<Node*> Children;
200 typedef std::vector<Node*>::iterator iterator;
201 typedef std::vector<Node*>::const_iterator const_iterator;
203 iterator begin() { return Children.begin(); }
204 iterator end() { return Children.end(); }
205 const_iterator begin() const { return Children.begin(); }
206 const_iterator end() const { return Children.end(); }
208 inline BasicBlock *getBlock() const { return TheBB; }
209 inline Node *getIDom() const { return IDom; }
210 inline const std::vector<Node*> &getChildren() const { return Children; }
212 /// properlyDominates - Returns true iff this dominates N and this != N.
213 /// Note that this is not a constant time operation!
215 bool properlyDominates(const Node *N) const {
217 if (this == 0 || N == 0) return false;
218 while ((IDom = N->getIDom()) != 0 && IDom != this)
219 N = IDom; // Walk up the tree
223 /// dominates - Returns true iff this dominates N. Note that this is not a
224 /// constant time operation!
226 inline bool dominates(const Node *N) const {
227 if (N == this) return true; // A node trivially dominates itself.
228 return properlyDominates(N);
232 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
233 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
235 void setIDom(Node *NewIDom);
239 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
240 ~DominatorTreeBase() { reset(); }
242 virtual void releaseMemory() { reset(); }
244 /// getNode - return the (Post)DominatorTree node for the specified basic
245 /// block. This is the same as using operator[] on this class.
247 inline Node *getNode(BasicBlock *BB) const {
248 NodeMapType::const_iterator i = Nodes.find(BB);
249 return (i != Nodes.end()) ? i->second : 0;
252 inline Node *operator[](BasicBlock *BB) const {
256 /// getRootNode - This returns the entry node for the CFG of the function. If
257 /// this tree represents the post-dominance relations for a function, however,
258 /// this root may be a node with the block == NULL. This is the case when
259 /// there are multiple exit nodes from a particular function. Consumers of
260 /// post-dominance information must be capable of dealing with this
263 Node *getRootNode() { return RootNode; }
264 const Node *getRootNode() const { return RootNode; }
266 //===--------------------------------------------------------------------===//
267 // API to update (Post)DominatorTree information based on modifications to
270 /// createNewNode - Add a new node to the dominator tree information. This
271 /// creates a new node as a child of IDomNode, linking it into the children
272 /// list of the immediate dominator.
274 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
275 assert(getNode(BB) == 0 && "Block already in dominator tree!");
276 assert(IDomNode && "Not immediate dominator specified for block!");
277 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
280 /// changeImmediateDominator - This method is used to update the dominator
281 /// tree information when a node's immediate dominator changes.
283 void changeImmediateDominator(Node *N, Node *NewIDom) {
284 assert(N && NewIDom && "Cannot change null node pointers!");
288 /// removeNode - Removes a node from the dominator tree. Block must not
289 /// dominate any other blocks. Invalidates any node pointing to removed
291 void removeNode(BasicBlock *BB) {
292 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
296 /// print - Convert to human readable form
298 virtual void print(std::ostream &OS, const Module* = 0) const;
299 void print(std::ostream *OS, const Module* M = 0) const {
300 if (OS) print(*OS, M);
304 //===-------------------------------------
305 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
306 /// compute a normal dominator tree.
308 class DominatorTree : public DominatorTreeBase {
310 DominatorTree() : DominatorTreeBase(false) {}
312 BasicBlock *getRoot() const {
313 assert(Roots.size() == 1 && "Should always have entry node!");
317 virtual bool runOnFunction(Function &F) {
318 reset(); // Reset from the last time we were run...
319 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
320 Roots = ID.getRoots();
325 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
326 AU.setPreservesAll();
327 AU.addRequired<ImmediateDominators>();
330 void calculate(const ImmediateDominators &ID);
331 Node *getNodeForBlock(BasicBlock *BB);
334 //===-------------------------------------
335 /// DominatorTree GraphTraits specialization so the DominatorTree can be
336 /// iterable by generic graph iterators.
338 template <> struct GraphTraits<DominatorTree::Node*> {
339 typedef DominatorTree::Node NodeType;
340 typedef NodeType::iterator ChildIteratorType;
342 static NodeType *getEntryNode(NodeType *N) {
345 static inline ChildIteratorType child_begin(NodeType* N) {
348 static inline ChildIteratorType child_end(NodeType* N) {
353 template <> struct GraphTraits<DominatorTree*>
354 : public GraphTraits<DominatorTree::Node*> {
355 static NodeType *getEntryNode(DominatorTree *DT) {
356 return DT->getRootNode();
361 //===-------------------------------------
362 /// ET-Forest Class - Class used to construct forwards and backwards
365 class ETForestBase : public DominatorBase {
367 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
368 DFSInfoValid(false), SlowQueries(0) {}
370 virtual void releaseMemory() { reset(); }
372 typedef std::map<BasicBlock*, ETNode*> ETMapType;
374 void updateDFSNumbers();
376 /// dominates - Return true if A dominates B.
378 inline bool dominates(BasicBlock *A, BasicBlock *B) {
382 ETNode *NodeA = getNode(A);
383 ETNode *NodeB = getNode(B);
386 return NodeB->DominatedBy(NodeA);
388 // If we end up with too many slow queries, just update the
389 // DFS numbers on the theory that we are going to keep querying.
391 if (SlowQueries > 32) {
393 return NodeB->DominatedBy(NodeA);
395 return NodeB->DominatedBySlow(NodeA);
399 // dominates - Return true if A dominates B. This performs the
400 // special checks necessary if A and B are in the same basic block.
401 bool dominates(Instruction *A, Instruction *B);
403 /// properlyDominates - Return true if A dominates B and A != B.
405 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
406 return dominates(A, B) && A != B;
409 /// isReachableFromEntry - Return true if A is dominated by the entry
410 /// block of the function containing it.
411 bool isReachableFromEntry(BasicBlock* A) {
412 return dominates(&A->getParent()->getEntryBlock(), A);
415 /// Return the nearest common dominator of A and B.
416 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
417 ETNode *NodeA = getNode(A);
418 ETNode *NodeB = getNode(B);
420 ETNode *Common = NodeA->NCA(NodeB);
423 return Common->getData<BasicBlock>();
426 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
427 AU.setPreservesAll();
428 AU.addRequired<ImmediateDominators>();
430 //===--------------------------------------------------------------------===//
431 // API to update Forest information based on modifications
434 /// addNewBlock - Add a new block to the CFG, with the specified immediate
437 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
439 /// setImmediateDominator - Update the immediate dominator information to
440 /// change the current immediate dominator for the specified block
441 /// to another block. This method requires that BB for NewIDom
442 /// already have an ETNode, otherwise just use addNewBlock.
444 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
445 /// print - Convert to human readable form
447 virtual void print(std::ostream &OS, const Module* = 0) const;
448 void print(std::ostream *OS, const Module* M = 0) const {
449 if (OS) print(*OS, M);
452 /// getNode - return the (Post)DominatorTree node for the specified basic
453 /// block. This is the same as using operator[] on this class.
455 inline ETNode *getNode(BasicBlock *BB) const {
456 ETMapType::const_iterator i = Nodes.find(BB);
457 return (i != Nodes.end()) ? i->second : 0;
460 inline ETNode *operator[](BasicBlock *BB) const {
467 unsigned int SlowQueries;
471 //==-------------------------------------
472 /// ETForest Class - Concrete subclass of ETForestBase that is used to
473 /// compute a forwards ET-Forest.
475 class ETForest : public ETForestBase {
477 ETForest() : ETForestBase(false) {}
479 BasicBlock *getRoot() const {
480 assert(Roots.size() == 1 && "Should always have entry node!");
484 virtual bool runOnFunction(Function &F) {
485 reset(); // Reset from the last time we were run...
486 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
487 Roots = ID.getRoots();
492 void calculate(const ImmediateDominators &ID);
493 ETNode *getNodeForBlock(BasicBlock *BB);
496 //===----------------------------------------------------------------------===//
497 /// DominanceFrontierBase - Common base class for computing forward and inverse
498 /// dominance frontiers for a function.
500 class DominanceFrontierBase : public DominatorBase {
502 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
503 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
505 DomSetMapType Frontiers;
507 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
509 virtual void releaseMemory() { Frontiers.clear(); }
511 // Accessor interface:
512 typedef DomSetMapType::iterator iterator;
513 typedef DomSetMapType::const_iterator const_iterator;
514 iterator begin() { return Frontiers.begin(); }
515 const_iterator begin() const { return Frontiers.begin(); }
516 iterator end() { return Frontiers.end(); }
517 const_iterator end() const { return Frontiers.end(); }
518 iterator find(BasicBlock *B) { return Frontiers.find(B); }
519 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
521 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
522 assert(find(BB) == end() && "Block already in DominanceFrontier!");
523 Frontiers.insert(std::make_pair(BB, frontier));
526 void addToFrontier(iterator I, BasicBlock *Node) {
527 assert(I != end() && "BB is not in DominanceFrontier!");
528 I->second.insert(Node);
531 void removeFromFrontier(iterator I, BasicBlock *Node) {
532 assert(I != end() && "BB is not in DominanceFrontier!");
533 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
534 I->second.erase(Node);
537 /// print - Convert to human readable form
539 virtual void print(std::ostream &OS, const Module* = 0) const;
540 void print(std::ostream *OS, const Module* M = 0) const {
541 if (OS) print(*OS, M);
546 //===-------------------------------------
547 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
548 /// used to compute a forward dominator frontiers.
550 class DominanceFrontier : public DominanceFrontierBase {
552 DominanceFrontier() : DominanceFrontierBase(false) {}
554 BasicBlock *getRoot() const {
555 assert(Roots.size() == 1 && "Should always have entry node!");
559 virtual bool runOnFunction(Function &) {
561 DominatorTree &DT = getAnalysis<DominatorTree>();
562 Roots = DT.getRoots();
563 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
564 calculate(DT, DT[Roots[0]]);
568 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
569 AU.setPreservesAll();
570 AU.addRequired<DominatorTree>();
573 const DomSetType &calculate(const DominatorTree &DT,
574 const DominatorTree::Node *Node);
578 } // End llvm namespace