DependenceGraphBuilder.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. //===- DependenceGraphBuilder.cpp ------------------------------------------==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // This file implements common steps of the build algorithm for construction
  9. // of dependence graphs such as DDG and PDG.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/Analysis/DependenceGraphBuilder.h"
  12. #include "llvm/ADT/DepthFirstIterator.h"
  13. #include "llvm/ADT/EnumeratedArray.h"
  14. #include "llvm/ADT/SCCIterator.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Analysis/DDG.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "dgb"
  19. STATISTIC(TotalGraphs, "Number of dependence graphs created.");
  20. STATISTIC(TotalDefUseEdges, "Number of def-use edges created.");
  21. STATISTIC(TotalMemoryEdges, "Number of memory dependence edges created.");
  22. STATISTIC(TotalFineGrainedNodes, "Number of fine-grained nodes created.");
  23. STATISTIC(TotalPiBlockNodes, "Number of pi-block nodes created.");
  24. STATISTIC(TotalConfusedEdges,
  25. "Number of confused memory dependencies between two nodes.");
  26. STATISTIC(TotalEdgeReversals,
  27. "Number of times the source and sink of dependence was reversed to "
  28. "expose cycles in the graph.");
  29. using InstructionListType = SmallVector<Instruction *, 2>;
  30. //===--------------------------------------------------------------------===//
  31. // AbstractDependenceGraphBuilder implementation
  32. //===--------------------------------------------------------------------===//
  33. template <class G>
  34. void AbstractDependenceGraphBuilder<G>::computeInstructionOrdinals() {
  35. // The BBList is expected to be in program order.
  36. size_t NextOrdinal = 1;
  37. for (auto *BB : BBList)
  38. for (auto &I : *BB)
  39. InstOrdinalMap.insert(std::make_pair(&I, NextOrdinal++));
  40. }
  41. template <class G>
  42. void AbstractDependenceGraphBuilder<G>::createFineGrainedNodes() {
  43. ++TotalGraphs;
  44. assert(IMap.empty() && "Expected empty instruction map at start");
  45. for (BasicBlock *BB : BBList)
  46. for (Instruction &I : *BB) {
  47. auto &NewNode = createFineGrainedNode(I);
  48. IMap.insert(std::make_pair(&I, &NewNode));
  49. NodeOrdinalMap.insert(std::make_pair(&NewNode, getOrdinal(I)));
  50. ++TotalFineGrainedNodes;
  51. }
  52. }
  53. template <class G>
  54. void AbstractDependenceGraphBuilder<G>::createAndConnectRootNode() {
  55. // Create a root node that connects to every connected component of the graph.
  56. // This is done to allow graph iterators to visit all the disjoint components
  57. // of the graph, in a single walk.
  58. //
  59. // This algorithm works by going through each node of the graph and for each
  60. // node N, do a DFS starting from N. A rooted edge is established between the
  61. // root node and N (if N is not yet visited). All the nodes reachable from N
  62. // are marked as visited and are skipped in the DFS of subsequent nodes.
  63. //
  64. // Note: This algorithm tries to limit the number of edges out of the root
  65. // node to some extent, but there may be redundant edges created depending on
  66. // the iteration order. For example for a graph {A -> B}, an edge from the
  67. // root node is added to both nodes if B is visited before A. While it does
  68. // not result in minimal number of edges, this approach saves compile-time
  69. // while keeping the number of edges in check.
  70. auto &RootNode = createRootNode();
  71. df_iterator_default_set<const NodeType *, 4> Visited;
  72. for (auto *N : Graph) {
  73. if (*N == RootNode)
  74. continue;
  75. for (auto I : depth_first_ext(N, Visited))
  76. if (I == N)
  77. createRootedEdge(RootNode, *N);
  78. }
  79. }
  80. template <class G> void AbstractDependenceGraphBuilder<G>::createPiBlocks() {
  81. if (!shouldCreatePiBlocks())
  82. return;
  83. LLVM_DEBUG(dbgs() << "==== Start of Creation of Pi-Blocks ===\n");
  84. // The overall algorithm is as follows:
  85. // 1. Identify SCCs and for each SCC create a pi-block node containing all
  86. // the nodes in that SCC.
  87. // 2. Identify incoming edges incident to the nodes inside of the SCC and
  88. // reconnect them to the pi-block node.
  89. // 3. Identify outgoing edges from the nodes inside of the SCC to nodes
  90. // outside of it and reconnect them so that the edges are coming out of the
  91. // SCC node instead.
  92. // Adding nodes as we iterate through the SCCs cause the SCC
  93. // iterators to get invalidated. To prevent this invalidation, we first
  94. // collect a list of nodes that are part of an SCC, and then iterate over
  95. // those lists to create the pi-block nodes. Each element of the list is a
  96. // list of nodes in an SCC. Note: trivial SCCs containing a single node are
  97. // ignored.
  98. SmallVector<NodeListType, 4> ListOfSCCs;
  99. for (auto &SCC : make_range(scc_begin(&Graph), scc_end(&Graph))) {
  100. if (SCC.size() > 1)
  101. ListOfSCCs.emplace_back(SCC.begin(), SCC.end());
  102. }
  103. for (NodeListType &NL : ListOfSCCs) {
  104. LLVM_DEBUG(dbgs() << "Creating pi-block node with " << NL.size()
  105. << " nodes in it.\n");
  106. // SCC iterator may put the nodes in an order that's different from the
  107. // program order. To preserve original program order, we sort the list of
  108. // nodes based on ordinal numbers computed earlier.
  109. llvm::sort(NL, [&](NodeType *LHS, NodeType *RHS) {
  110. return getOrdinal(*LHS) < getOrdinal(*RHS);
  111. });
  112. NodeType &PiNode = createPiBlock(NL);
  113. ++TotalPiBlockNodes;
  114. // Build a set to speed up the lookup for edges whose targets
  115. // are inside the SCC.
  116. SmallPtrSet<NodeType *, 4> NodesInSCC(NL.begin(), NL.end());
  117. // We have the set of nodes in the SCC. We go through the set of nodes
  118. // that are outside of the SCC and look for edges that cross the two sets.
  119. for (NodeType *N : Graph) {
  120. // Skip the SCC node and all the nodes inside of it.
  121. if (*N == PiNode || NodesInSCC.count(N))
  122. continue;
  123. enum Direction {
  124. Incoming, // Incoming edges to the SCC
  125. Outgoing, // Edges going ot of the SCC
  126. DirectionCount // To make the enum usable as an array index.
  127. };
  128. // Use these flags to help us avoid creating redundant edges. If there
  129. // are more than one edges from an outside node to inside nodes, we only
  130. // keep one edge from that node to the pi-block node. Similarly, if
  131. // there are more than one edges from inside nodes to an outside node,
  132. // we only keep one edge from the pi-block node to the outside node.
  133. // There is a flag defined for each direction (incoming vs outgoing) and
  134. // for each type of edge supported, using a two-dimensional boolean
  135. // array.
  136. using EdgeKind = typename EdgeType::EdgeKind;
  137. EnumeratedArray<bool, EdgeKind> EdgeAlreadyCreated[DirectionCount]{false,
  138. false};
  139. auto createEdgeOfKind = [this](NodeType &Src, NodeType &Dst,
  140. const EdgeKind K) {
  141. switch (K) {
  142. case EdgeKind::RegisterDefUse:
  143. createDefUseEdge(Src, Dst);
  144. break;
  145. case EdgeKind::MemoryDependence:
  146. createMemoryEdge(Src, Dst);
  147. break;
  148. case EdgeKind::Rooted:
  149. createRootedEdge(Src, Dst);
  150. break;
  151. default:
  152. llvm_unreachable("Unsupported type of edge.");
  153. }
  154. };
  155. auto reconnectEdges = [&](NodeType *Src, NodeType *Dst, NodeType *New,
  156. const Direction Dir) {
  157. if (!Src->hasEdgeTo(*Dst))
  158. return;
  159. LLVM_DEBUG(
  160. dbgs() << "reconnecting("
  161. << (Dir == Direction::Incoming ? "incoming)" : "outgoing)")
  162. << ":\nSrc:" << *Src << "\nDst:" << *Dst << "\nNew:" << *New
  163. << "\n");
  164. assert((Dir == Direction::Incoming || Dir == Direction::Outgoing) &&
  165. "Invalid direction.");
  166. SmallVector<EdgeType *, 10> EL;
  167. Src->findEdgesTo(*Dst, EL);
  168. for (EdgeType *OldEdge : EL) {
  169. EdgeKind Kind = OldEdge->getKind();
  170. if (!EdgeAlreadyCreated[Dir][Kind]) {
  171. if (Dir == Direction::Incoming) {
  172. createEdgeOfKind(*Src, *New, Kind);
  173. LLVM_DEBUG(dbgs() << "created edge from Src to New.\n");
  174. } else if (Dir == Direction::Outgoing) {
  175. createEdgeOfKind(*New, *Dst, Kind);
  176. LLVM_DEBUG(dbgs() << "created edge from New to Dst.\n");
  177. }
  178. EdgeAlreadyCreated[Dir][Kind] = true;
  179. }
  180. Src->removeEdge(*OldEdge);
  181. destroyEdge(*OldEdge);
  182. LLVM_DEBUG(dbgs() << "removed old edge between Src and Dst.\n\n");
  183. }
  184. };
  185. for (NodeType *SCCNode : NL) {
  186. // Process incoming edges incident to the pi-block node.
  187. reconnectEdges(N, SCCNode, &PiNode, Direction::Incoming);
  188. // Process edges that are coming out of the pi-block node.
  189. reconnectEdges(SCCNode, N, &PiNode, Direction::Outgoing);
  190. }
  191. }
  192. }
  193. // Ordinal maps are no longer needed.
  194. InstOrdinalMap.clear();
  195. NodeOrdinalMap.clear();
  196. LLVM_DEBUG(dbgs() << "==== End of Creation of Pi-Blocks ===\n");
  197. }
  198. template <class G> void AbstractDependenceGraphBuilder<G>::createDefUseEdges() {
  199. for (NodeType *N : Graph) {
  200. InstructionListType SrcIList;
  201. N->collectInstructions([](const Instruction *I) { return true; }, SrcIList);
  202. // Use a set to mark the targets that we link to N, so we don't add
  203. // duplicate def-use edges when more than one instruction in a target node
  204. // use results of instructions that are contained in N.
  205. SmallPtrSet<NodeType *, 4> VisitedTargets;
  206. for (Instruction *II : SrcIList) {
  207. for (User *U : II->users()) {
  208. Instruction *UI = dyn_cast<Instruction>(U);
  209. if (!UI)
  210. continue;
  211. NodeType *DstNode = nullptr;
  212. if (IMap.find(UI) != IMap.end())
  213. DstNode = IMap.find(UI)->second;
  214. // In the case of loops, the scope of the subgraph is all the
  215. // basic blocks (and instructions within them) belonging to the loop. We
  216. // simply ignore all the edges coming from (or going into) instructions
  217. // or basic blocks outside of this range.
  218. if (!DstNode) {
  219. LLVM_DEBUG(
  220. dbgs()
  221. << "skipped def-use edge since the sink" << *UI
  222. << " is outside the range of instructions being considered.\n");
  223. continue;
  224. }
  225. // Self dependencies are ignored because they are redundant and
  226. // uninteresting.
  227. if (DstNode == N) {
  228. LLVM_DEBUG(dbgs()
  229. << "skipped def-use edge since the sink and the source ("
  230. << N << ") are the same.\n");
  231. continue;
  232. }
  233. if (VisitedTargets.insert(DstNode).second) {
  234. createDefUseEdge(*N, *DstNode);
  235. ++TotalDefUseEdges;
  236. }
  237. }
  238. }
  239. }
  240. }
  241. template <class G>
  242. void AbstractDependenceGraphBuilder<G>::createMemoryDependencyEdges() {
  243. using DGIterator = typename G::iterator;
  244. auto isMemoryAccess = [](const Instruction *I) {
  245. return I->mayReadOrWriteMemory();
  246. };
  247. for (DGIterator SrcIt = Graph.begin(), E = Graph.end(); SrcIt != E; ++SrcIt) {
  248. InstructionListType SrcIList;
  249. (*SrcIt)->collectInstructions(isMemoryAccess, SrcIList);
  250. if (SrcIList.empty())
  251. continue;
  252. for (DGIterator DstIt = SrcIt; DstIt != E; ++DstIt) {
  253. if (**SrcIt == **DstIt)
  254. continue;
  255. InstructionListType DstIList;
  256. (*DstIt)->collectInstructions(isMemoryAccess, DstIList);
  257. if (DstIList.empty())
  258. continue;
  259. bool ForwardEdgeCreated = false;
  260. bool BackwardEdgeCreated = false;
  261. for (Instruction *ISrc : SrcIList) {
  262. for (Instruction *IDst : DstIList) {
  263. auto D = DI.depends(ISrc, IDst, true);
  264. if (!D)
  265. continue;
  266. // If we have a dependence with its left-most non-'=' direction
  267. // being '>' we need to reverse the direction of the edge, because
  268. // the source of the dependence cannot occur after the sink. For
  269. // confused dependencies, we will create edges in both directions to
  270. // represent the possibility of a cycle.
  271. auto createConfusedEdges = [&](NodeType &Src, NodeType &Dst) {
  272. if (!ForwardEdgeCreated) {
  273. createMemoryEdge(Src, Dst);
  274. ++TotalMemoryEdges;
  275. }
  276. if (!BackwardEdgeCreated) {
  277. createMemoryEdge(Dst, Src);
  278. ++TotalMemoryEdges;
  279. }
  280. ForwardEdgeCreated = BackwardEdgeCreated = true;
  281. ++TotalConfusedEdges;
  282. };
  283. auto createForwardEdge = [&](NodeType &Src, NodeType &Dst) {
  284. if (!ForwardEdgeCreated) {
  285. createMemoryEdge(Src, Dst);
  286. ++TotalMemoryEdges;
  287. }
  288. ForwardEdgeCreated = true;
  289. };
  290. auto createBackwardEdge = [&](NodeType &Src, NodeType &Dst) {
  291. if (!BackwardEdgeCreated) {
  292. createMemoryEdge(Dst, Src);
  293. ++TotalMemoryEdges;
  294. }
  295. BackwardEdgeCreated = true;
  296. };
  297. if (D->isConfused())
  298. createConfusedEdges(**SrcIt, **DstIt);
  299. else if (D->isOrdered() && !D->isLoopIndependent()) {
  300. bool ReversedEdge = false;
  301. for (unsigned Level = 1; Level <= D->getLevels(); ++Level) {
  302. if (D->getDirection(Level) == Dependence::DVEntry::EQ)
  303. continue;
  304. else if (D->getDirection(Level) == Dependence::DVEntry::GT) {
  305. createBackwardEdge(**SrcIt, **DstIt);
  306. ReversedEdge = true;
  307. ++TotalEdgeReversals;
  308. break;
  309. } else if (D->getDirection(Level) == Dependence::DVEntry::LT)
  310. break;
  311. else {
  312. createConfusedEdges(**SrcIt, **DstIt);
  313. break;
  314. }
  315. }
  316. if (!ReversedEdge)
  317. createForwardEdge(**SrcIt, **DstIt);
  318. } else
  319. createForwardEdge(**SrcIt, **DstIt);
  320. // Avoid creating duplicate edges.
  321. if (ForwardEdgeCreated && BackwardEdgeCreated)
  322. break;
  323. }
  324. // If we've created edges in both directions, there is no more
  325. // unique edge that we can create between these two nodes, so we
  326. // can exit early.
  327. if (ForwardEdgeCreated && BackwardEdgeCreated)
  328. break;
  329. }
  330. }
  331. }
  332. }
  333. template <class G> void AbstractDependenceGraphBuilder<G>::simplify() {
  334. if (!shouldSimplify())
  335. return;
  336. LLVM_DEBUG(dbgs() << "==== Start of Graph Simplification ===\n");
  337. // This algorithm works by first collecting a set of candidate nodes that have
  338. // an out-degree of one (in terms of def-use edges), and then ignoring those
  339. // whose targets have an in-degree more than one. Each node in the resulting
  340. // set can then be merged with its corresponding target and put back into the
  341. // worklist until no further merge candidates are available.
  342. SmallPtrSet<NodeType *, 32> CandidateSourceNodes;
  343. // A mapping between nodes and their in-degree. To save space, this map
  344. // only contains nodes that are targets of nodes in the CandidateSourceNodes.
  345. DenseMap<NodeType *, unsigned> TargetInDegreeMap;
  346. for (NodeType *N : Graph) {
  347. if (N->getEdges().size() != 1)
  348. continue;
  349. EdgeType &Edge = N->back();
  350. if (!Edge.isDefUse())
  351. continue;
  352. CandidateSourceNodes.insert(N);
  353. // Insert an element into the in-degree map and initialize to zero. The
  354. // count will get updated in the next step.
  355. TargetInDegreeMap.insert({&Edge.getTargetNode(), 0});
  356. }
  357. LLVM_DEBUG({
  358. dbgs() << "Size of candidate src node list:" << CandidateSourceNodes.size()
  359. << "\nNode with single outgoing def-use edge:\n";
  360. for (NodeType *N : CandidateSourceNodes) {
  361. dbgs() << N << "\n";
  362. }
  363. });
  364. for (NodeType *N : Graph) {
  365. for (EdgeType *E : *N) {
  366. NodeType *Tgt = &E->getTargetNode();
  367. auto TgtIT = TargetInDegreeMap.find(Tgt);
  368. if (TgtIT != TargetInDegreeMap.end())
  369. ++(TgtIT->second);
  370. }
  371. }
  372. LLVM_DEBUG({
  373. dbgs() << "Size of target in-degree map:" << TargetInDegreeMap.size()
  374. << "\nContent of in-degree map:\n";
  375. for (auto &I : TargetInDegreeMap) {
  376. dbgs() << I.first << " --> " << I.second << "\n";
  377. }
  378. });
  379. SmallVector<NodeType *, 32> Worklist(CandidateSourceNodes.begin(),
  380. CandidateSourceNodes.end());
  381. while (!Worklist.empty()) {
  382. NodeType &Src = *Worklist.pop_back_val();
  383. // As nodes get merged, we need to skip any node that has been removed from
  384. // the candidate set (see below).
  385. if (!CandidateSourceNodes.erase(&Src))
  386. continue;
  387. assert(Src.getEdges().size() == 1 &&
  388. "Expected a single edge from the candidate src node.");
  389. NodeType &Tgt = Src.back().getTargetNode();
  390. assert(TargetInDegreeMap.find(&Tgt) != TargetInDegreeMap.end() &&
  391. "Expected target to be in the in-degree map.");
  392. if (TargetInDegreeMap[&Tgt] != 1)
  393. continue;
  394. if (!areNodesMergeable(Src, Tgt))
  395. continue;
  396. // Do not merge if there is also an edge from target to src (immediate
  397. // cycle).
  398. if (Tgt.hasEdgeTo(Src))
  399. continue;
  400. LLVM_DEBUG(dbgs() << "Merging:" << Src << "\nWith:" << Tgt << "\n");
  401. mergeNodes(Src, Tgt);
  402. // If the target node is in the candidate set itself, we need to put the
  403. // src node back into the worklist again so it gives the target a chance
  404. // to get merged into it. For example if we have:
  405. // {(a)->(b), (b)->(c), (c)->(d), ...} and the worklist is initially {b, a},
  406. // then after merging (a) and (b) together, we need to put (a,b) back in
  407. // the worklist so that (c) can get merged in as well resulting in
  408. // {(a,b,c) -> d}
  409. // We also need to remove the old target (b), from the worklist. We first
  410. // remove it from the candidate set here, and skip any item from the
  411. // worklist that is not in the set.
  412. if (CandidateSourceNodes.erase(&Tgt)) {
  413. Worklist.push_back(&Src);
  414. CandidateSourceNodes.insert(&Src);
  415. LLVM_DEBUG(dbgs() << "Putting " << &Src << " back in the worklist.\n");
  416. }
  417. }
  418. LLVM_DEBUG(dbgs() << "=== End of Graph Simplification ===\n");
  419. }
  420. template <class G>
  421. void AbstractDependenceGraphBuilder<G>::sortNodesTopologically() {
  422. // If we don't create pi-blocks, then we may not have a DAG.
  423. if (!shouldCreatePiBlocks())
  424. return;
  425. SmallVector<NodeType *, 64> NodesInPO;
  426. using NodeKind = typename NodeType::NodeKind;
  427. for (NodeType *N : post_order(&Graph)) {
  428. if (N->getKind() == NodeKind::PiBlock) {
  429. // Put members of the pi-block right after the pi-block itself, for
  430. // convenience.
  431. const NodeListType &PiBlockMembers = getNodesInPiBlock(*N);
  432. llvm::append_range(NodesInPO, PiBlockMembers);
  433. }
  434. NodesInPO.push_back(N);
  435. }
  436. size_t OldSize = Graph.Nodes.size();
  437. Graph.Nodes.clear();
  438. append_range(Graph.Nodes, reverse(NodesInPO));
  439. if (Graph.Nodes.size() != OldSize)
  440. assert(false &&
  441. "Expected the number of nodes to stay the same after the sort");
  442. }
  443. template class llvm::AbstractDependenceGraphBuilder<DataDependenceGraph>;
  444. template class llvm::DependenceGraphInfo<DDGNode>;