Dominators.h revision cbf39b58919497f711de24fa687b044805f58ae7
1//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the DominatorTree class, which provides fast and efficient
11// dominance queries.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_DOMINATORS_H
16#define LLVM_ANALYSIS_DOMINATORS_H
17
18#include "llvm/Pass.h"
19#include "llvm/Function.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DepthFirstIterator.h"
22#include "llvm/ADT/GraphTraits.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Support/CFG.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29
30namespace llvm {
31
32//===----------------------------------------------------------------------===//
33/// DominatorBase - Base class that other, more interesting dominator analyses
34/// inherit from.
35///
36template <class NodeT>
37class DominatorBase {
38protected:
39  std::vector<NodeT*> Roots;
40  const bool IsPostDominators;
41  inline explicit DominatorBase(bool isPostDom) :
42    Roots(), IsPostDominators(isPostDom) {}
43public:
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<NodeT*> &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
59template<class NodeT> class DominatorTreeBase;
60struct PostDominatorTree;
61class MachineBasicBlock;
62
63template <class NodeT>
64class DomTreeNodeBase {
65  NodeT *TheBB;
66  DomTreeNodeBase<NodeT> *IDom;
67  std::vector<DomTreeNodeBase<NodeT> *> Children;
68  int DFSNumIn, DFSNumOut;
69
70  template<class N> friend class DominatorTreeBase;
71  friend struct PostDominatorTree;
72public:
73  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74  typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
75                   const_iterator;
76
77  iterator begin()             { return Children.begin(); }
78  iterator end()               { return Children.end(); }
79  const_iterator begin() const { return Children.begin(); }
80  const_iterator end()   const { return Children.end(); }
81
82  NodeT *getBlock() const { return TheBB; }
83  DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
84  const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
85    return Children;
86  }
87
88  DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
89    : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
90
91  DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
92    Children.push_back(C);
93    return C;
94  }
95
96  size_t getNumChildren() const {
97    return Children.size();
98  }
99
100  void clearAllChildren() {
101    Children.clear();
102  }
103
104  bool compare(DomTreeNodeBase<NodeT> *Other) {
105    if (getNumChildren() != Other->getNumChildren())
106      return true;
107
108    SmallPtrSet<NodeT *, 4> OtherChildren;
109    for (iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110      NodeT *Nd = (*I)->getBlock();
111      OtherChildren.insert(Nd);
112    }
113
114    for (iterator I = begin(), E = end(); I != E; ++I) {
115      NodeT *N = (*I)->getBlock();
116      if (OtherChildren.count(N) == 0)
117        return true;
118    }
119    return false;
120  }
121
122  void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
123    assert(IDom && "No immediate dominator?");
124    if (IDom != NewIDom) {
125      typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
126                  std::find(IDom->Children.begin(), IDom->Children.end(), this);
127      assert(I != IDom->Children.end() &&
128             "Not in immediate dominator children set!");
129      // I am no longer your child...
130      IDom->Children.erase(I);
131
132      // Switch to new dominator
133      IDom = NewIDom;
134      IDom->Children.push_back(this);
135    }
136  }
137
138  /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
139  /// not call them.
140  unsigned getDFSNumIn() const { return DFSNumIn; }
141  unsigned getDFSNumOut() const { return DFSNumOut; }
142private:
143  // Return true if this node is dominated by other. Use this only if DFS info
144  // is valid.
145  bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146    return this->DFSNumIn >= other->DFSNumIn &&
147      this->DFSNumOut <= other->DFSNumOut;
148  }
149};
150
151EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
152EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
153
154template<class NodeT>
155static raw_ostream &operator<<(raw_ostream &o,
156                               const DomTreeNodeBase<NodeT> *Node) {
157  if (Node->getBlock())
158    WriteAsOperand(o, Node->getBlock(), false);
159  else
160    o << " <<exit node>>";
161
162  o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
163
164  return o << "\n";
165}
166
167template<class NodeT>
168static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
169                         unsigned Lev) {
170  o.indent(2*Lev) << "[" << Lev << "] " << N;
171  for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172       E = N->end(); I != E; ++I)
173    PrintDomTree<NodeT>(*I, o, Lev+1);
174}
175
176typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
177
178//===----------------------------------------------------------------------===//
179/// DominatorTree - Calculate the immediate dominator tree for a function.
180///
181
182template<class FuncT, class N>
183void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
184               FuncT& F);
185
186template<class NodeT>
187class DominatorTreeBase : public DominatorBase<NodeT> {
188protected:
189  typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
190  DomTreeNodeMapType DomTreeNodes;
191  DomTreeNodeBase<NodeT> *RootNode;
192
193  bool DFSInfoValid;
194  unsigned int SlowQueries;
195  // Information record used during immediate dominators computation.
196  struct InfoRec {
197    unsigned DFSNum;
198    unsigned Semi;
199    unsigned Size;
200    NodeT *Label, *Child;
201    unsigned Parent, Ancestor;
202
203    std::vector<NodeT*> Bucket;
204
205    InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
206                Ancestor(0) {}
207  };
208
209  DenseMap<NodeT*, NodeT*> IDoms;
210
211  // Vertex - Map the DFS number to the BasicBlock*
212  std::vector<NodeT*> Vertex;
213
214  // Info - Collection of information used during the computation of idoms.
215  DenseMap<NodeT*, InfoRec> Info;
216
217  void reset() {
218    for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
219           E = DomTreeNodes.end(); I != E; ++I)
220      delete I->second;
221    DomTreeNodes.clear();
222    IDoms.clear();
223    this->Roots.clear();
224    Vertex.clear();
225    RootNode = 0;
226  }
227
228  // NewBB is split and now it has one successor. Update dominator tree to
229  // reflect this change.
230  template<class N, class GraphT>
231  void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
232             typename GraphT::NodeType* NewBB) {
233    assert(std::distance(GraphT::child_begin(NewBB),
234                         GraphT::child_end(NewBB)) == 1 &&
235           "NewBB should have a single successor!");
236    typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
237
238    std::vector<typename GraphT::NodeType*> PredBlocks;
239    typedef GraphTraits<Inverse<N> > InvTraits;
240    for (typename InvTraits::ChildIteratorType PI =
241         InvTraits::child_begin(NewBB),
242         PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
243      PredBlocks.push_back(*PI);
244
245    assert(!PredBlocks.empty() && "No predblocks?");
246
247    bool NewBBDominatesNewBBSucc = true;
248    for (typename InvTraits::ChildIteratorType PI =
249         InvTraits::child_begin(NewBBSucc),
250         E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
251      typename InvTraits::NodeType *ND = *PI;
252      if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
253          DT.isReachableFromEntry(ND)) {
254        NewBBDominatesNewBBSucc = false;
255        break;
256      }
257    }
258
259    // Find NewBB's immediate dominator and create new dominator tree node for
260    // NewBB.
261    NodeT *NewBBIDom = 0;
262    unsigned i = 0;
263    for (i = 0; i < PredBlocks.size(); ++i)
264      if (DT.isReachableFromEntry(PredBlocks[i])) {
265        NewBBIDom = PredBlocks[i];
266        break;
267      }
268
269    // It's possible that none of the predecessors of NewBB are reachable;
270    // in that case, NewBB itself is unreachable, so nothing needs to be
271    // changed.
272    if (!NewBBIDom)
273      return;
274
275    for (i = i + 1; i < PredBlocks.size(); ++i) {
276      if (DT.isReachableFromEntry(PredBlocks[i]))
277        NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
278    }
279
280    // Create the new dominator tree node... and set the idom of NewBB.
281    DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
282
283    // If NewBB strictly dominates other blocks, then it is now the immediate
284    // dominator of NewBBSucc.  Update the dominator tree as appropriate.
285    if (NewBBDominatesNewBBSucc) {
286      DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
287      DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
288    }
289  }
290
291public:
292  explicit DominatorTreeBase(bool isPostDom)
293    : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
294  virtual ~DominatorTreeBase() { reset(); }
295
296  // FIXME: Should remove this
297  virtual bool runOnFunction(Function &F) { return false; }
298
299  /// compare - Return false if the other dominator tree base matches this
300  /// dominator tree base. Otherwise return true.
301  bool compare(DominatorTreeBase &Other) const {
302
303    const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
304    if (DomTreeNodes.size() != OtherDomTreeNodes.size())
305      return true;
306
307    for (typename DomTreeNodeMapType::const_iterator
308           I = this->DomTreeNodes.begin(),
309           E = this->DomTreeNodes.end(); I != E; ++I) {
310      NodeT *BB = I->first;
311      typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
312      if (OI == OtherDomTreeNodes.end())
313        return true;
314
315      DomTreeNodeBase<NodeT>* MyNd = I->second;
316      DomTreeNodeBase<NodeT>* OtherNd = OI->second;
317
318      if (MyNd->compare(OtherNd))
319        return true;
320    }
321
322    return false;
323  }
324
325  virtual void releaseMemory() { reset(); }
326
327  /// getNode - return the (Post)DominatorTree node for the specified basic
328  /// block.  This is the same as using operator[] on this class.
329  ///
330  inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
331    typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
332    return I != DomTreeNodes.end() ? I->second : 0;
333  }
334
335  /// getRootNode - This returns the entry node for the CFG of the function.  If
336  /// this tree represents the post-dominance relations for a function, however,
337  /// this root may be a node with the block == NULL.  This is the case when
338  /// there are multiple exit nodes from a particular function.  Consumers of
339  /// post-dominance information must be capable of dealing with this
340  /// possibility.
341  ///
342  DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
343  const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
344
345  /// properlyDominates - Returns true iff this dominates N and this != N.
346  /// Note that this is not a constant time operation!
347  ///
348  bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
349                         const DomTreeNodeBase<NodeT> *B) const {
350    if (A == 0 || B == 0) return false;
351    return dominatedBySlowTreeWalk(A, B);
352  }
353
354  inline bool properlyDominates(const NodeT *A, const NodeT *B) {
355    if (A == B)
356      return false;
357
358    // Cast away the const qualifiers here. This is ok since
359    // this function doesn't actually return the values returned
360    // from getNode.
361    return properlyDominates(getNode(const_cast<NodeT *>(A)),
362                             getNode(const_cast<NodeT *>(B)));
363  }
364
365  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
366                               const DomTreeNodeBase<NodeT> *B) const {
367    const DomTreeNodeBase<NodeT> *IDom;
368    if (A == 0 || B == 0) return false;
369    while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
370      B = IDom;   // Walk up the tree
371    return IDom != 0;
372  }
373
374
375  /// isReachableFromEntry - Return true if A is dominated by the entry
376  /// block of the function containing it.
377  bool isReachableFromEntry(const NodeT* A) {
378    assert(!this->isPostDominator() &&
379           "This is not implemented for post dominators");
380    return dominates(&A->getParent()->front(), A);
381  }
382
383  /// dominates - Returns true iff A dominates B.  Note that this is not a
384  /// constant time operation!
385  ///
386  inline bool dominates(const DomTreeNodeBase<NodeT> *A,
387                        const DomTreeNodeBase<NodeT> *B) {
388    if (B == A)
389      return true;  // A node trivially dominates itself.
390
391    if (A == 0 || B == 0)
392      return false;
393
394    // Compare the result of the tree walk and the dfs numbers, if expensive
395    // checks are enabled.
396#ifdef XDEBUG
397    assert((!DFSInfoValid ||
398            (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
399           "Tree walk disagrees with dfs numbers!");
400#endif
401
402    if (DFSInfoValid)
403      return B->DominatedBy(A);
404
405    // If we end up with too many slow queries, just update the
406    // DFS numbers on the theory that we are going to keep querying.
407    SlowQueries++;
408    if (SlowQueries > 32) {
409      updateDFSNumbers();
410      return B->DominatedBy(A);
411    }
412
413    return dominatedBySlowTreeWalk(A, B);
414  }
415
416  inline bool dominates(const NodeT *A, const NodeT *B) {
417    if (A == B)
418      return true;
419
420    // Cast away the const qualifiers here. This is ok since
421    // this function doesn't actually return the values returned
422    // from getNode.
423    return dominates(getNode(const_cast<NodeT *>(A)),
424                     getNode(const_cast<NodeT *>(B)));
425  }
426
427  NodeT *getRoot() const {
428    assert(this->Roots.size() == 1 && "Should always have entry node!");
429    return this->Roots[0];
430  }
431
432  /// findNearestCommonDominator - Find nearest common dominator basic block
433  /// for basic block A and B. If there is no such block then return NULL.
434  NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
435    assert(A->getParent() == B->getParent() &&
436           "Two blocks are not in same function");
437
438    // If either A or B is a entry block then it is nearest common dominator
439    // (for forward-dominators).
440    if (!this->isPostDominator()) {
441      NodeT &Entry = A->getParent()->front();
442      if (A == &Entry || B == &Entry)
443        return &Entry;
444    }
445
446    // If B dominates A then B is nearest common dominator.
447    if (dominates(B, A))
448      return B;
449
450    // If A dominates B then A is nearest common dominator.
451    if (dominates(A, B))
452      return A;
453
454    DomTreeNodeBase<NodeT> *NodeA = getNode(A);
455    DomTreeNodeBase<NodeT> *NodeB = getNode(B);
456
457    // Collect NodeA dominators set.
458    SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
459    NodeADoms.insert(NodeA);
460    DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
461    while (IDomA) {
462      NodeADoms.insert(IDomA);
463      IDomA = IDomA->getIDom();
464    }
465
466    // Walk NodeB immediate dominators chain and find common dominator node.
467    DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
468    while (IDomB) {
469      if (NodeADoms.count(IDomB) != 0)
470        return IDomB->getBlock();
471
472      IDomB = IDomB->getIDom();
473    }
474
475    return NULL;
476  }
477
478  const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
479    // Cast away the const qualifiers here. This is ok since
480    // const is re-introduced on the return type.
481    return findNearestCommonDominator(const_cast<NodeT *>(A),
482                                      const_cast<NodeT *>(B));
483  }
484
485  //===--------------------------------------------------------------------===//
486  // API to update (Post)DominatorTree information based on modifications to
487  // the CFG...
488
489  /// addNewBlock - Add a new node to the dominator tree information.  This
490  /// creates a new node as a child of DomBB dominator node,linking it into
491  /// the children list of the immediate dominator.
492  DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
493    assert(getNode(BB) == 0 && "Block already in dominator tree!");
494    DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
495    assert(IDomNode && "Not immediate dominator specified for block!");
496    DFSInfoValid = false;
497    return DomTreeNodes[BB] =
498      IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
499  }
500
501  /// changeImmediateDominator - This method is used to update the dominator
502  /// tree information when a node's immediate dominator changes.
503  ///
504  void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
505                                DomTreeNodeBase<NodeT> *NewIDom) {
506    assert(N && NewIDom && "Cannot change null node pointers!");
507    DFSInfoValid = false;
508    N->setIDom(NewIDom);
509  }
510
511  void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
512    changeImmediateDominator(getNode(BB), getNode(NewBB));
513  }
514
515  /// eraseNode - Removes a node from the dominator tree. Block must not
516  /// dominate any other blocks. Removes node from its immediate dominator's
517  /// children list. Deletes dominator node associated with basic block BB.
518  void eraseNode(NodeT *BB) {
519    DomTreeNodeBase<NodeT> *Node = getNode(BB);
520    assert(Node && "Removing node that isn't in dominator tree.");
521    assert(Node->getChildren().empty() && "Node is not a leaf node.");
522
523      // Remove node from immediate dominator's children list.
524    DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
525    if (IDom) {
526      typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
527        std::find(IDom->Children.begin(), IDom->Children.end(), Node);
528      assert(I != IDom->Children.end() &&
529             "Not in immediate dominator children set!");
530      // I am no longer your child...
531      IDom->Children.erase(I);
532    }
533
534    DomTreeNodes.erase(BB);
535    delete Node;
536  }
537
538  /// removeNode - Removes a node from the dominator tree.  Block must not
539  /// dominate any other blocks.  Invalidates any node pointing to removed
540  /// block.
541  void removeNode(NodeT *BB) {
542    assert(getNode(BB) && "Removing node that isn't in dominator tree.");
543    DomTreeNodes.erase(BB);
544  }
545
546  /// splitBlock - BB is split and now it has one successor. Update dominator
547  /// tree to reflect this change.
548  void splitBlock(NodeT* NewBB) {
549    if (this->IsPostDominators)
550      this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
551    else
552      this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
553  }
554
555  /// print - Convert to human readable form
556  ///
557  void print(raw_ostream &o) const {
558    o << "=============================--------------------------------\n";
559    if (this->isPostDominator())
560      o << "Inorder PostDominator Tree: ";
561    else
562      o << "Inorder Dominator Tree: ";
563    if (!this->DFSInfoValid)
564      o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
565    o << "\n";
566
567    // The postdom tree can have a null root if there are no returns.
568    if (getRootNode())
569      PrintDomTree<NodeT>(getRootNode(), o, 1);
570  }
571
572protected:
573  template<class GraphT>
574  friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
575                       typename GraphT::NodeType* VIn);
576
577  template<class GraphT>
578  friend typename GraphT::NodeType* Eval(
579                               DominatorTreeBase<typename GraphT::NodeType>& DT,
580                                         typename GraphT::NodeType* V);
581
582  template<class GraphT>
583  friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
584                   unsigned DFSNumV, typename GraphT::NodeType* W,
585         typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
586
587  template<class GraphT>
588  friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
589                          typename GraphT::NodeType* V,
590                          unsigned N);
591
592  template<class FuncT, class N>
593  friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
594                        FuncT& F);
595
596  /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
597  /// dominator tree in dfs order.
598  void updateDFSNumbers() {
599    unsigned DFSNum = 0;
600
601    SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
602                typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
603
604    DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
605
606    if (!ThisRoot)
607      return;
608
609    // Even in the case of multiple exits that form the post dominator root
610    // nodes, do not iterate over all exits, but start from the virtual root
611    // node. Otherwise bbs, that are not post dominated by any exit but by the
612    // virtual root node, will never be assigned a DFS number.
613    WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
614    ThisRoot->DFSNumIn = DFSNum++;
615
616    while (!WorkStack.empty()) {
617      DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
618      typename DomTreeNodeBase<NodeT>::iterator ChildIt =
619        WorkStack.back().second;
620
621      // If we visited all of the children of this node, "recurse" back up the
622      // stack setting the DFOutNum.
623      if (ChildIt == Node->end()) {
624        Node->DFSNumOut = DFSNum++;
625        WorkStack.pop_back();
626      } else {
627        // Otherwise, recursively visit this child.
628        DomTreeNodeBase<NodeT> *Child = *ChildIt;
629        ++WorkStack.back().second;
630
631        WorkStack.push_back(std::make_pair(Child, Child->begin()));
632        Child->DFSNumIn = DFSNum++;
633      }
634    }
635
636    SlowQueries = 0;
637    DFSInfoValid = true;
638  }
639
640  DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
641    typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
642    if (I != this->DomTreeNodes.end() && I->second)
643      return I->second;
644
645    // Haven't calculated this node yet?  Get or calculate the node for the
646    // immediate dominator.
647    NodeT *IDom = getIDom(BB);
648
649    assert(IDom || this->DomTreeNodes[NULL]);
650    DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
651
652    // Add a new tree node for this BasicBlock, and link it as a child of
653    // IDomNode
654    DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
655    return this->DomTreeNodes[BB] = IDomNode->addChild(C);
656  }
657
658  inline NodeT *getIDom(NodeT *BB) const {
659    typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
660    return I != IDoms.end() ? I->second : 0;
661  }
662
663  inline void addRoot(NodeT* BB) {
664    this->Roots.push_back(BB);
665  }
666
667public:
668  /// recalculate - compute a dominator tree for the given function
669  template<class FT>
670  void recalculate(FT& F) {
671    reset();
672    this->Vertex.push_back(0);
673
674    if (!this->IsPostDominators) {
675      // Initialize root
676      this->Roots.push_back(&F.front());
677      this->IDoms[&F.front()] = 0;
678      this->DomTreeNodes[&F.front()] = 0;
679
680      Calculate<FT, NodeT*>(*this, F);
681    } else {
682      // Initialize the roots list
683      for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
684        if (std::distance(GraphTraits<FT*>::child_begin(I),
685                          GraphTraits<FT*>::child_end(I)) == 0)
686          addRoot(I);
687
688        // Prepopulate maps so that we don't get iterator invalidation issues later.
689        this->IDoms[I] = 0;
690        this->DomTreeNodes[I] = 0;
691      }
692
693      Calculate<FT, Inverse<NodeT*> >(*this, F);
694    }
695  }
696};
697
698EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
699
700//===-------------------------------------
701/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
702/// compute a normal dominator tree.
703///
704class DominatorTree : public FunctionPass {
705public:
706  static char ID; // Pass ID, replacement for typeid
707  DominatorTreeBase<BasicBlock>* DT;
708
709  DominatorTree() : FunctionPass(ID) {
710    initializeDominatorTreePass(*PassRegistry::getPassRegistry());
711    DT = new DominatorTreeBase<BasicBlock>(false);
712  }
713
714  ~DominatorTree() {
715    delete DT;
716  }
717
718  DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
719
720  /// getRoots - Return the root blocks of the current CFG.  This may include
721  /// multiple blocks if we are computing post dominators.  For forward
722  /// dominators, this will always be a single block (the entry node).
723  ///
724  inline const std::vector<BasicBlock*> &getRoots() const {
725    return DT->getRoots();
726  }
727
728  inline BasicBlock *getRoot() const {
729    return DT->getRoot();
730  }
731
732  inline DomTreeNode *getRootNode() const {
733    return DT->getRootNode();
734  }
735
736  /// compare - Return false if the other dominator tree matches this
737  /// dominator tree. Otherwise return true.
738  inline bool compare(DominatorTree &Other) const {
739    DomTreeNode *R = getRootNode();
740    DomTreeNode *OtherR = Other.getRootNode();
741
742    if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
743      return true;
744
745    if (DT->compare(Other.getBase()))
746      return true;
747
748    return false;
749  }
750
751  virtual bool runOnFunction(Function &F);
752
753  virtual void verifyAnalysis() const;
754
755  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
756    AU.setPreservesAll();
757  }
758
759  inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
760    return DT->dominates(A, B);
761  }
762
763  inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
764    return DT->dominates(A, B);
765  }
766
767  // dominates - Return true if A dominates B. This performs the
768  // special checks necessary if A and B are in the same basic block.
769  bool dominates(const Instruction *A, const Instruction *B) const;
770
771  bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
772    return DT->properlyDominates(A, B);
773  }
774
775  bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
776    return DT->properlyDominates(A, B);
777  }
778
779  /// findNearestCommonDominator - Find nearest common dominator basic block
780  /// for basic block A and B. If there is no such block then return NULL.
781  inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
782    return DT->findNearestCommonDominator(A, B);
783  }
784
785  inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
786                                                      const BasicBlock *B) {
787    return DT->findNearestCommonDominator(A, B);
788  }
789
790  inline DomTreeNode *operator[](BasicBlock *BB) const {
791    return DT->getNode(BB);
792  }
793
794  /// getNode - return the (Post)DominatorTree node for the specified basic
795  /// block.  This is the same as using operator[] on this class.
796  ///
797  inline DomTreeNode *getNode(BasicBlock *BB) const {
798    return DT->getNode(BB);
799  }
800
801  /// addNewBlock - Add a new node to the dominator tree information.  This
802  /// creates a new node as a child of DomBB dominator node,linking it into
803  /// the children list of the immediate dominator.
804  inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
805    return DT->addNewBlock(BB, DomBB);
806  }
807
808  /// changeImmediateDominator - This method is used to update the dominator
809  /// tree information when a node's immediate dominator changes.
810  ///
811  inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
812    DT->changeImmediateDominator(N, NewIDom);
813  }
814
815  inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
816    DT->changeImmediateDominator(N, NewIDom);
817  }
818
819  /// eraseNode - Removes a node from the dominator tree. Block must not
820  /// dominate any other blocks. Removes node from its immediate dominator's
821  /// children list. Deletes dominator node associated with basic block BB.
822  inline void eraseNode(BasicBlock *BB) {
823    DT->eraseNode(BB);
824  }
825
826  /// splitBlock - BB is split and now it has one successor. Update dominator
827  /// tree to reflect this change.
828  inline void splitBlock(BasicBlock* NewBB) {
829    DT->splitBlock(NewBB);
830  }
831
832  bool isReachableFromEntry(const BasicBlock* A) {
833    return DT->isReachableFromEntry(A);
834  }
835
836
837  virtual void releaseMemory() {
838    DT->releaseMemory();
839  }
840
841  virtual void print(raw_ostream &OS, const Module* M= 0) const;
842};
843
844//===-------------------------------------
845/// DominatorTree GraphTraits specialization so the DominatorTree can be
846/// iterable by generic graph iterators.
847///
848template <> struct GraphTraits<DomTreeNode*> {
849  typedef DomTreeNode NodeType;
850  typedef NodeType::iterator  ChildIteratorType;
851
852  static NodeType *getEntryNode(NodeType *N) {
853    return N;
854  }
855  static inline ChildIteratorType child_begin(NodeType *N) {
856    return N->begin();
857  }
858  static inline ChildIteratorType child_end(NodeType *N) {
859    return N->end();
860  }
861
862  typedef df_iterator<DomTreeNode*> nodes_iterator;
863
864  static nodes_iterator nodes_begin(DomTreeNode *N) {
865    return df_begin(getEntryNode(N));
866  }
867
868  static nodes_iterator nodes_end(DomTreeNode *N) {
869    return df_end(getEntryNode(N));
870  }
871};
872
873template <> struct GraphTraits<DominatorTree*>
874  : public GraphTraits<DomTreeNode*> {
875  static NodeType *getEntryNode(DominatorTree *DT) {
876    return DT->getRootNode();
877  }
878
879  static nodes_iterator nodes_begin(DominatorTree *N) {
880    return df_begin(getEntryNode(N));
881  }
882
883  static nodes_iterator nodes_end(DominatorTree *N) {
884    return df_end(getEntryNode(N));
885  }
886};
887
888
889} // End llvm namespace
890
891#endif
892