GenericDomTree.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. ///
  15. /// This file defines a set of templates that efficiently compute a dominator
  16. /// tree over a generic graph. This is used typically in LLVM for fast
  17. /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
  18. /// graph types.
  19. ///
  20. /// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
  21. /// on the graph's NodeRef. The NodeRef should be a pointer and,
  22. /// either NodeRef->getParent() must return the parent node that is also a
  23. /// pointer or DomTreeNodeTraits needs to be specialized.
  24. ///
  25. /// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
  26. ///
  27. //===----------------------------------------------------------------------===//
  28. #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
  29. #define LLVM_SUPPORT_GENERICDOMTREE_H
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/GraphTraits.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/Support/CFGDiff.h"
  36. #include "llvm/Support/CFGUpdate.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <algorithm>
  39. #include <cassert>
  40. #include <cstddef>
  41. #include <iterator>
  42. #include <memory>
  43. #include <type_traits>
  44. #include <utility>
  45. namespace llvm {
  46. template <typename NodeT, bool IsPostDom>
  47. class DominatorTreeBase;
  48. namespace DomTreeBuilder {
  49. template <typename DomTreeT>
  50. struct SemiNCAInfo;
  51. } // namespace DomTreeBuilder
  52. /// Base class for the actual dominator tree node.
  53. template <class NodeT> class DomTreeNodeBase {
  54. friend class PostDominatorTree;
  55. friend class DominatorTreeBase<NodeT, false>;
  56. friend class DominatorTreeBase<NodeT, true>;
  57. friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, false>>;
  58. friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, true>>;
  59. NodeT *TheBB;
  60. DomTreeNodeBase *IDom;
  61. unsigned Level;
  62. SmallVector<DomTreeNodeBase *, 4> Children;
  63. mutable unsigned DFSNumIn = ~0;
  64. mutable unsigned DFSNumOut = ~0;
  65. public:
  66. DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
  67. : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
  68. using iterator = typename SmallVector<DomTreeNodeBase *, 4>::iterator;
  69. using const_iterator =
  70. typename SmallVector<DomTreeNodeBase *, 4>::const_iterator;
  71. iterator begin() { return Children.begin(); }
  72. iterator end() { return Children.end(); }
  73. const_iterator begin() const { return Children.begin(); }
  74. const_iterator end() const { return Children.end(); }
  75. DomTreeNodeBase *const &back() const { return Children.back(); }
  76. DomTreeNodeBase *&back() { return Children.back(); }
  77. iterator_range<iterator> children() { return make_range(begin(), end()); }
  78. iterator_range<const_iterator> children() const {
  79. return make_range(begin(), end());
  80. }
  81. NodeT *getBlock() const { return TheBB; }
  82. DomTreeNodeBase *getIDom() const { return IDom; }
  83. unsigned getLevel() const { return Level; }
  84. std::unique_ptr<DomTreeNodeBase> addChild(
  85. std::unique_ptr<DomTreeNodeBase> C) {
  86. Children.push_back(C.get());
  87. return C;
  88. }
  89. bool isLeaf() const { return Children.empty(); }
  90. size_t getNumChildren() const { return Children.size(); }
  91. void clearAllChildren() { Children.clear(); }
  92. bool compare(const DomTreeNodeBase *Other) const {
  93. if (getNumChildren() != Other->getNumChildren())
  94. return true;
  95. if (Level != Other->Level) return true;
  96. SmallPtrSet<const NodeT *, 4> OtherChildren;
  97. for (const DomTreeNodeBase *I : *Other) {
  98. const NodeT *Nd = I->getBlock();
  99. OtherChildren.insert(Nd);
  100. }
  101. for (const DomTreeNodeBase *I : *this) {
  102. const NodeT *N = I->getBlock();
  103. if (OtherChildren.count(N) == 0)
  104. return true;
  105. }
  106. return false;
  107. }
  108. void setIDom(DomTreeNodeBase *NewIDom) {
  109. assert(IDom && "No immediate dominator?");
  110. if (IDom == NewIDom) return;
  111. auto I = find(IDom->Children, this);
  112. assert(I != IDom->Children.end() &&
  113. "Not in immediate dominator children set!");
  114. // I am no longer your child...
  115. IDom->Children.erase(I);
  116. // Switch to new dominator
  117. IDom = NewIDom;
  118. IDom->Children.push_back(this);
  119. UpdateLevel();
  120. }
  121. /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
  122. /// in the dominator tree. They are only guaranteed valid if
  123. /// updateDFSNumbers() has been called.
  124. unsigned getDFSNumIn() const { return DFSNumIn; }
  125. unsigned getDFSNumOut() const { return DFSNumOut; }
  126. private:
  127. // Return true if this node is dominated by other. Use this only if DFS info
  128. // is valid.
  129. bool DominatedBy(const DomTreeNodeBase *other) const {
  130. return this->DFSNumIn >= other->DFSNumIn &&
  131. this->DFSNumOut <= other->DFSNumOut;
  132. }
  133. void UpdateLevel() {
  134. assert(IDom);
  135. if (Level == IDom->Level + 1) return;
  136. SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
  137. while (!WorkStack.empty()) {
  138. DomTreeNodeBase *Current = WorkStack.pop_back_val();
  139. Current->Level = Current->IDom->Level + 1;
  140. for (DomTreeNodeBase *C : *Current) {
  141. assert(C->IDom);
  142. if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
  143. }
  144. }
  145. }
  146. };
  147. template <class NodeT>
  148. raw_ostream &operator<<(raw_ostream &O, const DomTreeNodeBase<NodeT> *Node) {
  149. if (Node->getBlock())
  150. Node->getBlock()->printAsOperand(O, false);
  151. else
  152. O << " <<exit node>>";
  153. O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
  154. << Node->getLevel() << "]\n";
  155. return O;
  156. }
  157. template <class NodeT>
  158. void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &O,
  159. unsigned Lev) {
  160. O.indent(2 * Lev) << "[" << Lev << "] " << N;
  161. for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
  162. E = N->end();
  163. I != E; ++I)
  164. PrintDomTree<NodeT>(*I, O, Lev + 1);
  165. }
  166. namespace DomTreeBuilder {
  167. // The routines below are provided in a separate header but referenced here.
  168. template <typename DomTreeT>
  169. void Calculate(DomTreeT &DT);
  170. template <typename DomTreeT>
  171. void CalculateWithUpdates(DomTreeT &DT,
  172. ArrayRef<typename DomTreeT::UpdateType> Updates);
  173. template <typename DomTreeT>
  174. void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  175. typename DomTreeT::NodePtr To);
  176. template <typename DomTreeT>
  177. void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  178. typename DomTreeT::NodePtr To);
  179. template <typename DomTreeT>
  180. void ApplyUpdates(DomTreeT &DT,
  181. GraphDiff<typename DomTreeT::NodePtr,
  182. DomTreeT::IsPostDominator> &PreViewCFG,
  183. GraphDiff<typename DomTreeT::NodePtr,
  184. DomTreeT::IsPostDominator> *PostViewCFG);
  185. template <typename DomTreeT>
  186. bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
  187. } // namespace DomTreeBuilder
  188. /// Default DomTreeNode traits for NodeT. The default implementation assume a
  189. /// Function-like NodeT. Can be specialized to support different node types.
  190. template <typename NodeT> struct DomTreeNodeTraits {
  191. using NodeType = NodeT;
  192. using NodePtr = NodeT *;
  193. using ParentPtr = decltype(std::declval<NodePtr>()->getParent());
  194. static_assert(std::is_pointer<ParentPtr>::value,
  195. "Currently NodeT's parent must be a pointer type");
  196. using ParentType = std::remove_pointer_t<ParentPtr>;
  197. static NodeT *getEntryNode(ParentPtr Parent) { return &Parent->front(); }
  198. static ParentPtr getParent(NodePtr BB) { return BB->getParent(); }
  199. };
  200. /// Core dominator tree base class.
  201. ///
  202. /// This class is a generic template over graph nodes. It is instantiated for
  203. /// various graphs in the LLVM IR or in the code generator.
  204. template <typename NodeT, bool IsPostDom>
  205. class DominatorTreeBase {
  206. public:
  207. static_assert(std::is_pointer<typename GraphTraits<NodeT *>::NodeRef>::value,
  208. "Currently DominatorTreeBase supports only pointer nodes");
  209. using NodeTrait = DomTreeNodeTraits<NodeT>;
  210. using NodeType = typename NodeTrait::NodeType;
  211. using NodePtr = typename NodeTrait::NodePtr;
  212. using ParentPtr = typename NodeTrait::ParentPtr;
  213. static_assert(std::is_pointer<ParentPtr>::value,
  214. "Currently NodeT's parent must be a pointer type");
  215. using ParentType = std::remove_pointer_t<ParentPtr>;
  216. static constexpr bool IsPostDominator = IsPostDom;
  217. using UpdateType = cfg::Update<NodePtr>;
  218. using UpdateKind = cfg::UpdateKind;
  219. static constexpr UpdateKind Insert = UpdateKind::Insert;
  220. static constexpr UpdateKind Delete = UpdateKind::Delete;
  221. enum class VerificationLevel { Fast, Basic, Full };
  222. protected:
  223. // Dominators always have a single root, postdominators can have more.
  224. SmallVector<NodeT *, IsPostDom ? 4 : 1> Roots;
  225. using DomTreeNodeMapType =
  226. DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>;
  227. DomTreeNodeMapType DomTreeNodes;
  228. DomTreeNodeBase<NodeT> *RootNode = nullptr;
  229. ParentPtr Parent = nullptr;
  230. mutable bool DFSInfoValid = false;
  231. mutable unsigned int SlowQueries = 0;
  232. friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase>;
  233. public:
  234. DominatorTreeBase() = default;
  235. DominatorTreeBase(DominatorTreeBase &&Arg)
  236. : Roots(std::move(Arg.Roots)),
  237. DomTreeNodes(std::move(Arg.DomTreeNodes)),
  238. RootNode(Arg.RootNode),
  239. Parent(Arg.Parent),
  240. DFSInfoValid(Arg.DFSInfoValid),
  241. SlowQueries(Arg.SlowQueries) {
  242. Arg.wipe();
  243. }
  244. DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
  245. Roots = std::move(RHS.Roots);
  246. DomTreeNodes = std::move(RHS.DomTreeNodes);
  247. RootNode = RHS.RootNode;
  248. Parent = RHS.Parent;
  249. DFSInfoValid = RHS.DFSInfoValid;
  250. SlowQueries = RHS.SlowQueries;
  251. RHS.wipe();
  252. return *this;
  253. }
  254. DominatorTreeBase(const DominatorTreeBase &) = delete;
  255. DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
  256. /// Iteration over roots.
  257. ///
  258. /// This may include multiple blocks if we are computing post dominators.
  259. /// For forward dominators, this will always be a single block (the entry
  260. /// block).
  261. using root_iterator = typename SmallVectorImpl<NodeT *>::iterator;
  262. using const_root_iterator = typename SmallVectorImpl<NodeT *>::const_iterator;
  263. root_iterator root_begin() { return Roots.begin(); }
  264. const_root_iterator root_begin() const { return Roots.begin(); }
  265. root_iterator root_end() { return Roots.end(); }
  266. const_root_iterator root_end() const { return Roots.end(); }
  267. size_t root_size() const { return Roots.size(); }
  268. iterator_range<root_iterator> roots() {
  269. return make_range(root_begin(), root_end());
  270. }
  271. iterator_range<const_root_iterator> roots() const {
  272. return make_range(root_begin(), root_end());
  273. }
  274. /// isPostDominator - Returns true if analysis based of postdoms
  275. ///
  276. bool isPostDominator() const { return IsPostDominator; }
  277. /// compare - Return false if the other dominator tree base matches this
  278. /// dominator tree base. Otherwise return true.
  279. bool compare(const DominatorTreeBase &Other) const {
  280. if (Parent != Other.Parent) return true;
  281. if (Roots.size() != Other.Roots.size())
  282. return true;
  283. if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin()))
  284. return true;
  285. const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
  286. if (DomTreeNodes.size() != OtherDomTreeNodes.size())
  287. return true;
  288. for (const auto &DomTreeNode : DomTreeNodes) {
  289. NodeT *BB = DomTreeNode.first;
  290. typename DomTreeNodeMapType::const_iterator OI =
  291. OtherDomTreeNodes.find(BB);
  292. if (OI == OtherDomTreeNodes.end())
  293. return true;
  294. DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second;
  295. DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
  296. if (MyNd.compare(&OtherNd))
  297. return true;
  298. }
  299. return false;
  300. }
  301. /// getNode - return the (Post)DominatorTree node for the specified basic
  302. /// block. This is the same as using operator[] on this class. The result
  303. /// may (but is not required to) be null for a forward (backwards)
  304. /// statically unreachable block.
  305. DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
  306. auto I = DomTreeNodes.find(BB);
  307. if (I != DomTreeNodes.end())
  308. return I->second.get();
  309. return nullptr;
  310. }
  311. /// See getNode.
  312. DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
  313. return getNode(BB);
  314. }
  315. /// getRootNode - This returns the entry node for the CFG of the function. If
  316. /// this tree represents the post-dominance relations for a function, however,
  317. /// this root may be a node with the block == NULL. This is the case when
  318. /// there are multiple exit nodes from a particular function. Consumers of
  319. /// post-dominance information must be capable of dealing with this
  320. /// possibility.
  321. ///
  322. DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
  323. const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
  324. /// Get all nodes dominated by R, including R itself.
  325. void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
  326. Result.clear();
  327. const DomTreeNodeBase<NodeT> *RN = getNode(R);
  328. if (!RN)
  329. return; // If R is unreachable, it will not be present in the DOM tree.
  330. SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
  331. WL.push_back(RN);
  332. while (!WL.empty()) {
  333. const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
  334. Result.push_back(N->getBlock());
  335. WL.append(N->begin(), N->end());
  336. }
  337. }
  338. /// properlyDominates - Returns true iff A dominates B and A != B.
  339. /// Note that this is not a constant time operation!
  340. ///
  341. bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
  342. const DomTreeNodeBase<NodeT> *B) const {
  343. if (!A || !B)
  344. return false;
  345. if (A == B)
  346. return false;
  347. return dominates(A, B);
  348. }
  349. bool properlyDominates(const NodeT *A, const NodeT *B) const;
  350. /// isReachableFromEntry - Return true if A is dominated by the entry
  351. /// block of the function containing it.
  352. bool isReachableFromEntry(const NodeT *A) const {
  353. assert(!this->isPostDominator() &&
  354. "This is not implemented for post dominators");
  355. return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
  356. }
  357. bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
  358. /// dominates - Returns true iff A dominates B. Note that this is not a
  359. /// constant time operation!
  360. ///
  361. bool dominates(const DomTreeNodeBase<NodeT> *A,
  362. const DomTreeNodeBase<NodeT> *B) const {
  363. // A node trivially dominates itself.
  364. if (B == A)
  365. return true;
  366. // An unreachable node is dominated by anything.
  367. if (!isReachableFromEntry(B))
  368. return true;
  369. // And dominates nothing.
  370. if (!isReachableFromEntry(A))
  371. return false;
  372. if (B->getIDom() == A) return true;
  373. if (A->getIDom() == B) return false;
  374. // A can only dominate B if it is higher in the tree.
  375. if (A->getLevel() >= B->getLevel()) return false;
  376. // Compare the result of the tree walk and the dfs numbers, if expensive
  377. // checks are enabled.
  378. #ifdef EXPENSIVE_CHECKS
  379. assert((!DFSInfoValid ||
  380. (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
  381. "Tree walk disagrees with dfs numbers!");
  382. #endif
  383. if (DFSInfoValid)
  384. return B->DominatedBy(A);
  385. // If we end up with too many slow queries, just update the
  386. // DFS numbers on the theory that we are going to keep querying.
  387. SlowQueries++;
  388. if (SlowQueries > 32) {
  389. updateDFSNumbers();
  390. return B->DominatedBy(A);
  391. }
  392. return dominatedBySlowTreeWalk(A, B);
  393. }
  394. bool dominates(const NodeT *A, const NodeT *B) const;
  395. NodeT *getRoot() const {
  396. assert(this->Roots.size() == 1 && "Should always have entry node!");
  397. return this->Roots[0];
  398. }
  399. /// Find nearest common dominator basic block for basic block A and B. A and B
  400. /// must have tree nodes.
  401. NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
  402. assert(A && B && "Pointers are not valid");
  403. assert(NodeTrait::getParent(A) == NodeTrait::getParent(B) &&
  404. "Two blocks are not in same function");
  405. // If either A or B is a entry block then it is nearest common dominator
  406. // (for forward-dominators).
  407. if (!isPostDominator()) {
  408. NodeT &Entry =
  409. *DomTreeNodeTraits<NodeT>::getEntryNode(NodeTrait::getParent(A));
  410. if (A == &Entry || B == &Entry)
  411. return &Entry;
  412. }
  413. DomTreeNodeBase<NodeT> *NodeA = getNode(A);
  414. DomTreeNodeBase<NodeT> *NodeB = getNode(B);
  415. assert(NodeA && "A must be in the tree");
  416. assert(NodeB && "B must be in the tree");
  417. // Use level information to go up the tree until the levels match. Then
  418. // continue going up til we arrive at the same node.
  419. while (NodeA != NodeB) {
  420. if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
  421. NodeA = NodeA->IDom;
  422. }
  423. return NodeA->getBlock();
  424. }
  425. const NodeT *findNearestCommonDominator(const NodeT *A,
  426. const NodeT *B) const {
  427. // Cast away the const qualifiers here. This is ok since
  428. // const is re-introduced on the return type.
  429. return findNearestCommonDominator(const_cast<NodeT *>(A),
  430. const_cast<NodeT *>(B));
  431. }
  432. bool isVirtualRoot(const DomTreeNodeBase<NodeT> *A) const {
  433. return isPostDominator() && !A->getBlock();
  434. }
  435. //===--------------------------------------------------------------------===//
  436. // API to update (Post)DominatorTree information based on modifications to
  437. // the CFG...
  438. /// Inform the dominator tree about a sequence of CFG edge insertions and
  439. /// deletions and perform a batch update on the tree.
  440. ///
  441. /// This function should be used when there were multiple CFG updates after
  442. /// the last dominator tree update. It takes care of performing the updates
  443. /// in sync with the CFG and optimizes away the redundant operations that
  444. /// cancel each other.
  445. /// The functions expects the sequence of updates to be balanced. Eg.:
  446. /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
  447. /// logically it results in a single insertions.
  448. /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
  449. /// sense to insert the same edge twice.
  450. ///
  451. /// What's more, the functions assumes that it's safe to ask every node in the
  452. /// CFG about its children and inverse children. This implies that deletions
  453. /// of CFG edges must not delete the CFG nodes before calling this function.
  454. ///
  455. /// The applyUpdates function can reorder the updates and remove redundant
  456. /// ones internally (as long as it is done in a deterministic fashion). The
  457. /// batch updater is also able to detect sequences of zero and exactly one
  458. /// update -- it's optimized to do less work in these cases.
  459. ///
  460. /// Note that for postdominators it automatically takes care of applying
  461. /// updates on reverse edges internally (so there's no need to swap the
  462. /// From and To pointers when constructing DominatorTree::UpdateType).
  463. /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
  464. /// with the same template parameter T.
  465. ///
  466. /// \param Updates An ordered sequence of updates to perform. The current CFG
  467. /// and the reverse of these updates provides the pre-view of the CFG.
  468. ///
  469. void applyUpdates(ArrayRef<UpdateType> Updates) {
  470. GraphDiff<NodePtr, IsPostDominator> PreViewCFG(
  471. Updates, /*ReverseApplyUpdates=*/true);
  472. DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr);
  473. }
  474. /// \param Updates An ordered sequence of updates to perform. The current CFG
  475. /// and the reverse of these updates provides the pre-view of the CFG.
  476. /// \param PostViewUpdates An ordered sequence of update to perform in order
  477. /// to obtain a post-view of the CFG. The DT will be updated assuming the
  478. /// obtained PostViewCFG is the desired end state.
  479. void applyUpdates(ArrayRef<UpdateType> Updates,
  480. ArrayRef<UpdateType> PostViewUpdates) {
  481. if (Updates.empty()) {
  482. GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
  483. DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG);
  484. } else {
  485. // PreViewCFG needs to merge Updates and PostViewCFG. The updates in
  486. // Updates need to be reversed, and match the direction in PostViewCFG.
  487. // The PostViewCFG is created with updates reversed (equivalent to changes
  488. // made to the CFG), so the PreViewCFG needs all the updates reverse
  489. // applied.
  490. SmallVector<UpdateType> AllUpdates(Updates.begin(), Updates.end());
  491. append_range(AllUpdates, PostViewUpdates);
  492. GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates,
  493. /*ReverseApplyUpdates=*/true);
  494. GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
  495. DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG);
  496. }
  497. }
  498. /// Inform the dominator tree about a CFG edge insertion and update the tree.
  499. ///
  500. /// This function has to be called just before or just after making the update
  501. /// on the actual CFG. There cannot be any other updates that the dominator
  502. /// tree doesn't know about.
  503. ///
  504. /// Note that for postdominators it automatically takes care of inserting
  505. /// a reverse edge internally (so there's no need to swap the parameters).
  506. ///
  507. void insertEdge(NodeT *From, NodeT *To) {
  508. assert(From);
  509. assert(To);
  510. assert(NodeTrait::getParent(From) == Parent);
  511. assert(NodeTrait::getParent(To) == Parent);
  512. DomTreeBuilder::InsertEdge(*this, From, To);
  513. }
  514. /// Inform the dominator tree about a CFG edge deletion and update the tree.
  515. ///
  516. /// This function has to be called just after making the update on the actual
  517. /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
  518. /// DEBUG mode. There cannot be any other updates that the
  519. /// dominator tree doesn't know about.
  520. ///
  521. /// Note that for postdominators it automatically takes care of deleting
  522. /// a reverse edge internally (so there's no need to swap the parameters).
  523. ///
  524. void deleteEdge(NodeT *From, NodeT *To) {
  525. assert(From);
  526. assert(To);
  527. assert(NodeTrait::getParent(From) == Parent);
  528. assert(NodeTrait::getParent(To) == Parent);
  529. DomTreeBuilder::DeleteEdge(*this, From, To);
  530. }
  531. /// Add a new node to the dominator tree information.
  532. ///
  533. /// This creates a new node as a child of DomBB dominator node, linking it
  534. /// into the children list of the immediate dominator.
  535. ///
  536. /// \param BB New node in CFG.
  537. /// \param DomBB CFG node that is dominator for BB.
  538. /// \returns New dominator tree node that represents new CFG node.
  539. ///
  540. DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
  541. assert(getNode(BB) == nullptr && "Block already in dominator tree!");
  542. DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
  543. assert(IDomNode && "Not immediate dominator specified for block!");
  544. DFSInfoValid = false;
  545. return createChild(BB, IDomNode);
  546. }
  547. /// Add a new node to the forward dominator tree and make it a new root.
  548. ///
  549. /// \param BB New node in CFG.
  550. /// \returns New dominator tree node that represents new CFG node.
  551. ///
  552. DomTreeNodeBase<NodeT> *setNewRoot(NodeT *BB) {
  553. assert(getNode(BB) == nullptr && "Block already in dominator tree!");
  554. assert(!this->isPostDominator() &&
  555. "Cannot change root of post-dominator tree");
  556. DFSInfoValid = false;
  557. DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
  558. if (Roots.empty()) {
  559. addRoot(BB);
  560. } else {
  561. assert(Roots.size() == 1);
  562. NodeT *OldRoot = Roots.front();
  563. auto &OldNode = DomTreeNodes[OldRoot];
  564. OldNode = NewNode->addChild(std::move(DomTreeNodes[OldRoot]));
  565. OldNode->IDom = NewNode;
  566. OldNode->UpdateLevel();
  567. Roots[0] = BB;
  568. }
  569. return RootNode = NewNode;
  570. }
  571. /// changeImmediateDominator - This method is used to update the dominator
  572. /// tree information when a node's immediate dominator changes.
  573. ///
  574. void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
  575. DomTreeNodeBase<NodeT> *NewIDom) {
  576. assert(N && NewIDom && "Cannot change null node pointers!");
  577. DFSInfoValid = false;
  578. N->setIDom(NewIDom);
  579. }
  580. void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
  581. changeImmediateDominator(getNode(BB), getNode(NewBB));
  582. }
  583. /// eraseNode - Removes a node from the dominator tree. Block must not
  584. /// dominate any other blocks. Removes node from its immediate dominator's
  585. /// children list. Deletes dominator node associated with basic block BB.
  586. void eraseNode(NodeT *BB) {
  587. DomTreeNodeBase<NodeT> *Node = getNode(BB);
  588. assert(Node && "Removing node that isn't in dominator tree.");
  589. assert(Node->isLeaf() && "Node is not a leaf node.");
  590. DFSInfoValid = false;
  591. // Remove node from immediate dominator's children list.
  592. DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
  593. if (IDom) {
  594. const auto I = find(IDom->Children, Node);
  595. assert(I != IDom->Children.end() &&
  596. "Not in immediate dominator children set!");
  597. // I am no longer your child...
  598. IDom->Children.erase(I);
  599. }
  600. DomTreeNodes.erase(BB);
  601. if (!IsPostDom) return;
  602. // Remember to update PostDominatorTree roots.
  603. auto RIt = llvm::find(Roots, BB);
  604. if (RIt != Roots.end()) {
  605. std::swap(*RIt, Roots.back());
  606. Roots.pop_back();
  607. }
  608. }
  609. /// splitBlock - BB is split and now it has one successor. Update dominator
  610. /// tree to reflect this change.
  611. void splitBlock(NodeT *NewBB) {
  612. if (IsPostDominator)
  613. Split<Inverse<NodeT *>>(NewBB);
  614. else
  615. Split<NodeT *>(NewBB);
  616. }
  617. /// print - Convert to human readable form
  618. ///
  619. void print(raw_ostream &O) const {
  620. O << "=============================--------------------------------\n";
  621. if (IsPostDominator)
  622. O << "Inorder PostDominator Tree: ";
  623. else
  624. O << "Inorder Dominator Tree: ";
  625. if (!DFSInfoValid)
  626. O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
  627. O << "\n";
  628. // The postdom tree can have a null root if there are no returns.
  629. if (getRootNode()) PrintDomTree<NodeT>(getRootNode(), O, 1);
  630. O << "Roots: ";
  631. for (const NodePtr Block : Roots) {
  632. Block->printAsOperand(O, false);
  633. O << " ";
  634. }
  635. O << "\n";
  636. }
  637. public:
  638. /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
  639. /// dominator tree in dfs order.
  640. void updateDFSNumbers() const {
  641. if (DFSInfoValid) {
  642. SlowQueries = 0;
  643. return;
  644. }
  645. SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
  646. typename DomTreeNodeBase<NodeT>::const_iterator>,
  647. 32> WorkStack;
  648. const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
  649. assert((!Parent || ThisRoot) && "Empty constructed DomTree");
  650. if (!ThisRoot)
  651. return;
  652. // Both dominators and postdominators have a single root node. In the case
  653. // case of PostDominatorTree, this node is a virtual root.
  654. WorkStack.push_back({ThisRoot, ThisRoot->begin()});
  655. unsigned DFSNum = 0;
  656. ThisRoot->DFSNumIn = DFSNum++;
  657. while (!WorkStack.empty()) {
  658. const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
  659. const auto ChildIt = WorkStack.back().second;
  660. // If we visited all of the children of this node, "recurse" back up the
  661. // stack setting the DFOutNum.
  662. if (ChildIt == Node->end()) {
  663. Node->DFSNumOut = DFSNum++;
  664. WorkStack.pop_back();
  665. } else {
  666. // Otherwise, recursively visit this child.
  667. const DomTreeNodeBase<NodeT> *Child = *ChildIt;
  668. ++WorkStack.back().second;
  669. WorkStack.push_back({Child, Child->begin()});
  670. Child->DFSNumIn = DFSNum++;
  671. }
  672. }
  673. SlowQueries = 0;
  674. DFSInfoValid = true;
  675. }
  676. /// recalculate - compute a dominator tree for the given function
  677. void recalculate(ParentType &Func) {
  678. Parent = &Func;
  679. DomTreeBuilder::Calculate(*this);
  680. }
  681. void recalculate(ParentType &Func, ArrayRef<UpdateType> Updates) {
  682. Parent = &Func;
  683. DomTreeBuilder::CalculateWithUpdates(*this, Updates);
  684. }
  685. /// verify - checks if the tree is correct. There are 3 level of verification:
  686. /// - Full -- verifies if the tree is correct by making sure all the
  687. /// properties (including the parent and the sibling property)
  688. /// hold.
  689. /// Takes O(N^3) time.
  690. ///
  691. /// - Basic -- checks if the tree is correct, but compares it to a freshly
  692. /// constructed tree instead of checking the sibling property.
  693. /// Takes O(N^2) time.
  694. ///
  695. /// - Fast -- checks basic tree structure and compares it with a freshly
  696. /// constructed tree.
  697. /// Takes O(N^2) time worst case, but is faster in practise (same
  698. /// as tree construction).
  699. bool verify(VerificationLevel VL = VerificationLevel::Full) const {
  700. return DomTreeBuilder::Verify(*this, VL);
  701. }
  702. void reset() {
  703. DomTreeNodes.clear();
  704. Roots.clear();
  705. RootNode = nullptr;
  706. Parent = nullptr;
  707. DFSInfoValid = false;
  708. SlowQueries = 0;
  709. }
  710. protected:
  711. void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
  712. DomTreeNodeBase<NodeT> *createChild(NodeT *BB, DomTreeNodeBase<NodeT> *IDom) {
  713. return (DomTreeNodes[BB] = IDom->addChild(
  714. std::make_unique<DomTreeNodeBase<NodeT>>(BB, IDom)))
  715. .get();
  716. }
  717. DomTreeNodeBase<NodeT> *createNode(NodeT *BB) {
  718. return (DomTreeNodes[BB] =
  719. std::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr))
  720. .get();
  721. }
  722. // NewBB is split and now it has one successor. Update dominator tree to
  723. // reflect this change.
  724. template <class N>
  725. void Split(typename GraphTraits<N>::NodeRef NewBB) {
  726. using GraphT = GraphTraits<N>;
  727. using NodeRef = typename GraphT::NodeRef;
  728. assert(std::distance(GraphT::child_begin(NewBB),
  729. GraphT::child_end(NewBB)) == 1 &&
  730. "NewBB should have a single successor!");
  731. NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
  732. SmallVector<NodeRef, 4> PredBlocks(children<Inverse<N>>(NewBB));
  733. assert(!PredBlocks.empty() && "No predblocks?");
  734. bool NewBBDominatesNewBBSucc = true;
  735. for (auto *Pred : children<Inverse<N>>(NewBBSucc)) {
  736. if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
  737. isReachableFromEntry(Pred)) {
  738. NewBBDominatesNewBBSucc = false;
  739. break;
  740. }
  741. }
  742. // Find NewBB's immediate dominator and create new dominator tree node for
  743. // NewBB.
  744. NodeT *NewBBIDom = nullptr;
  745. unsigned i = 0;
  746. for (i = 0; i < PredBlocks.size(); ++i)
  747. if (isReachableFromEntry(PredBlocks[i])) {
  748. NewBBIDom = PredBlocks[i];
  749. break;
  750. }
  751. // It's possible that none of the predecessors of NewBB are reachable;
  752. // in that case, NewBB itself is unreachable, so nothing needs to be
  753. // changed.
  754. if (!NewBBIDom) return;
  755. for (i = i + 1; i < PredBlocks.size(); ++i) {
  756. if (isReachableFromEntry(PredBlocks[i]))
  757. NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
  758. }
  759. // Create the new dominator tree node... and set the idom of NewBB.
  760. DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
  761. // If NewBB strictly dominates other blocks, then it is now the immediate
  762. // dominator of NewBBSucc. Update the dominator tree as appropriate.
  763. if (NewBBDominatesNewBBSucc) {
  764. DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
  765. changeImmediateDominator(NewBBSuccNode, NewBBNode);
  766. }
  767. }
  768. private:
  769. bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
  770. const DomTreeNodeBase<NodeT> *B) const {
  771. assert(A != B);
  772. assert(isReachableFromEntry(B));
  773. assert(isReachableFromEntry(A));
  774. const unsigned ALevel = A->getLevel();
  775. const DomTreeNodeBase<NodeT> *IDom;
  776. // Don't walk nodes above A's subtree. When we reach A's level, we must
  777. // either find A or be in some other subtree not dominated by A.
  778. while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
  779. B = IDom; // Walk up the tree
  780. return B == A;
  781. }
  782. /// Wipe this tree's state without releasing any resources.
  783. ///
  784. /// This is essentially a post-move helper only. It leaves the object in an
  785. /// assignable and destroyable state, but otherwise invalid.
  786. void wipe() {
  787. DomTreeNodes.clear();
  788. RootNode = nullptr;
  789. Parent = nullptr;
  790. }
  791. };
  792. template <typename T>
  793. using DomTreeBase = DominatorTreeBase<T, false>;
  794. template <typename T>
  795. using PostDomTreeBase = DominatorTreeBase<T, true>;
  796. // These two functions are declared out of line as a workaround for building
  797. // with old (< r147295) versions of clang because of pr11642.
  798. template <typename NodeT, bool IsPostDom>
  799. bool DominatorTreeBase<NodeT, IsPostDom>::dominates(const NodeT *A,
  800. const NodeT *B) const {
  801. if (A == B)
  802. return true;
  803. // Cast away the const qualifiers here. This is ok since
  804. // this function doesn't actually return the values returned
  805. // from getNode.
  806. return dominates(getNode(const_cast<NodeT *>(A)),
  807. getNode(const_cast<NodeT *>(B)));
  808. }
  809. template <typename NodeT, bool IsPostDom>
  810. bool DominatorTreeBase<NodeT, IsPostDom>::properlyDominates(
  811. const NodeT *A, const NodeT *B) const {
  812. if (A == B)
  813. return false;
  814. // Cast away the const qualifiers here. This is ok since
  815. // this function doesn't actually return the values returned
  816. // from getNode.
  817. return dominates(getNode(const_cast<NodeT *>(A)),
  818. getNode(const_cast<NodeT *>(B)));
  819. }
  820. } // end namespace llvm
  821. #endif // LLVM_SUPPORT_GENERICDOMTREE_H
  822. #ifdef __GNUC__
  823. #pragma GCC diagnostic pop
  824. #endif