GenericDomTreeConstruction.h 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- GenericDomTreeConstruction.h - Dominator Calculation ------*- 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. /// Generic dominator tree construction - this file provides routines to
  16. /// construct immediate dominator information for a flow-graph based on the
  17. /// Semi-NCA algorithm described in this dissertation:
  18. ///
  19. /// [1] Linear-Time Algorithms for Dominators and Related Problems
  20. /// Loukas Georgiadis, Princeton University, November 2005, pp. 21-23:
  21. /// ftp://ftp.cs.princeton.edu/reports/2005/737.pdf
  22. ///
  23. /// Semi-NCA algorithm runs in O(n^2) worst-case time but usually slightly
  24. /// faster than Simple Lengauer-Tarjan in practice.
  25. ///
  26. /// O(n^2) worst cases happen when the computation of nearest common ancestors
  27. /// requires O(n) average time, which is very unlikely in real world. If this
  28. /// ever turns out to be an issue, consider implementing a hybrid algorithm
  29. /// that uses SLT to perform full constructions and SemiNCA for incremental
  30. /// updates.
  31. ///
  32. /// The file uses the Depth Based Search algorithm to perform incremental
  33. /// updates (insertion and deletions). The implemented algorithm is based on
  34. /// this publication:
  35. ///
  36. /// [2] An Experimental Study of Dynamic Dominators
  37. /// Loukas Georgiadis, et al., April 12 2016, pp. 5-7, 9-10:
  38. /// https://arxiv.org/pdf/1604.02711.pdf
  39. ///
  40. //===----------------------------------------------------------------------===//
  41. #ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  42. #define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  43. #include "llvm/ADT/ArrayRef.h"
  44. #include "llvm/ADT/DenseSet.h"
  45. #include "llvm/ADT/DepthFirstIterator.h"
  46. #include "llvm/ADT/PointerIntPair.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/Support/Debug.h"
  49. #include "llvm/Support/GenericDomTree.h"
  50. #include <optional>
  51. #include <queue>
  52. #define DEBUG_TYPE "dom-tree-builder"
  53. namespace llvm {
  54. namespace DomTreeBuilder {
  55. template <typename DomTreeT>
  56. struct SemiNCAInfo {
  57. using NodePtr = typename DomTreeT::NodePtr;
  58. using NodeT = typename DomTreeT::NodeType;
  59. using TreeNodePtr = DomTreeNodeBase<NodeT> *;
  60. using RootsT = decltype(DomTreeT::Roots);
  61. static constexpr bool IsPostDom = DomTreeT::IsPostDominator;
  62. using GraphDiffT = GraphDiff<NodePtr, IsPostDom>;
  63. // Information record used by Semi-NCA during tree construction.
  64. struct InfoRec {
  65. unsigned DFSNum = 0;
  66. unsigned Parent = 0;
  67. unsigned Semi = 0;
  68. NodePtr Label = nullptr;
  69. NodePtr IDom = nullptr;
  70. SmallVector<NodePtr, 2> ReverseChildren;
  71. };
  72. // Number to node mapping is 1-based. Initialize the mapping to start with
  73. // a dummy element.
  74. std::vector<NodePtr> NumToNode = {nullptr};
  75. DenseMap<NodePtr, InfoRec> NodeToInfo;
  76. using UpdateT = typename DomTreeT::UpdateType;
  77. using UpdateKind = typename DomTreeT::UpdateKind;
  78. struct BatchUpdateInfo {
  79. // Note: Updates inside PreViewCFG are already legalized.
  80. BatchUpdateInfo(GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG = nullptr)
  81. : PreViewCFG(PreViewCFG), PostViewCFG(PostViewCFG),
  82. NumLegalized(PreViewCFG.getNumLegalizedUpdates()) {}
  83. // Remembers if the whole tree was recalculated at some point during the
  84. // current batch update.
  85. bool IsRecalculated = false;
  86. GraphDiffT &PreViewCFG;
  87. GraphDiffT *PostViewCFG;
  88. const size_t NumLegalized;
  89. };
  90. BatchUpdateInfo *BatchUpdates;
  91. using BatchUpdatePtr = BatchUpdateInfo *;
  92. // If BUI is a nullptr, then there's no batch update in progress.
  93. SemiNCAInfo(BatchUpdatePtr BUI) : BatchUpdates(BUI) {}
  94. void clear() {
  95. NumToNode = {nullptr}; // Restore to initial state with a dummy start node.
  96. NodeToInfo.clear();
  97. // Don't reset the pointer to BatchUpdateInfo here -- if there's an update
  98. // in progress, we need this information to continue it.
  99. }
  100. template <bool Inversed>
  101. static SmallVector<NodePtr, 8> getChildren(NodePtr N, BatchUpdatePtr BUI) {
  102. if (BUI)
  103. return BUI->PreViewCFG.template getChildren<Inversed>(N);
  104. return getChildren<Inversed>(N);
  105. }
  106. template <bool Inversed>
  107. static SmallVector<NodePtr, 8> getChildren(NodePtr N) {
  108. using DirectedNodeT =
  109. std::conditional_t<Inversed, Inverse<NodePtr>, NodePtr>;
  110. auto R = children<DirectedNodeT>(N);
  111. SmallVector<NodePtr, 8> Res(detail::reverse_if<!Inversed>(R));
  112. // Remove nullptr children for clang.
  113. llvm::erase_value(Res, nullptr);
  114. return Res;
  115. }
  116. NodePtr getIDom(NodePtr BB) const {
  117. auto InfoIt = NodeToInfo.find(BB);
  118. if (InfoIt == NodeToInfo.end()) return nullptr;
  119. return InfoIt->second.IDom;
  120. }
  121. TreeNodePtr getNodeForBlock(NodePtr BB, DomTreeT &DT) {
  122. if (TreeNodePtr Node = DT.getNode(BB)) return Node;
  123. // Haven't calculated this node yet? Get or calculate the node for the
  124. // immediate dominator.
  125. NodePtr IDom = getIDom(BB);
  126. assert(IDom || DT.DomTreeNodes[nullptr]);
  127. TreeNodePtr IDomNode = getNodeForBlock(IDom, DT);
  128. // Add a new tree node for this NodeT, and link it as a child of
  129. // IDomNode
  130. return DT.createChild(BB, IDomNode);
  131. }
  132. static bool AlwaysDescend(NodePtr, NodePtr) { return true; }
  133. struct BlockNamePrinter {
  134. NodePtr N;
  135. BlockNamePrinter(NodePtr Block) : N(Block) {}
  136. BlockNamePrinter(TreeNodePtr TN) : N(TN ? TN->getBlock() : nullptr) {}
  137. friend raw_ostream &operator<<(raw_ostream &O, const BlockNamePrinter &BP) {
  138. if (!BP.N)
  139. O << "nullptr";
  140. else
  141. BP.N->printAsOperand(O, false);
  142. return O;
  143. }
  144. };
  145. using NodeOrderMap = DenseMap<NodePtr, unsigned>;
  146. // Custom DFS implementation which can skip nodes based on a provided
  147. // predicate. It also collects ReverseChildren so that we don't have to spend
  148. // time getting predecessors in SemiNCA.
  149. //
  150. // If IsReverse is set to true, the DFS walk will be performed backwards
  151. // relative to IsPostDom -- using reverse edges for dominators and forward
  152. // edges for postdominators.
  153. //
  154. // If SuccOrder is specified then in this order the DFS traverses the children
  155. // otherwise the order is implied by the results of getChildren().
  156. template <bool IsReverse = false, typename DescendCondition>
  157. unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition,
  158. unsigned AttachToNum,
  159. const NodeOrderMap *SuccOrder = nullptr) {
  160. assert(V);
  161. SmallVector<NodePtr, 64> WorkList = {V};
  162. if (NodeToInfo.count(V) != 0) NodeToInfo[V].Parent = AttachToNum;
  163. while (!WorkList.empty()) {
  164. const NodePtr BB = WorkList.pop_back_val();
  165. auto &BBInfo = NodeToInfo[BB];
  166. // Visited nodes always have positive DFS numbers.
  167. if (BBInfo.DFSNum != 0) continue;
  168. BBInfo.DFSNum = BBInfo.Semi = ++LastNum;
  169. BBInfo.Label = BB;
  170. NumToNode.push_back(BB);
  171. constexpr bool Direction = IsReverse != IsPostDom; // XOR.
  172. auto Successors = getChildren<Direction>(BB, BatchUpdates);
  173. if (SuccOrder && Successors.size() > 1)
  174. llvm::sort(
  175. Successors.begin(), Successors.end(), [=](NodePtr A, NodePtr B) {
  176. return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
  177. });
  178. for (const NodePtr Succ : Successors) {
  179. const auto SIT = NodeToInfo.find(Succ);
  180. // Don't visit nodes more than once but remember to collect
  181. // ReverseChildren.
  182. if (SIT != NodeToInfo.end() && SIT->second.DFSNum != 0) {
  183. if (Succ != BB) SIT->second.ReverseChildren.push_back(BB);
  184. continue;
  185. }
  186. if (!Condition(BB, Succ)) continue;
  187. // It's fine to add Succ to the map, because we know that it will be
  188. // visited later.
  189. auto &SuccInfo = NodeToInfo[Succ];
  190. WorkList.push_back(Succ);
  191. SuccInfo.Parent = LastNum;
  192. SuccInfo.ReverseChildren.push_back(BB);
  193. }
  194. }
  195. return LastNum;
  196. }
  197. // V is a predecessor of W. eval() returns V if V < W, otherwise the minimum
  198. // of sdom(U), where U > W and there is a virtual forest path from U to V. The
  199. // virtual forest consists of linked edges of processed vertices.
  200. //
  201. // We can follow Parent pointers (virtual forest edges) to determine the
  202. // ancestor U with minimum sdom(U). But it is slow and thus we employ the path
  203. // compression technique to speed up to O(m*log(n)). Theoretically the virtual
  204. // forest can be organized as balanced trees to achieve almost linear
  205. // O(m*alpha(m,n)) running time. But it requires two auxiliary arrays (Size
  206. // and Child) and is unlikely to be faster than the simple implementation.
  207. //
  208. // For each vertex V, its Label points to the vertex with the minimal sdom(U)
  209. // (Semi) in its path from V (included) to NodeToInfo[V].Parent (excluded).
  210. NodePtr eval(NodePtr V, unsigned LastLinked,
  211. SmallVectorImpl<InfoRec *> &Stack) {
  212. InfoRec *VInfo = &NodeToInfo[V];
  213. if (VInfo->Parent < LastLinked)
  214. return VInfo->Label;
  215. // Store ancestors except the last (root of a virtual tree) into a stack.
  216. assert(Stack.empty());
  217. do {
  218. Stack.push_back(VInfo);
  219. VInfo = &NodeToInfo[NumToNode[VInfo->Parent]];
  220. } while (VInfo->Parent >= LastLinked);
  221. // Path compression. Point each vertex's Parent to the root and update its
  222. // Label if any of its ancestors (PInfo->Label) has a smaller Semi.
  223. const InfoRec *PInfo = VInfo;
  224. const InfoRec *PLabelInfo = &NodeToInfo[PInfo->Label];
  225. do {
  226. VInfo = Stack.pop_back_val();
  227. VInfo->Parent = PInfo->Parent;
  228. const InfoRec *VLabelInfo = &NodeToInfo[VInfo->Label];
  229. if (PLabelInfo->Semi < VLabelInfo->Semi)
  230. VInfo->Label = PInfo->Label;
  231. else
  232. PLabelInfo = VLabelInfo;
  233. PInfo = VInfo;
  234. } while (!Stack.empty());
  235. return VInfo->Label;
  236. }
  237. // This function requires DFS to be run before calling it.
  238. void runSemiNCA(DomTreeT &DT, const unsigned MinLevel = 0) {
  239. const unsigned NextDFSNum(NumToNode.size());
  240. // Initialize IDoms to spanning tree parents.
  241. for (unsigned i = 1; i < NextDFSNum; ++i) {
  242. const NodePtr V = NumToNode[i];
  243. auto &VInfo = NodeToInfo[V];
  244. VInfo.IDom = NumToNode[VInfo.Parent];
  245. }
  246. // Step #1: Calculate the semidominators of all vertices.
  247. SmallVector<InfoRec *, 32> EvalStack;
  248. for (unsigned i = NextDFSNum - 1; i >= 2; --i) {
  249. NodePtr W = NumToNode[i];
  250. auto &WInfo = NodeToInfo[W];
  251. // Initialize the semi dominator to point to the parent node.
  252. WInfo.Semi = WInfo.Parent;
  253. for (const auto &N : WInfo.ReverseChildren) {
  254. if (NodeToInfo.count(N) == 0) // Skip unreachable predecessors.
  255. continue;
  256. const TreeNodePtr TN = DT.getNode(N);
  257. // Skip predecessors whose level is above the subtree we are processing.
  258. if (TN && TN->getLevel() < MinLevel)
  259. continue;
  260. unsigned SemiU = NodeToInfo[eval(N, i + 1, EvalStack)].Semi;
  261. if (SemiU < WInfo.Semi) WInfo.Semi = SemiU;
  262. }
  263. }
  264. // Step #2: Explicitly define the immediate dominator of each vertex.
  265. // IDom[i] = NCA(SDom[i], SpanningTreeParent(i)).
  266. // Note that the parents were stored in IDoms and later got invalidated
  267. // during path compression in Eval.
  268. for (unsigned i = 2; i < NextDFSNum; ++i) {
  269. const NodePtr W = NumToNode[i];
  270. auto &WInfo = NodeToInfo[W];
  271. const unsigned SDomNum = NodeToInfo[NumToNode[WInfo.Semi]].DFSNum;
  272. NodePtr WIDomCandidate = WInfo.IDom;
  273. while (NodeToInfo[WIDomCandidate].DFSNum > SDomNum)
  274. WIDomCandidate = NodeToInfo[WIDomCandidate].IDom;
  275. WInfo.IDom = WIDomCandidate;
  276. }
  277. }
  278. // PostDominatorTree always has a virtual root that represents a virtual CFG
  279. // node that serves as a single exit from the function. All the other exits
  280. // (CFG nodes with terminators and nodes in infinite loops are logically
  281. // connected to this virtual CFG exit node).
  282. // This functions maps a nullptr CFG node to the virtual root tree node.
  283. void addVirtualRoot() {
  284. assert(IsPostDom && "Only postdominators have a virtual root");
  285. assert(NumToNode.size() == 1 && "SNCAInfo must be freshly constructed");
  286. auto &BBInfo = NodeToInfo[nullptr];
  287. BBInfo.DFSNum = BBInfo.Semi = 1;
  288. BBInfo.Label = nullptr;
  289. NumToNode.push_back(nullptr); // NumToNode[1] = nullptr;
  290. }
  291. // For postdominators, nodes with no forward successors are trivial roots that
  292. // are always selected as tree roots. Roots with forward successors correspond
  293. // to CFG nodes within infinite loops.
  294. static bool HasForwardSuccessors(const NodePtr N, BatchUpdatePtr BUI) {
  295. assert(N && "N must be a valid node");
  296. return !getChildren<false>(N, BUI).empty();
  297. }
  298. static NodePtr GetEntryNode(const DomTreeT &DT) {
  299. assert(DT.Parent && "Parent not set");
  300. return GraphTraits<typename DomTreeT::ParentPtr>::getEntryNode(DT.Parent);
  301. }
  302. // Finds all roots without relaying on the set of roots already stored in the
  303. // tree.
  304. // We define roots to be some non-redundant set of the CFG nodes
  305. static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI) {
  306. assert(DT.Parent && "Parent pointer is not set");
  307. RootsT Roots;
  308. // For dominators, function entry CFG node is always a tree root node.
  309. if (!IsPostDom) {
  310. Roots.push_back(GetEntryNode(DT));
  311. return Roots;
  312. }
  313. SemiNCAInfo SNCA(BUI);
  314. // PostDominatorTree always has a virtual root.
  315. SNCA.addVirtualRoot();
  316. unsigned Num = 1;
  317. LLVM_DEBUG(dbgs() << "\t\tLooking for trivial roots\n");
  318. // Step #1: Find all the trivial roots that are going to will definitely
  319. // remain tree roots.
  320. unsigned Total = 0;
  321. // It may happen that there are some new nodes in the CFG that are result of
  322. // the ongoing batch update, but we cannot really pretend that they don't
  323. // exist -- we won't see any outgoing or incoming edges to them, so it's
  324. // fine to discover them here, as they would end up appearing in the CFG at
  325. // some point anyway.
  326. for (const NodePtr N : nodes(DT.Parent)) {
  327. ++Total;
  328. // If it has no *successors*, it is definitely a root.
  329. if (!HasForwardSuccessors(N, BUI)) {
  330. Roots.push_back(N);
  331. // Run DFS not to walk this part of CFG later.
  332. Num = SNCA.runDFS(N, Num, AlwaysDescend, 1);
  333. LLVM_DEBUG(dbgs() << "Found a new trivial root: " << BlockNamePrinter(N)
  334. << "\n");
  335. LLVM_DEBUG(dbgs() << "Last visited node: "
  336. << BlockNamePrinter(SNCA.NumToNode[Num]) << "\n");
  337. }
  338. }
  339. LLVM_DEBUG(dbgs() << "\t\tLooking for non-trivial roots\n");
  340. // Step #2: Find all non-trivial root candidates. Those are CFG nodes that
  341. // are reverse-unreachable were not visited by previous DFS walks (i.e. CFG
  342. // nodes in infinite loops).
  343. bool HasNonTrivialRoots = false;
  344. // Accounting for the virtual exit, see if we had any reverse-unreachable
  345. // nodes.
  346. if (Total + 1 != Num) {
  347. HasNonTrivialRoots = true;
  348. // SuccOrder is the order of blocks in the function. It is needed to make
  349. // the calculation of the FurthestAway node and the whole PostDomTree
  350. // immune to swap successors transformation (e.g. canonicalizing branch
  351. // predicates). SuccOrder is initialized lazily only for successors of
  352. // reverse unreachable nodes.
  353. std::optional<NodeOrderMap> SuccOrder;
  354. auto InitSuccOrderOnce = [&]() {
  355. SuccOrder = NodeOrderMap();
  356. for (const auto Node : nodes(DT.Parent))
  357. if (SNCA.NodeToInfo.count(Node) == 0)
  358. for (const auto Succ : getChildren<false>(Node, SNCA.BatchUpdates))
  359. SuccOrder->try_emplace(Succ, 0);
  360. // Add mapping for all entries of SuccOrder.
  361. unsigned NodeNum = 0;
  362. for (const auto Node : nodes(DT.Parent)) {
  363. ++NodeNum;
  364. auto Order = SuccOrder->find(Node);
  365. if (Order != SuccOrder->end()) {
  366. assert(Order->second == 0);
  367. Order->second = NodeNum;
  368. }
  369. }
  370. };
  371. // Make another DFS pass over all other nodes to find the
  372. // reverse-unreachable blocks, and find the furthest paths we'll be able
  373. // to make.
  374. // Note that this looks N^2, but it's really 2N worst case, if every node
  375. // is unreachable. This is because we are still going to only visit each
  376. // unreachable node once, we may just visit it in two directions,
  377. // depending on how lucky we get.
  378. for (const NodePtr I : nodes(DT.Parent)) {
  379. if (SNCA.NodeToInfo.count(I) == 0) {
  380. LLVM_DEBUG(dbgs()
  381. << "\t\t\tVisiting node " << BlockNamePrinter(I) << "\n");
  382. // Find the furthest away we can get by following successors, then
  383. // follow them in reverse. This gives us some reasonable answer about
  384. // the post-dom tree inside any infinite loop. In particular, it
  385. // guarantees we get to the farthest away point along *some*
  386. // path. This also matches the GCC's behavior.
  387. // If we really wanted a totally complete picture of dominance inside
  388. // this infinite loop, we could do it with SCC-like algorithms to find
  389. // the lowest and highest points in the infinite loop. In theory, it
  390. // would be nice to give the canonical backedge for the loop, but it's
  391. // expensive and does not always lead to a minimal set of roots.
  392. LLVM_DEBUG(dbgs() << "\t\t\tRunning forward DFS\n");
  393. if (!SuccOrder)
  394. InitSuccOrderOnce();
  395. assert(SuccOrder);
  396. const unsigned NewNum =
  397. SNCA.runDFS<true>(I, Num, AlwaysDescend, Num, &*SuccOrder);
  398. const NodePtr FurthestAway = SNCA.NumToNode[NewNum];
  399. LLVM_DEBUG(dbgs() << "\t\t\tFound a new furthest away node "
  400. << "(non-trivial root): "
  401. << BlockNamePrinter(FurthestAway) << "\n");
  402. Roots.push_back(FurthestAway);
  403. LLVM_DEBUG(dbgs() << "\t\t\tPrev DFSNum: " << Num << ", new DFSNum: "
  404. << NewNum << "\n\t\t\tRemoving DFS info\n");
  405. for (unsigned i = NewNum; i > Num; --i) {
  406. const NodePtr N = SNCA.NumToNode[i];
  407. LLVM_DEBUG(dbgs() << "\t\t\t\tRemoving DFS info for "
  408. << BlockNamePrinter(N) << "\n");
  409. SNCA.NodeToInfo.erase(N);
  410. SNCA.NumToNode.pop_back();
  411. }
  412. const unsigned PrevNum = Num;
  413. LLVM_DEBUG(dbgs() << "\t\t\tRunning reverse DFS\n");
  414. Num = SNCA.runDFS(FurthestAway, Num, AlwaysDescend, 1);
  415. for (unsigned i = PrevNum + 1; i <= Num; ++i)
  416. LLVM_DEBUG(dbgs() << "\t\t\t\tfound node "
  417. << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
  418. }
  419. }
  420. }
  421. LLVM_DEBUG(dbgs() << "Total: " << Total << ", Num: " << Num << "\n");
  422. LLVM_DEBUG(dbgs() << "Discovered CFG nodes:\n");
  423. LLVM_DEBUG(for (size_t i = 0; i <= Num; ++i) dbgs()
  424. << i << ": " << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
  425. assert((Total + 1 == Num) && "Everything should have been visited");
  426. // Step #3: If we found some non-trivial roots, make them non-redundant.
  427. if (HasNonTrivialRoots) RemoveRedundantRoots(DT, BUI, Roots);
  428. LLVM_DEBUG(dbgs() << "Found roots: ");
  429. LLVM_DEBUG(for (auto *Root
  430. : Roots) dbgs()
  431. << BlockNamePrinter(Root) << " ");
  432. LLVM_DEBUG(dbgs() << "\n");
  433. return Roots;
  434. }
  435. // This function only makes sense for postdominators.
  436. // We define roots to be some set of CFG nodes where (reverse) DFS walks have
  437. // to start in order to visit all the CFG nodes (including the
  438. // reverse-unreachable ones).
  439. // When the search for non-trivial roots is done it may happen that some of
  440. // the non-trivial roots are reverse-reachable from other non-trivial roots,
  441. // which makes them redundant. This function removes them from the set of
  442. // input roots.
  443. static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI,
  444. RootsT &Roots) {
  445. assert(IsPostDom && "This function is for postdominators only");
  446. LLVM_DEBUG(dbgs() << "Removing redundant roots\n");
  447. SemiNCAInfo SNCA(BUI);
  448. for (unsigned i = 0; i < Roots.size(); ++i) {
  449. auto &Root = Roots[i];
  450. // Trivial roots are always non-redundant.
  451. if (!HasForwardSuccessors(Root, BUI)) continue;
  452. LLVM_DEBUG(dbgs() << "\tChecking if " << BlockNamePrinter(Root)
  453. << " remains a root\n");
  454. SNCA.clear();
  455. // Do a forward walk looking for the other roots.
  456. const unsigned Num = SNCA.runDFS<true>(Root, 0, AlwaysDescend, 0);
  457. // Skip the start node and begin from the second one (note that DFS uses
  458. // 1-based indexing).
  459. for (unsigned x = 2; x <= Num; ++x) {
  460. const NodePtr N = SNCA.NumToNode[x];
  461. // If we wound another root in a (forward) DFS walk, remove the current
  462. // root from the set of roots, as it is reverse-reachable from the other
  463. // one.
  464. if (llvm::is_contained(Roots, N)) {
  465. LLVM_DEBUG(dbgs() << "\tForward DFS walk found another root "
  466. << BlockNamePrinter(N) << "\n\tRemoving root "
  467. << BlockNamePrinter(Root) << "\n");
  468. std::swap(Root, Roots.back());
  469. Roots.pop_back();
  470. // Root at the back takes the current root's place.
  471. // Start the next loop iteration with the same index.
  472. --i;
  473. break;
  474. }
  475. }
  476. }
  477. }
  478. template <typename DescendCondition>
  479. void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC) {
  480. if (!IsPostDom) {
  481. assert(DT.Roots.size() == 1 && "Dominators should have a singe root");
  482. runDFS(DT.Roots[0], 0, DC, 0);
  483. return;
  484. }
  485. addVirtualRoot();
  486. unsigned Num = 1;
  487. for (const NodePtr Root : DT.Roots) Num = runDFS(Root, Num, DC, 0);
  488. }
  489. static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI) {
  490. auto *Parent = DT.Parent;
  491. DT.reset();
  492. DT.Parent = Parent;
  493. // If the update is using the actual CFG, BUI is null. If it's using a view,
  494. // BUI is non-null and the PreCFGView is used. When calculating from
  495. // scratch, make the PreViewCFG equal to the PostCFGView, so Post is used.
  496. BatchUpdatePtr PostViewBUI = nullptr;
  497. if (BUI && BUI->PostViewCFG) {
  498. BUI->PreViewCFG = *BUI->PostViewCFG;
  499. PostViewBUI = BUI;
  500. }
  501. // This is rebuilding the whole tree, not incrementally, but PostViewBUI is
  502. // used in case the caller needs a DT update with a CFGView.
  503. SemiNCAInfo SNCA(PostViewBUI);
  504. // Step #0: Number blocks in depth-first order and initialize variables used
  505. // in later stages of the algorithm.
  506. DT.Roots = FindRoots(DT, PostViewBUI);
  507. SNCA.doFullDFSWalk(DT, AlwaysDescend);
  508. SNCA.runSemiNCA(DT);
  509. if (BUI) {
  510. BUI->IsRecalculated = true;
  511. LLVM_DEBUG(
  512. dbgs() << "DomTree recalculated, skipping future batch updates\n");
  513. }
  514. if (DT.Roots.empty()) return;
  515. // Add a node for the root. If the tree is a PostDominatorTree it will be
  516. // the virtual exit (denoted by (BasicBlock *) nullptr) which postdominates
  517. // all real exits (including multiple exit blocks, infinite loops).
  518. NodePtr Root = IsPostDom ? nullptr : DT.Roots[0];
  519. DT.RootNode = DT.createNode(Root);
  520. SNCA.attachNewSubtree(DT, DT.RootNode);
  521. }
  522. void attachNewSubtree(DomTreeT& DT, const TreeNodePtr AttachTo) {
  523. // Attach the first unreachable block to AttachTo.
  524. NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
  525. // Loop over all of the discovered blocks in the function...
  526. for (size_t i = 1, e = NumToNode.size(); i != e; ++i) {
  527. NodePtr W = NumToNode[i];
  528. // Don't replace this with 'count', the insertion side effect is important
  529. if (DT.DomTreeNodes[W]) continue; // Haven't calculated this node yet?
  530. NodePtr ImmDom = getIDom(W);
  531. // Get or calculate the node for the immediate dominator.
  532. TreeNodePtr IDomNode = getNodeForBlock(ImmDom, DT);
  533. // Add a new tree node for this BasicBlock, and link it as a child of
  534. // IDomNode.
  535. DT.createChild(W, IDomNode);
  536. }
  537. }
  538. void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo) {
  539. NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
  540. for (size_t i = 1, e = NumToNode.size(); i != e; ++i) {
  541. const NodePtr N = NumToNode[i];
  542. const TreeNodePtr TN = DT.getNode(N);
  543. assert(TN);
  544. const TreeNodePtr NewIDom = DT.getNode(NodeToInfo[N].IDom);
  545. TN->setIDom(NewIDom);
  546. }
  547. }
  548. // Helper struct used during edge insertions.
  549. struct InsertionInfo {
  550. struct Compare {
  551. bool operator()(TreeNodePtr LHS, TreeNodePtr RHS) const {
  552. return LHS->getLevel() < RHS->getLevel();
  553. }
  554. };
  555. // Bucket queue of tree nodes ordered by descending level. For simplicity,
  556. // we use a priority_queue here.
  557. std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>,
  558. Compare>
  559. Bucket;
  560. SmallDenseSet<TreeNodePtr, 8> Visited;
  561. SmallVector<TreeNodePtr, 8> Affected;
  562. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  563. SmallVector<TreeNodePtr, 8> VisitedUnaffected;
  564. #endif
  565. };
  566. static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
  567. const NodePtr From, const NodePtr To) {
  568. assert((From || IsPostDom) &&
  569. "From has to be a valid CFG node or a virtual root");
  570. assert(To && "Cannot be a nullptr");
  571. LLVM_DEBUG(dbgs() << "Inserting edge " << BlockNamePrinter(From) << " -> "
  572. << BlockNamePrinter(To) << "\n");
  573. TreeNodePtr FromTN = DT.getNode(From);
  574. if (!FromTN) {
  575. // Ignore edges from unreachable nodes for (forward) dominators.
  576. if (!IsPostDom) return;
  577. // The unreachable node becomes a new root -- a tree node for it.
  578. TreeNodePtr VirtualRoot = DT.getNode(nullptr);
  579. FromTN = DT.createChild(From, VirtualRoot);
  580. DT.Roots.push_back(From);
  581. }
  582. DT.DFSInfoValid = false;
  583. const TreeNodePtr ToTN = DT.getNode(To);
  584. if (!ToTN)
  585. InsertUnreachable(DT, BUI, FromTN, To);
  586. else
  587. InsertReachable(DT, BUI, FromTN, ToTN);
  588. }
  589. // Determines if some existing root becomes reverse-reachable after the
  590. // insertion. Rebuilds the whole tree if that situation happens.
  591. static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
  592. const TreeNodePtr From,
  593. const TreeNodePtr To) {
  594. assert(IsPostDom && "This function is only for postdominators");
  595. // Destination node is not attached to the virtual root, so it cannot be a
  596. // root.
  597. if (!DT.isVirtualRoot(To->getIDom())) return false;
  598. if (!llvm::is_contained(DT.Roots, To->getBlock()))
  599. return false; // To is not a root, nothing to update.
  600. LLVM_DEBUG(dbgs() << "\t\tAfter the insertion, " << BlockNamePrinter(To)
  601. << " is no longer a root\n\t\tRebuilding the tree!!!\n");
  602. CalculateFromScratch(DT, BUI);
  603. return true;
  604. }
  605. static bool isPermutation(const SmallVectorImpl<NodePtr> &A,
  606. const SmallVectorImpl<NodePtr> &B) {
  607. if (A.size() != B.size())
  608. return false;
  609. SmallPtrSet<NodePtr, 4> Set(A.begin(), A.end());
  610. for (NodePtr N : B)
  611. if (Set.count(N) == 0)
  612. return false;
  613. return true;
  614. }
  615. // Updates the set of roots after insertion or deletion. This ensures that
  616. // roots are the same when after a series of updates and when the tree would
  617. // be built from scratch.
  618. static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI) {
  619. assert(IsPostDom && "This function is only for postdominators");
  620. // The tree has only trivial roots -- nothing to update.
  621. if (llvm::none_of(DT.Roots, [BUI](const NodePtr N) {
  622. return HasForwardSuccessors(N, BUI);
  623. }))
  624. return;
  625. // Recalculate the set of roots.
  626. RootsT Roots = FindRoots(DT, BUI);
  627. if (!isPermutation(DT.Roots, Roots)) {
  628. // The roots chosen in the CFG have changed. This is because the
  629. // incremental algorithm does not really know or use the set of roots and
  630. // can make a different (implicit) decision about which node within an
  631. // infinite loop becomes a root.
  632. LLVM_DEBUG(dbgs() << "Roots are different in updated trees\n"
  633. << "The entire tree needs to be rebuilt\n");
  634. // It may be possible to update the tree without recalculating it, but
  635. // we do not know yet how to do it, and it happens rarely in practice.
  636. CalculateFromScratch(DT, BUI);
  637. }
  638. }
  639. // Handles insertion to a node already in the dominator tree.
  640. static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  641. const TreeNodePtr From, const TreeNodePtr To) {
  642. LLVM_DEBUG(dbgs() << "\tReachable " << BlockNamePrinter(From->getBlock())
  643. << " -> " << BlockNamePrinter(To->getBlock()) << "\n");
  644. if (IsPostDom && UpdateRootsBeforeInsertion(DT, BUI, From, To)) return;
  645. // DT.findNCD expects both pointers to be valid. When From is a virtual
  646. // root, then its CFG block pointer is a nullptr, so we have to 'compute'
  647. // the NCD manually.
  648. const NodePtr NCDBlock =
  649. (From->getBlock() && To->getBlock())
  650. ? DT.findNearestCommonDominator(From->getBlock(), To->getBlock())
  651. : nullptr;
  652. assert(NCDBlock || DT.isPostDominator());
  653. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  654. assert(NCD);
  655. LLVM_DEBUG(dbgs() << "\t\tNCA == " << BlockNamePrinter(NCD) << "\n");
  656. const unsigned NCDLevel = NCD->getLevel();
  657. // Based on Lemma 2.5 from [2], after insertion of (From,To), v is affected
  658. // iff depth(NCD)+1 < depth(v) && a path P from To to v exists where every
  659. // w on P s.t. depth(v) <= depth(w)
  660. //
  661. // This reduces to a widest path problem (maximizing the depth of the
  662. // minimum vertex in the path) which can be solved by a modified version of
  663. // Dijkstra with a bucket queue (named depth-based search in [2]).
  664. // To is in the path, so depth(NCD)+1 < depth(v) <= depth(To). Nothing
  665. // affected if this does not hold.
  666. if (NCDLevel + 1 >= To->getLevel())
  667. return;
  668. InsertionInfo II;
  669. SmallVector<TreeNodePtr, 8> UnaffectedOnCurrentLevel;
  670. II.Bucket.push(To);
  671. II.Visited.insert(To);
  672. while (!II.Bucket.empty()) {
  673. TreeNodePtr TN = II.Bucket.top();
  674. II.Bucket.pop();
  675. II.Affected.push_back(TN);
  676. const unsigned CurrentLevel = TN->getLevel();
  677. LLVM_DEBUG(dbgs() << "Mark " << BlockNamePrinter(TN) <<
  678. "as affected, CurrentLevel " << CurrentLevel << "\n");
  679. assert(TN->getBlock() && II.Visited.count(TN) && "Preconditions!");
  680. while (true) {
  681. // Unlike regular Dijkstra, we have an inner loop to expand more
  682. // vertices. The first iteration is for the (affected) vertex popped
  683. // from II.Bucket and the rest are for vertices in
  684. // UnaffectedOnCurrentLevel, which may eventually expand to affected
  685. // vertices.
  686. //
  687. // Invariant: there is an optimal path from `To` to TN with the minimum
  688. // depth being CurrentLevel.
  689. for (const NodePtr Succ : getChildren<IsPostDom>(TN->getBlock(), BUI)) {
  690. const TreeNodePtr SuccTN = DT.getNode(Succ);
  691. assert(SuccTN &&
  692. "Unreachable successor found at reachable insertion");
  693. const unsigned SuccLevel = SuccTN->getLevel();
  694. LLVM_DEBUG(dbgs() << "\tSuccessor " << BlockNamePrinter(Succ)
  695. << ", level = " << SuccLevel << "\n");
  696. // There is an optimal path from `To` to Succ with the minimum depth
  697. // being min(CurrentLevel, SuccLevel).
  698. //
  699. // If depth(NCD)+1 < depth(Succ) is not satisfied, Succ is unaffected
  700. // and no affected vertex may be reached by a path passing through it.
  701. // Stop here. Also, Succ may be visited by other predecessors but the
  702. // first visit has the optimal path. Stop if Succ has been visited.
  703. if (SuccLevel <= NCDLevel + 1 || !II.Visited.insert(SuccTN).second)
  704. continue;
  705. if (SuccLevel > CurrentLevel) {
  706. // Succ is unaffected but it may (transitively) expand to affected
  707. // vertices. Store it in UnaffectedOnCurrentLevel.
  708. LLVM_DEBUG(dbgs() << "\t\tMarking visited not affected "
  709. << BlockNamePrinter(Succ) << "\n");
  710. UnaffectedOnCurrentLevel.push_back(SuccTN);
  711. #ifndef NDEBUG
  712. II.VisitedUnaffected.push_back(SuccTN);
  713. #endif
  714. } else {
  715. // The condition is satisfied (Succ is affected). Add Succ to the
  716. // bucket queue.
  717. LLVM_DEBUG(dbgs() << "\t\tAdd " << BlockNamePrinter(Succ)
  718. << " to a Bucket\n");
  719. II.Bucket.push(SuccTN);
  720. }
  721. }
  722. if (UnaffectedOnCurrentLevel.empty())
  723. break;
  724. TN = UnaffectedOnCurrentLevel.pop_back_val();
  725. LLVM_DEBUG(dbgs() << " Next: " << BlockNamePrinter(TN) << "\n");
  726. }
  727. }
  728. // Finish by updating immediate dominators and levels.
  729. UpdateInsertion(DT, BUI, NCD, II);
  730. }
  731. // Updates immediate dominators and levels after insertion.
  732. static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
  733. const TreeNodePtr NCD, InsertionInfo &II) {
  734. LLVM_DEBUG(dbgs() << "Updating NCD = " << BlockNamePrinter(NCD) << "\n");
  735. for (const TreeNodePtr TN : II.Affected) {
  736. LLVM_DEBUG(dbgs() << "\tIDom(" << BlockNamePrinter(TN)
  737. << ") = " << BlockNamePrinter(NCD) << "\n");
  738. TN->setIDom(NCD);
  739. }
  740. #if defined(LLVM_ENABLE_ABI_BREAKING_CHECKS) && !defined(NDEBUG)
  741. for (const TreeNodePtr TN : II.VisitedUnaffected)
  742. assert(TN->getLevel() == TN->getIDom()->getLevel() + 1 &&
  743. "TN should have been updated by an affected ancestor");
  744. #endif
  745. if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
  746. }
  747. // Handles insertion to previously unreachable nodes.
  748. static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  749. const TreeNodePtr From, const NodePtr To) {
  750. LLVM_DEBUG(dbgs() << "Inserting " << BlockNamePrinter(From)
  751. << " -> (unreachable) " << BlockNamePrinter(To) << "\n");
  752. // Collect discovered edges to already reachable nodes.
  753. SmallVector<std::pair<NodePtr, TreeNodePtr>, 8> DiscoveredEdgesToReachable;
  754. // Discover and connect nodes that became reachable with the insertion.
  755. ComputeUnreachableDominators(DT, BUI, To, From, DiscoveredEdgesToReachable);
  756. LLVM_DEBUG(dbgs() << "Inserted " << BlockNamePrinter(From)
  757. << " -> (prev unreachable) " << BlockNamePrinter(To)
  758. << "\n");
  759. // Used the discovered edges and inset discovered connecting (incoming)
  760. // edges.
  761. for (const auto &Edge : DiscoveredEdgesToReachable) {
  762. LLVM_DEBUG(dbgs() << "\tInserting discovered connecting edge "
  763. << BlockNamePrinter(Edge.first) << " -> "
  764. << BlockNamePrinter(Edge.second) << "\n");
  765. InsertReachable(DT, BUI, DT.getNode(Edge.first), Edge.second);
  766. }
  767. }
  768. // Connects nodes that become reachable with an insertion.
  769. static void ComputeUnreachableDominators(
  770. DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root,
  771. const TreeNodePtr Incoming,
  772. SmallVectorImpl<std::pair<NodePtr, TreeNodePtr>>
  773. &DiscoveredConnectingEdges) {
  774. assert(!DT.getNode(Root) && "Root must not be reachable");
  775. // Visit only previously unreachable nodes.
  776. auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](NodePtr From,
  777. NodePtr To) {
  778. const TreeNodePtr ToTN = DT.getNode(To);
  779. if (!ToTN) return true;
  780. DiscoveredConnectingEdges.push_back({From, ToTN});
  781. return false;
  782. };
  783. SemiNCAInfo SNCA(BUI);
  784. SNCA.runDFS(Root, 0, UnreachableDescender, 0);
  785. SNCA.runSemiNCA(DT);
  786. SNCA.attachNewSubtree(DT, Incoming);
  787. LLVM_DEBUG(dbgs() << "After adding unreachable nodes\n");
  788. }
  789. static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
  790. const NodePtr From, const NodePtr To) {
  791. assert(From && To && "Cannot disconnect nullptrs");
  792. LLVM_DEBUG(dbgs() << "Deleting edge " << BlockNamePrinter(From) << " -> "
  793. << BlockNamePrinter(To) << "\n");
  794. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  795. // Ensure that the edge was in fact deleted from the CFG before informing
  796. // the DomTree about it.
  797. // The check is O(N), so run it only in debug configuration.
  798. auto IsSuccessor = [BUI](const NodePtr SuccCandidate, const NodePtr Of) {
  799. auto Successors = getChildren<IsPostDom>(Of, BUI);
  800. return llvm::is_contained(Successors, SuccCandidate);
  801. };
  802. (void)IsSuccessor;
  803. assert(!IsSuccessor(To, From) && "Deleted edge still exists in the CFG!");
  804. #endif
  805. const TreeNodePtr FromTN = DT.getNode(From);
  806. // Deletion in an unreachable subtree -- nothing to do.
  807. if (!FromTN) return;
  808. const TreeNodePtr ToTN = DT.getNode(To);
  809. if (!ToTN) {
  810. LLVM_DEBUG(
  811. dbgs() << "\tTo (" << BlockNamePrinter(To)
  812. << ") already unreachable -- there is no edge to delete\n");
  813. return;
  814. }
  815. const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
  816. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  817. // If To dominates From -- nothing to do.
  818. if (ToTN != NCD) {
  819. DT.DFSInfoValid = false;
  820. const TreeNodePtr ToIDom = ToTN->getIDom();
  821. LLVM_DEBUG(dbgs() << "\tNCD " << BlockNamePrinter(NCD) << ", ToIDom "
  822. << BlockNamePrinter(ToIDom) << "\n");
  823. // To remains reachable after deletion.
  824. // (Based on the caption under Figure 4. from [2].)
  825. if (FromTN != ToIDom || HasProperSupport(DT, BUI, ToTN))
  826. DeleteReachable(DT, BUI, FromTN, ToTN);
  827. else
  828. DeleteUnreachable(DT, BUI, ToTN);
  829. }
  830. if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
  831. }
  832. // Handles deletions that leave destination nodes reachable.
  833. static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  834. const TreeNodePtr FromTN,
  835. const TreeNodePtr ToTN) {
  836. LLVM_DEBUG(dbgs() << "Deleting reachable " << BlockNamePrinter(FromTN)
  837. << " -> " << BlockNamePrinter(ToTN) << "\n");
  838. LLVM_DEBUG(dbgs() << "\tRebuilding subtree\n");
  839. // Find the top of the subtree that needs to be rebuilt.
  840. // (Based on the lemma 2.6 from [2].)
  841. const NodePtr ToIDom =
  842. DT.findNearestCommonDominator(FromTN->getBlock(), ToTN->getBlock());
  843. assert(ToIDom || DT.isPostDominator());
  844. const TreeNodePtr ToIDomTN = DT.getNode(ToIDom);
  845. assert(ToIDomTN);
  846. const TreeNodePtr PrevIDomSubTree = ToIDomTN->getIDom();
  847. // Top of the subtree to rebuild is the root node. Rebuild the tree from
  848. // scratch.
  849. if (!PrevIDomSubTree) {
  850. LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
  851. CalculateFromScratch(DT, BUI);
  852. return;
  853. }
  854. // Only visit nodes in the subtree starting at To.
  855. const unsigned Level = ToIDomTN->getLevel();
  856. auto DescendBelow = [Level, &DT](NodePtr, NodePtr To) {
  857. return DT.getNode(To)->getLevel() > Level;
  858. };
  859. LLVM_DEBUG(dbgs() << "\tTop of subtree: " << BlockNamePrinter(ToIDomTN)
  860. << "\n");
  861. SemiNCAInfo SNCA(BUI);
  862. SNCA.runDFS(ToIDom, 0, DescendBelow, 0);
  863. LLVM_DEBUG(dbgs() << "\tRunning Semi-NCA\n");
  864. SNCA.runSemiNCA(DT, Level);
  865. SNCA.reattachExistingSubtree(DT, PrevIDomSubTree);
  866. }
  867. // Checks if a node has proper support, as defined on the page 3 and later
  868. // explained on the page 7 of [2].
  869. static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI,
  870. const TreeNodePtr TN) {
  871. LLVM_DEBUG(dbgs() << "IsReachableFromIDom " << BlockNamePrinter(TN)
  872. << "\n");
  873. auto TNB = TN->getBlock();
  874. for (const NodePtr Pred : getChildren<!IsPostDom>(TNB, BUI)) {
  875. LLVM_DEBUG(dbgs() << "\tPred " << BlockNamePrinter(Pred) << "\n");
  876. if (!DT.getNode(Pred)) continue;
  877. const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
  878. LLVM_DEBUG(dbgs() << "\tSupport " << BlockNamePrinter(Support) << "\n");
  879. if (Support != TNB) {
  880. LLVM_DEBUG(dbgs() << "\t" << BlockNamePrinter(TN)
  881. << " is reachable from support "
  882. << BlockNamePrinter(Support) << "\n");
  883. return true;
  884. }
  885. }
  886. return false;
  887. }
  888. // Handle deletions that make destination node unreachable.
  889. // (Based on the lemma 2.7 from the [2].)
  890. static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  891. const TreeNodePtr ToTN) {
  892. LLVM_DEBUG(dbgs() << "Deleting unreachable subtree "
  893. << BlockNamePrinter(ToTN) << "\n");
  894. assert(ToTN);
  895. assert(ToTN->getBlock());
  896. if (IsPostDom) {
  897. // Deletion makes a region reverse-unreachable and creates a new root.
  898. // Simulate that by inserting an edge from the virtual root to ToTN and
  899. // adding it as a new root.
  900. LLVM_DEBUG(dbgs() << "\tDeletion made a region reverse-unreachable\n");
  901. LLVM_DEBUG(dbgs() << "\tAdding new root " << BlockNamePrinter(ToTN)
  902. << "\n");
  903. DT.Roots.push_back(ToTN->getBlock());
  904. InsertReachable(DT, BUI, DT.getNode(nullptr), ToTN);
  905. return;
  906. }
  907. SmallVector<NodePtr, 16> AffectedQueue;
  908. const unsigned Level = ToTN->getLevel();
  909. // Traverse destination node's descendants with greater level in the tree
  910. // and collect visited nodes.
  911. auto DescendAndCollect = [Level, &AffectedQueue, &DT](NodePtr, NodePtr To) {
  912. const TreeNodePtr TN = DT.getNode(To);
  913. assert(TN);
  914. if (TN->getLevel() > Level) return true;
  915. if (!llvm::is_contained(AffectedQueue, To))
  916. AffectedQueue.push_back(To);
  917. return false;
  918. };
  919. SemiNCAInfo SNCA(BUI);
  920. unsigned LastDFSNum =
  921. SNCA.runDFS(ToTN->getBlock(), 0, DescendAndCollect, 0);
  922. TreeNodePtr MinNode = ToTN;
  923. // Identify the top of the subtree to rebuild by finding the NCD of all
  924. // the affected nodes.
  925. for (const NodePtr N : AffectedQueue) {
  926. const TreeNodePtr TN = DT.getNode(N);
  927. const NodePtr NCDBlock =
  928. DT.findNearestCommonDominator(TN->getBlock(), ToTN->getBlock());
  929. assert(NCDBlock || DT.isPostDominator());
  930. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  931. assert(NCD);
  932. LLVM_DEBUG(dbgs() << "Processing affected node " << BlockNamePrinter(TN)
  933. << " with NCD = " << BlockNamePrinter(NCD)
  934. << ", MinNode =" << BlockNamePrinter(MinNode) << "\n");
  935. if (NCD != TN && NCD->getLevel() < MinNode->getLevel()) MinNode = NCD;
  936. }
  937. // Root reached, rebuild the whole tree from scratch.
  938. if (!MinNode->getIDom()) {
  939. LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
  940. CalculateFromScratch(DT, BUI);
  941. return;
  942. }
  943. // Erase the unreachable subtree in reverse preorder to process all children
  944. // before deleting their parent.
  945. for (unsigned i = LastDFSNum; i > 0; --i) {
  946. const NodePtr N = SNCA.NumToNode[i];
  947. const TreeNodePtr TN = DT.getNode(N);
  948. LLVM_DEBUG(dbgs() << "Erasing node " << BlockNamePrinter(TN) << "\n");
  949. EraseNode(DT, TN);
  950. }
  951. // The affected subtree start at the To node -- there's no extra work to do.
  952. if (MinNode == ToTN) return;
  953. LLVM_DEBUG(dbgs() << "DeleteUnreachable: running DFS with MinNode = "
  954. << BlockNamePrinter(MinNode) << "\n");
  955. const unsigned MinLevel = MinNode->getLevel();
  956. const TreeNodePtr PrevIDom = MinNode->getIDom();
  957. assert(PrevIDom);
  958. SNCA.clear();
  959. // Identify nodes that remain in the affected subtree.
  960. auto DescendBelow = [MinLevel, &DT](NodePtr, NodePtr To) {
  961. const TreeNodePtr ToTN = DT.getNode(To);
  962. return ToTN && ToTN->getLevel() > MinLevel;
  963. };
  964. SNCA.runDFS(MinNode->getBlock(), 0, DescendBelow, 0);
  965. LLVM_DEBUG(dbgs() << "Previous IDom(MinNode) = "
  966. << BlockNamePrinter(PrevIDom) << "\nRunning Semi-NCA\n");
  967. // Rebuild the remaining part of affected subtree.
  968. SNCA.runSemiNCA(DT, MinLevel);
  969. SNCA.reattachExistingSubtree(DT, PrevIDom);
  970. }
  971. // Removes leaf tree nodes from the dominator tree.
  972. static void EraseNode(DomTreeT &DT, const TreeNodePtr TN) {
  973. assert(TN);
  974. assert(TN->getNumChildren() == 0 && "Not a tree leaf");
  975. const TreeNodePtr IDom = TN->getIDom();
  976. assert(IDom);
  977. auto ChIt = llvm::find(IDom->Children, TN);
  978. assert(ChIt != IDom->Children.end());
  979. std::swap(*ChIt, IDom->Children.back());
  980. IDom->Children.pop_back();
  981. DT.DomTreeNodes.erase(TN->getBlock());
  982. }
  983. //~~
  984. //===--------------------- DomTree Batch Updater --------------------------===
  985. //~~
  986. static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG,
  987. GraphDiffT *PostViewCFG) {
  988. // Note: the PostViewCFG is only used when computing from scratch. It's data
  989. // should already included in the PreViewCFG for incremental updates.
  990. const size_t NumUpdates = PreViewCFG.getNumLegalizedUpdates();
  991. if (NumUpdates == 0)
  992. return;
  993. // Take the fast path for a single update and avoid running the batch update
  994. // machinery.
  995. if (NumUpdates == 1) {
  996. UpdateT Update = PreViewCFG.popUpdateForIncrementalUpdates();
  997. if (!PostViewCFG) {
  998. if (Update.getKind() == UpdateKind::Insert)
  999. InsertEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
  1000. else
  1001. DeleteEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
  1002. } else {
  1003. BatchUpdateInfo BUI(*PostViewCFG, PostViewCFG);
  1004. if (Update.getKind() == UpdateKind::Insert)
  1005. InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
  1006. else
  1007. DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
  1008. }
  1009. return;
  1010. }
  1011. BatchUpdateInfo BUI(PreViewCFG, PostViewCFG);
  1012. // Recalculate the DominatorTree when the number of updates
  1013. // exceeds a threshold, which usually makes direct updating slower than
  1014. // recalculation. We select this threshold proportional to the
  1015. // size of the DominatorTree. The constant is selected
  1016. // by choosing the one with an acceptable performance on some real-world
  1017. // inputs.
  1018. // Make unittests of the incremental algorithm work
  1019. if (DT.DomTreeNodes.size() <= 100) {
  1020. if (BUI.NumLegalized > DT.DomTreeNodes.size())
  1021. CalculateFromScratch(DT, &BUI);
  1022. } else if (BUI.NumLegalized > DT.DomTreeNodes.size() / 40)
  1023. CalculateFromScratch(DT, &BUI);
  1024. // If the DominatorTree was recalculated at some point, stop the batch
  1025. // updates. Full recalculations ignore batch updates and look at the actual
  1026. // CFG.
  1027. for (size_t i = 0; i < BUI.NumLegalized && !BUI.IsRecalculated; ++i)
  1028. ApplyNextUpdate(DT, BUI);
  1029. }
  1030. static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI) {
  1031. // Popping the next update, will move the PreViewCFG to the next snapshot.
  1032. UpdateT CurrentUpdate = BUI.PreViewCFG.popUpdateForIncrementalUpdates();
  1033. #if 0
  1034. // FIXME: The LLVM_DEBUG macro only plays well with a modular
  1035. // build of LLVM when the header is marked as textual, but doing
  1036. // so causes redefinition errors.
  1037. LLVM_DEBUG(dbgs() << "Applying update: ");
  1038. LLVM_DEBUG(CurrentUpdate.dump(); dbgs() << "\n");
  1039. #endif
  1040. if (CurrentUpdate.getKind() == UpdateKind::Insert)
  1041. InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
  1042. else
  1043. DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
  1044. }
  1045. //~~
  1046. //===--------------- DomTree correctness verification ---------------------===
  1047. //~~
  1048. // Check if the tree has correct roots. A DominatorTree always has a single
  1049. // root which is the function's entry node. A PostDominatorTree can have
  1050. // multiple roots - one for each node with no successors and for infinite
  1051. // loops.
  1052. // Running time: O(N).
  1053. bool verifyRoots(const DomTreeT &DT) {
  1054. if (!DT.Parent && !DT.Roots.empty()) {
  1055. errs() << "Tree has no parent but has roots!\n";
  1056. errs().flush();
  1057. return false;
  1058. }
  1059. if (!IsPostDom) {
  1060. if (DT.Roots.empty()) {
  1061. errs() << "Tree doesn't have a root!\n";
  1062. errs().flush();
  1063. return false;
  1064. }
  1065. if (DT.getRoot() != GetEntryNode(DT)) {
  1066. errs() << "Tree's root is not its parent's entry node!\n";
  1067. errs().flush();
  1068. return false;
  1069. }
  1070. }
  1071. RootsT ComputedRoots = FindRoots(DT, nullptr);
  1072. if (!isPermutation(DT.Roots, ComputedRoots)) {
  1073. errs() << "Tree has different roots than freshly computed ones!\n";
  1074. errs() << "\tPDT roots: ";
  1075. for (const NodePtr N : DT.Roots) errs() << BlockNamePrinter(N) << ", ";
  1076. errs() << "\n\tComputed roots: ";
  1077. for (const NodePtr N : ComputedRoots)
  1078. errs() << BlockNamePrinter(N) << ", ";
  1079. errs() << "\n";
  1080. errs().flush();
  1081. return false;
  1082. }
  1083. return true;
  1084. }
  1085. // Checks if the tree contains all reachable nodes in the input graph.
  1086. // Running time: O(N).
  1087. bool verifyReachability(const DomTreeT &DT) {
  1088. clear();
  1089. doFullDFSWalk(DT, AlwaysDescend);
  1090. for (auto &NodeToTN : DT.DomTreeNodes) {
  1091. const TreeNodePtr TN = NodeToTN.second.get();
  1092. const NodePtr BB = TN->getBlock();
  1093. // Virtual root has a corresponding virtual CFG node.
  1094. if (DT.isVirtualRoot(TN)) continue;
  1095. if (NodeToInfo.count(BB) == 0) {
  1096. errs() << "DomTree node " << BlockNamePrinter(BB)
  1097. << " not found by DFS walk!\n";
  1098. errs().flush();
  1099. return false;
  1100. }
  1101. }
  1102. for (const NodePtr N : NumToNode) {
  1103. if (N && !DT.getNode(N)) {
  1104. errs() << "CFG node " << BlockNamePrinter(N)
  1105. << " not found in the DomTree!\n";
  1106. errs().flush();
  1107. return false;
  1108. }
  1109. }
  1110. return true;
  1111. }
  1112. // Check if for every parent with a level L in the tree all of its children
  1113. // have level L + 1.
  1114. // Running time: O(N).
  1115. static bool VerifyLevels(const DomTreeT &DT) {
  1116. for (auto &NodeToTN : DT.DomTreeNodes) {
  1117. const TreeNodePtr TN = NodeToTN.second.get();
  1118. const NodePtr BB = TN->getBlock();
  1119. if (!BB) continue;
  1120. const TreeNodePtr IDom = TN->getIDom();
  1121. if (!IDom && TN->getLevel() != 0) {
  1122. errs() << "Node without an IDom " << BlockNamePrinter(BB)
  1123. << " has a nonzero level " << TN->getLevel() << "!\n";
  1124. errs().flush();
  1125. return false;
  1126. }
  1127. if (IDom && TN->getLevel() != IDom->getLevel() + 1) {
  1128. errs() << "Node " << BlockNamePrinter(BB) << " has level "
  1129. << TN->getLevel() << " while its IDom "
  1130. << BlockNamePrinter(IDom->getBlock()) << " has level "
  1131. << IDom->getLevel() << "!\n";
  1132. errs().flush();
  1133. return false;
  1134. }
  1135. }
  1136. return true;
  1137. }
  1138. // Check if the computed DFS numbers are correct. Note that DFS info may not
  1139. // be valid, and when that is the case, we don't verify the numbers.
  1140. // Running time: O(N log(N)).
  1141. static bool VerifyDFSNumbers(const DomTreeT &DT) {
  1142. if (!DT.DFSInfoValid || !DT.Parent)
  1143. return true;
  1144. const NodePtr RootBB = IsPostDom ? nullptr : *DT.root_begin();
  1145. const TreeNodePtr Root = DT.getNode(RootBB);
  1146. auto PrintNodeAndDFSNums = [](const TreeNodePtr TN) {
  1147. errs() << BlockNamePrinter(TN) << " {" << TN->getDFSNumIn() << ", "
  1148. << TN->getDFSNumOut() << '}';
  1149. };
  1150. // Verify the root's DFS In number. Although DFS numbering would also work
  1151. // if we started from some other value, we assume 0-based numbering.
  1152. if (Root->getDFSNumIn() != 0) {
  1153. errs() << "DFSIn number for the tree root is not:\n\t";
  1154. PrintNodeAndDFSNums(Root);
  1155. errs() << '\n';
  1156. errs().flush();
  1157. return false;
  1158. }
  1159. // For each tree node verify if children's DFS numbers cover their parent's
  1160. // DFS numbers with no gaps.
  1161. for (const auto &NodeToTN : DT.DomTreeNodes) {
  1162. const TreeNodePtr Node = NodeToTN.second.get();
  1163. // Handle tree leaves.
  1164. if (Node->isLeaf()) {
  1165. if (Node->getDFSNumIn() + 1 != Node->getDFSNumOut()) {
  1166. errs() << "Tree leaf should have DFSOut = DFSIn + 1:\n\t";
  1167. PrintNodeAndDFSNums(Node);
  1168. errs() << '\n';
  1169. errs().flush();
  1170. return false;
  1171. }
  1172. continue;
  1173. }
  1174. // Make a copy and sort it such that it is possible to check if there are
  1175. // no gaps between DFS numbers of adjacent children.
  1176. SmallVector<TreeNodePtr, 8> Children(Node->begin(), Node->end());
  1177. llvm::sort(Children, [](const TreeNodePtr Ch1, const TreeNodePtr Ch2) {
  1178. return Ch1->getDFSNumIn() < Ch2->getDFSNumIn();
  1179. });
  1180. auto PrintChildrenError = [Node, &Children, PrintNodeAndDFSNums](
  1181. const TreeNodePtr FirstCh, const TreeNodePtr SecondCh) {
  1182. assert(FirstCh);
  1183. errs() << "Incorrect DFS numbers for:\n\tParent ";
  1184. PrintNodeAndDFSNums(Node);
  1185. errs() << "\n\tChild ";
  1186. PrintNodeAndDFSNums(FirstCh);
  1187. if (SecondCh) {
  1188. errs() << "\n\tSecond child ";
  1189. PrintNodeAndDFSNums(SecondCh);
  1190. }
  1191. errs() << "\nAll children: ";
  1192. for (const TreeNodePtr Ch : Children) {
  1193. PrintNodeAndDFSNums(Ch);
  1194. errs() << ", ";
  1195. }
  1196. errs() << '\n';
  1197. errs().flush();
  1198. };
  1199. if (Children.front()->getDFSNumIn() != Node->getDFSNumIn() + 1) {
  1200. PrintChildrenError(Children.front(), nullptr);
  1201. return false;
  1202. }
  1203. if (Children.back()->getDFSNumOut() + 1 != Node->getDFSNumOut()) {
  1204. PrintChildrenError(Children.back(), nullptr);
  1205. return false;
  1206. }
  1207. for (size_t i = 0, e = Children.size() - 1; i != e; ++i) {
  1208. if (Children[i]->getDFSNumOut() + 1 != Children[i + 1]->getDFSNumIn()) {
  1209. PrintChildrenError(Children[i], Children[i + 1]);
  1210. return false;
  1211. }
  1212. }
  1213. }
  1214. return true;
  1215. }
  1216. // The below routines verify the correctness of the dominator tree relative to
  1217. // the CFG it's coming from. A tree is a dominator tree iff it has two
  1218. // properties, called the parent property and the sibling property. Tarjan
  1219. // and Lengauer prove (but don't explicitly name) the properties as part of
  1220. // the proofs in their 1972 paper, but the proofs are mostly part of proving
  1221. // things about semidominators and idoms, and some of them are simply asserted
  1222. // based on even earlier papers (see, e.g., lemma 2). Some papers refer to
  1223. // these properties as "valid" and "co-valid". See, e.g., "Dominators,
  1224. // directed bipolar orders, and independent spanning trees" by Loukas
  1225. // Georgiadis and Robert E. Tarjan, as well as "Dominator Tree Verification
  1226. // and Vertex-Disjoint Paths " by the same authors.
  1227. // A very simple and direct explanation of these properties can be found in
  1228. // "An Experimental Study of Dynamic Dominators", found at
  1229. // https://arxiv.org/abs/1604.02711
  1230. // The easiest way to think of the parent property is that it's a requirement
  1231. // of being a dominator. Let's just take immediate dominators. For PARENT to
  1232. // be an immediate dominator of CHILD, all paths in the CFG must go through
  1233. // PARENT before they hit CHILD. This implies that if you were to cut PARENT
  1234. // out of the CFG, there should be no paths to CHILD that are reachable. If
  1235. // there are, then you now have a path from PARENT to CHILD that goes around
  1236. // PARENT and still reaches CHILD, which by definition, means PARENT can't be
  1237. // a dominator of CHILD (let alone an immediate one).
  1238. // The sibling property is similar. It says that for each pair of sibling
  1239. // nodes in the dominator tree (LEFT and RIGHT) , they must not dominate each
  1240. // other. If sibling LEFT dominated sibling RIGHT, it means there are no
  1241. // paths in the CFG from sibling LEFT to sibling RIGHT that do not go through
  1242. // LEFT, and thus, LEFT is really an ancestor (in the dominator tree) of
  1243. // RIGHT, not a sibling.
  1244. // It is possible to verify the parent and sibling properties in linear time,
  1245. // but the algorithms are complex. Instead, we do it in a straightforward
  1246. // N^2 and N^3 way below, using direct path reachability.
  1247. // Checks if the tree has the parent property: if for all edges from V to W in
  1248. // the input graph, such that V is reachable, the parent of W in the tree is
  1249. // an ancestor of V in the tree.
  1250. // Running time: O(N^2).
  1251. //
  1252. // This means that if a node gets disconnected from the graph, then all of
  1253. // the nodes it dominated previously will now become unreachable.
  1254. bool verifyParentProperty(const DomTreeT &DT) {
  1255. for (auto &NodeToTN : DT.DomTreeNodes) {
  1256. const TreeNodePtr TN = NodeToTN.second.get();
  1257. const NodePtr BB = TN->getBlock();
  1258. if (!BB || TN->isLeaf())
  1259. continue;
  1260. LLVM_DEBUG(dbgs() << "Verifying parent property of node "
  1261. << BlockNamePrinter(TN) << "\n");
  1262. clear();
  1263. doFullDFSWalk(DT, [BB](NodePtr From, NodePtr To) {
  1264. return From != BB && To != BB;
  1265. });
  1266. for (TreeNodePtr Child : TN->children())
  1267. if (NodeToInfo.count(Child->getBlock()) != 0) {
  1268. errs() << "Child " << BlockNamePrinter(Child)
  1269. << " reachable after its parent " << BlockNamePrinter(BB)
  1270. << " is removed!\n";
  1271. errs().flush();
  1272. return false;
  1273. }
  1274. }
  1275. return true;
  1276. }
  1277. // Check if the tree has sibling property: if a node V does not dominate a
  1278. // node W for all siblings V and W in the tree.
  1279. // Running time: O(N^3).
  1280. //
  1281. // This means that if a node gets disconnected from the graph, then all of its
  1282. // siblings will now still be reachable.
  1283. bool verifySiblingProperty(const DomTreeT &DT) {
  1284. for (auto &NodeToTN : DT.DomTreeNodes) {
  1285. const TreeNodePtr TN = NodeToTN.second.get();
  1286. const NodePtr BB = TN->getBlock();
  1287. if (!BB || TN->isLeaf())
  1288. continue;
  1289. for (const TreeNodePtr N : TN->children()) {
  1290. clear();
  1291. NodePtr BBN = N->getBlock();
  1292. doFullDFSWalk(DT, [BBN](NodePtr From, NodePtr To) {
  1293. return From != BBN && To != BBN;
  1294. });
  1295. for (const TreeNodePtr S : TN->children()) {
  1296. if (S == N) continue;
  1297. if (NodeToInfo.count(S->getBlock()) == 0) {
  1298. errs() << "Node " << BlockNamePrinter(S)
  1299. << " not reachable when its sibling " << BlockNamePrinter(N)
  1300. << " is removed!\n";
  1301. errs().flush();
  1302. return false;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. return true;
  1308. }
  1309. // Check if the given tree is the same as a freshly computed one for the same
  1310. // Parent.
  1311. // Running time: O(N^2), but faster in practice (same as tree construction).
  1312. //
  1313. // Note that this does not check if that the tree construction algorithm is
  1314. // correct and should be only used for fast (but possibly unsound)
  1315. // verification.
  1316. static bool IsSameAsFreshTree(const DomTreeT &DT) {
  1317. DomTreeT FreshTree;
  1318. FreshTree.recalculate(*DT.Parent);
  1319. const bool Different = DT.compare(FreshTree);
  1320. if (Different) {
  1321. errs() << (DT.isPostDominator() ? "Post" : "")
  1322. << "DominatorTree is different than a freshly computed one!\n"
  1323. << "\tCurrent:\n";
  1324. DT.print(errs());
  1325. errs() << "\n\tFreshly computed tree:\n";
  1326. FreshTree.print(errs());
  1327. errs().flush();
  1328. }
  1329. return !Different;
  1330. }
  1331. };
  1332. template <class DomTreeT>
  1333. void Calculate(DomTreeT &DT) {
  1334. SemiNCAInfo<DomTreeT>::CalculateFromScratch(DT, nullptr);
  1335. }
  1336. template <typename DomTreeT>
  1337. void CalculateWithUpdates(DomTreeT &DT,
  1338. ArrayRef<typename DomTreeT::UpdateType> Updates) {
  1339. // FIXME: Updated to use the PreViewCFG and behave the same as until now.
  1340. // This behavior is however incorrect; this actually needs the PostViewCFG.
  1341. GraphDiff<typename DomTreeT::NodePtr, DomTreeT::IsPostDominator> PreViewCFG(
  1342. Updates, /*ReverseApplyUpdates=*/true);
  1343. typename SemiNCAInfo<DomTreeT>::BatchUpdateInfo BUI(PreViewCFG);
  1344. SemiNCAInfo<DomTreeT>::CalculateFromScratch(DT, &BUI);
  1345. }
  1346. template <class DomTreeT>
  1347. void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  1348. typename DomTreeT::NodePtr To) {
  1349. if (DT.isPostDominator()) std::swap(From, To);
  1350. SemiNCAInfo<DomTreeT>::InsertEdge(DT, nullptr, From, To);
  1351. }
  1352. template <class DomTreeT>
  1353. void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  1354. typename DomTreeT::NodePtr To) {
  1355. if (DT.isPostDominator()) std::swap(From, To);
  1356. SemiNCAInfo<DomTreeT>::DeleteEdge(DT, nullptr, From, To);
  1357. }
  1358. template <class DomTreeT>
  1359. void ApplyUpdates(DomTreeT &DT,
  1360. GraphDiff<typename DomTreeT::NodePtr,
  1361. DomTreeT::IsPostDominator> &PreViewCFG,
  1362. GraphDiff<typename DomTreeT::NodePtr,
  1363. DomTreeT::IsPostDominator> *PostViewCFG) {
  1364. SemiNCAInfo<DomTreeT>::ApplyUpdates(DT, PreViewCFG, PostViewCFG);
  1365. }
  1366. template <class DomTreeT>
  1367. bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL) {
  1368. SemiNCAInfo<DomTreeT> SNCA(nullptr);
  1369. // Simplist check is to compare against a new tree. This will also
  1370. // usefully print the old and new trees, if they are different.
  1371. if (!SNCA.IsSameAsFreshTree(DT))
  1372. return false;
  1373. // Common checks to verify the properties of the tree. O(N log N) at worst.
  1374. if (!SNCA.verifyRoots(DT) || !SNCA.verifyReachability(DT) ||
  1375. !SNCA.VerifyLevels(DT) || !SNCA.VerifyDFSNumbers(DT))
  1376. return false;
  1377. // Extra checks depending on VerificationLevel. Up to O(N^3).
  1378. if (VL == DomTreeT::VerificationLevel::Basic ||
  1379. VL == DomTreeT::VerificationLevel::Full)
  1380. if (!SNCA.verifyParentProperty(DT))
  1381. return false;
  1382. if (VL == DomTreeT::VerificationLevel::Full)
  1383. if (!SNCA.verifySiblingProperty(DT))
  1384. return false;
  1385. return true;
  1386. }
  1387. } // namespace DomTreeBuilder
  1388. } // namespace llvm
  1389. #undef DEBUG_TYPE
  1390. #endif
  1391. #ifdef __GNUC__
  1392. #pragma GCC diagnostic pop
  1393. #endif