Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

920 lines
30 KiB

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