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. DominatorSet: Calculates the [reverse] dominator set for a function
14 // 3. DominatorTree: Represent the ImmediateDominator as an explicit tree
16 // 4. ETForest: Efficient data structure for dominance comparisons and
17 // nearest-common-ancestor queries.
18 // 5. DominanceFrontier: Calculate and hold the dominance frontier for a
21 // These data structures are listed in increasing order of complexity. It
22 // takes longer to calculate the dominator frontier, for example, than the
23 // ImmediateDominator mapping.
25 //===----------------------------------------------------------------------===//
27 #ifndef LLVM_ANALYSIS_DOMINATORS_H
28 #define LLVM_ANALYSIS_DOMINATORS_H
30 #include "llvm/Analysis/ET-Forest.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;
149 //===-------------------------------------
150 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
151 /// that is used to compute a normal immediate dominator set.
153 class ImmediateDominators : public ImmediateDominatorsBase {
155 ImmediateDominators() : ImmediateDominatorsBase(false) {}
157 BasicBlock *getRoot() const {
158 assert(Roots.size() == 1 && "Should always have entry node!");
162 virtual bool runOnFunction(Function &F);
164 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.setPreservesAll();
169 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
170 void Compress(BasicBlock *V, InfoRec &VInfo);
171 BasicBlock *Eval(BasicBlock *v);
172 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
177 //===----------------------------------------------------------------------===//
178 /// DominatorSet - Maintain a set<BasicBlock*> for every basic block in a
179 /// function, that represents the blocks that dominate the block. If the block
180 /// is unreachable in this function, the set will be empty. This cannot happen
181 /// for reachable code, because every block dominates at least itself.
183 class DominatorSetBase : public DominatorBase {
185 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
187 typedef std::map<BasicBlock*, DomSetType> DomSetMapType;
191 DominatorSetBase(bool isPostDom) : DominatorBase(isPostDom) {}
193 virtual void releaseMemory() { Doms.clear(); }
195 // Accessor interface:
196 typedef DomSetMapType::const_iterator const_iterator;
197 typedef DomSetMapType::iterator iterator;
198 inline const_iterator begin() const { return Doms.begin(); }
199 inline iterator begin() { return Doms.begin(); }
200 inline const_iterator end() const { return Doms.end(); }
201 inline iterator end() { return Doms.end(); }
202 inline const_iterator find(BasicBlock* B) const { return Doms.find(B); }
203 inline iterator find(BasicBlock* B) { return Doms.find(B); }
206 /// getDominators - Return the set of basic blocks that dominate the specified
209 inline const DomSetType &getDominators(BasicBlock *BB) const {
210 const_iterator I = find(BB);
211 assert(I != end() && "BB not in function!");
215 /// isReachable - Return true if the specified basicblock is reachable. If
216 /// the block is reachable, we have dominator set information for it.
218 bool isReachable(BasicBlock *BB) const {
219 return !getDominators(BB).empty();
222 /// dominates - Return true if A dominates B.
224 inline bool dominates(BasicBlock *A, BasicBlock *B) const {
225 return getDominators(B).count(A) != 0;
228 /// properlyDominates - Return true if A dominates B and A != B.
230 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
231 return dominates(A, B) && A != B;
234 /// print - Convert to human readable form
236 virtual void print(std::ostream &OS, const Module* = 0) const;
238 /// dominates - Return true if A dominates B. This performs the special
239 /// checks necessary if A and B are in the same basic block.
241 bool dominates(Instruction *A, Instruction *B) const;
243 //===--------------------------------------------------------------------===//
244 // API to update (Post)DominatorSet information based on modifications to
247 /// addBasicBlock - Call to update the dominator set with information about a
248 /// new block that was inserted into the function.
250 void addBasicBlock(BasicBlock *BB, const DomSetType &Dominators) {
251 assert(find(BB) == end() && "Block already in DominatorSet!");
252 Doms.insert(std::make_pair(BB, Dominators));
255 /// addDominator - If a new block is inserted into the CFG, then method may be
256 /// called to notify the blocks it dominates that it is in their set.
258 void addDominator(BasicBlock *BB, BasicBlock *NewDominator) {
259 iterator I = find(BB);
260 assert(I != end() && "BB is not in DominatorSet!");
261 I->second.insert(NewDominator);
266 //===-------------------------------------
267 /// DominatorSet Class - Concrete subclass of DominatorSetBase that is used to
268 /// compute a normal dominator set.
270 class DominatorSet : public DominatorSetBase {
272 DominatorSet() : DominatorSetBase(false) {}
274 virtual bool runOnFunction(Function &F);
276 BasicBlock *getRoot() const {
277 assert(Roots.size() == 1 && "Should always have entry node!");
281 /// getAnalysisUsage - This simply provides a dominator set
283 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
284 AU.addRequired<ImmediateDominators>();
285 AU.setPreservesAll();
288 // stub - dummy function, just ignore it
293 //===----------------------------------------------------------------------===//
294 /// DominatorTree - Calculate the immediate dominator tree for a function.
296 class DominatorTreeBase : public DominatorBase {
300 std::map<BasicBlock*, Node*> Nodes;
302 typedef std::map<BasicBlock*, Node*> NodeMapType;
307 friend struct DominatorTree;
308 friend struct PostDominatorTree;
309 friend struct DominatorTreeBase;
312 std::vector<Node*> Children;
314 typedef std::vector<Node*>::iterator iterator;
315 typedef std::vector<Node*>::const_iterator const_iterator;
317 iterator begin() { return Children.begin(); }
318 iterator end() { return Children.end(); }
319 const_iterator begin() const { return Children.begin(); }
320 const_iterator end() const { return Children.end(); }
322 inline BasicBlock *getBlock() const { return TheBB; }
323 inline Node *getIDom() const { return IDom; }
324 inline const std::vector<Node*> &getChildren() const { return Children; }
326 /// properlyDominates - Returns true iff this dominates N and this != N.
327 /// Note that this is not a constant time operation!
329 bool properlyDominates(const Node *N) const {
331 if (this == 0 || N == 0) return false;
332 while ((IDom = N->getIDom()) != 0 && IDom != this)
333 N = IDom; // Walk up the tree
337 /// dominates - Returns true iff this dominates N. Note that this is not a
338 /// constant time operation!
340 inline bool dominates(const Node *N) const {
341 if (N == this) return true; // A node trivially dominates itself.
342 return properlyDominates(N);
346 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
347 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
349 void setIDom(Node *NewIDom);
353 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
354 ~DominatorTreeBase() { reset(); }
356 virtual void releaseMemory() { reset(); }
358 /// getNode - return the (Post)DominatorTree node for the specified basic
359 /// block. This is the same as using operator[] on this class.
361 inline Node *getNode(BasicBlock *BB) const {
362 NodeMapType::const_iterator i = Nodes.find(BB);
363 return (i != Nodes.end()) ? i->second : 0;
366 inline Node *operator[](BasicBlock *BB) const {
370 /// getRootNode - This returns the entry node for the CFG of the function. If
371 /// this tree represents the post-dominance relations for a function, however,
372 /// this root may be a node with the block == NULL. This is the case when
373 /// there are multiple exit nodes from a particular function. Consumers of
374 /// post-dominance information must be capable of dealing with this
377 Node *getRootNode() { return RootNode; }
378 const Node *getRootNode() const { return RootNode; }
380 //===--------------------------------------------------------------------===//
381 // API to update (Post)DominatorTree information based on modifications to
384 /// createNewNode - Add a new node to the dominator tree information. This
385 /// creates a new node as a child of IDomNode, linking it into the children
386 /// list of the immediate dominator.
388 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
389 assert(getNode(BB) == 0 && "Block already in dominator tree!");
390 assert(IDomNode && "Not immediate dominator specified for block!");
391 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
394 /// changeImmediateDominator - This method is used to update the dominator
395 /// tree information when a node's immediate dominator changes.
397 void changeImmediateDominator(Node *N, Node *NewIDom) {
398 assert(N && NewIDom && "Cannot change null node pointers!");
402 /// print - Convert to human readable form
404 virtual void print(std::ostream &OS, const Module* = 0) const;
408 //===-------------------------------------
409 /// ET-Forest Class - Class used to construct forwards and backwards
412 class ETForestBase : public DominatorBase {
414 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
415 DFSInfoValid(false), SlowQueries(0) {}
417 virtual void releaseMemory() { reset(); }
419 typedef std::map<BasicBlock*, ETNode*> ETMapType;
421 void updateDFSNumbers();
423 /// dominates - Return true if A dominates B.
425 inline bool dominates(BasicBlock *A, BasicBlock *B) {
429 ETNode *NodeA = getNode(A);
430 ETNode *NodeB = getNode(B);
433 return NodeB->DominatedBy(NodeA);
435 // If we end up with too many slow queries, just update the
436 // DFS numbers on the theory that we are going to keep querying.
438 if (SlowQueries > 32) {
440 return NodeB->DominatedBy(NodeA);
442 return NodeB->DominatedBySlow(NodeA);
446 /// properlyDominates - Return true if A dominates B and A != B.
448 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
449 return dominates(A, B) && A != B;
452 /// Return the nearest common dominator of A and B.
453 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
454 ETNode *NodeA = getNode(A);
455 ETNode *NodeB = getNode(B);
457 ETNode *Common = NodeA->NCA(NodeB);
460 return Common->getData<BasicBlock>();
463 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
464 AU.setPreservesAll();
465 AU.addRequired<ImmediateDominators>();
467 //===--------------------------------------------------------------------===//
468 // API to update Forest information based on modifications
471 /// addNewBlock - Add a new block to the CFG, with the specified immediate
474 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
476 /// setImmediateDominator - Update the immediate dominator information to
477 /// change the current immediate dominator for the specified block
478 /// to another block. This method requires that BB for NewIDom
479 /// already have an ETNode, otherwise just use addNewBlock.
481 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
482 /// print - Convert to human readable form
484 virtual void print(std::ostream &OS, const Module* = 0) const;
486 /// getNode - return the (Post)DominatorTree node for the specified basic
487 /// block. This is the same as using operator[] on this class.
489 inline ETNode *getNode(BasicBlock *BB) const {
490 ETMapType::const_iterator i = Nodes.find(BB);
491 return (i != Nodes.end()) ? i->second : 0;
494 inline ETNode *operator[](BasicBlock *BB) const {
501 unsigned int SlowQueries;
505 //==-------------------------------------
506 /// ETForest Class - Concrete subclass of ETForestBase that is used to
507 /// compute a forwards ET-Forest.
509 class ETForest : public ETForestBase {
511 ETForest() : ETForestBase(false) {}
513 BasicBlock *getRoot() const {
514 assert(Roots.size() == 1 && "Should always have entry node!");
518 virtual bool runOnFunction(Function &F) {
519 reset(); // Reset from the last time we were run...
520 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
521 Roots = ID.getRoots();
526 void calculate(const ImmediateDominators &ID);
527 ETNode *getNodeForBlock(BasicBlock *BB);
530 //===-------------------------------------
531 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
532 /// compute a normal dominator tree.
534 class DominatorTree : public DominatorTreeBase {
536 DominatorTree() : DominatorTreeBase(false) {}
538 BasicBlock *getRoot() const {
539 assert(Roots.size() == 1 && "Should always have entry node!");
543 virtual bool runOnFunction(Function &F) {
544 reset(); // Reset from the last time we were run...
545 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
546 Roots = ID.getRoots();
551 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
552 AU.setPreservesAll();
553 AU.addRequired<ImmediateDominators>();
556 void calculate(const ImmediateDominators &ID);
557 Node *getNodeForBlock(BasicBlock *BB);
560 //===-------------------------------------
561 /// DominatorTree GraphTraits specialization so the DominatorTree can be
562 /// iterable by generic graph iterators.
564 template <> struct GraphTraits<DominatorTree::Node*> {
565 typedef DominatorTree::Node NodeType;
566 typedef NodeType::iterator ChildIteratorType;
568 static NodeType *getEntryNode(NodeType *N) {
571 static inline ChildIteratorType child_begin(NodeType* N) {
574 static inline ChildIteratorType child_end(NodeType* N) {
579 template <> struct GraphTraits<DominatorTree*>
580 : public GraphTraits<DominatorTree::Node*> {
581 static NodeType *getEntryNode(DominatorTree *DT) {
582 return DT->getRootNode();
586 //===----------------------------------------------------------------------===//
587 /// DominanceFrontierBase - Common base class for computing forward and inverse
588 /// dominance frontiers for a function.
590 class DominanceFrontierBase : public DominatorBase {
592 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
593 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
595 DomSetMapType Frontiers;
597 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
599 virtual void releaseMemory() { Frontiers.clear(); }
601 // Accessor interface:
602 typedef DomSetMapType::iterator iterator;
603 typedef DomSetMapType::const_iterator const_iterator;
604 iterator begin() { return Frontiers.begin(); }
605 const_iterator begin() const { return Frontiers.begin(); }
606 iterator end() { return Frontiers.end(); }
607 const_iterator end() const { return Frontiers.end(); }
608 iterator find(BasicBlock *B) { return Frontiers.find(B); }
609 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
611 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
612 assert(find(BB) == end() && "Block already in DominanceFrontier!");
613 Frontiers.insert(std::make_pair(BB, frontier));
616 void addToFrontier(iterator I, BasicBlock *Node) {
617 assert(I != end() && "BB is not in DominanceFrontier!");
618 I->second.insert(Node);
621 void removeFromFrontier(iterator I, BasicBlock *Node) {
622 assert(I != end() && "BB is not in DominanceFrontier!");
623 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
624 I->second.erase(Node);
627 /// print - Convert to human readable form
629 virtual void print(std::ostream &OS, const Module* = 0) const;
633 //===-------------------------------------
634 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
635 /// used to compute a forward dominator frontiers.
637 class DominanceFrontier : public DominanceFrontierBase {
639 DominanceFrontier() : DominanceFrontierBase(false) {}
641 BasicBlock *getRoot() const {
642 assert(Roots.size() == 1 && "Should always have entry node!");
646 virtual bool runOnFunction(Function &) {
648 DominatorTree &DT = getAnalysis<DominatorTree>();
649 Roots = DT.getRoots();
650 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
651 calculate(DT, DT[Roots[0]]);
655 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
656 AU.setPreservesAll();
657 AU.addRequired<DominatorTree>();
660 const DomSetType &calculate(const DominatorTree &DT,
661 const DominatorTree::Node *Node);
665 } // End llvm namespace
667 // Make sure that any clients of this file link in Dominators.cpp
668 FORCE_DEFINING_FILE_TO_BE_LINKED(DominatorSet)