1 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Analysis/LazyCallGraph.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/ScopeExit.h" 13 #include "llvm/ADT/Sequence.h" 14 #include "llvm/IR/CallSite.h" 15 #include "llvm/IR/InstVisitor.h" 16 #include "llvm/IR/Instructions.h" 17 #include "llvm/IR/PassManager.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/GraphWriter.h" 20 #include <utility> 21 22 using namespace llvm; 23 24 #define DEBUG_TYPE "lcg" 25 26 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN, 27 Edge::Kind EK) { 28 EdgeIndexMap.insert({&TargetN, Edges.size()}); 29 Edges.emplace_back(TargetN, EK); 30 } 31 32 void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) { 33 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK); 34 } 35 36 bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) { 37 auto IndexMapI = EdgeIndexMap.find(&TargetN); 38 if (IndexMapI == EdgeIndexMap.end()) 39 return false; 40 41 Edges[IndexMapI->second] = Edge(); 42 EdgeIndexMap.erase(IndexMapI); 43 return true; 44 } 45 46 static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges, 47 DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap, 48 LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) { 49 if (!EdgeIndexMap.insert({&N, Edges.size()}).second) 50 return; 51 52 DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n"); 53 Edges.emplace_back(LazyCallGraph::Edge(N, EK)); 54 } 55 56 LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() { 57 assert(!Edges && "Must not have already populated the edges for this node!"); 58 59 DEBUG(dbgs() << " Adding functions called by '" << getName() 60 << "' to the graph.\n"); 61 62 Edges = EdgeSequence(); 63 64 SmallVector<Constant *, 16> Worklist; 65 SmallPtrSet<Function *, 4> Callees; 66 SmallPtrSet<Constant *, 16> Visited; 67 68 // Find all the potential call graph edges in this function. We track both 69 // actual call edges and indirect references to functions. The direct calls 70 // are trivially added, but to accumulate the latter we walk the instructions 71 // and add every operand which is a constant to the worklist to process 72 // afterward. 73 // 74 // Note that we consider *any* function with a definition to be a viable 75 // edge. Even if the function's definition is subject to replacement by 76 // some other module (say, a weak definition) there may still be 77 // optimizations which essentially speculate based on the definition and 78 // a way to check that the specific definition is in fact the one being 79 // used. For example, this could be done by moving the weak definition to 80 // a strong (internal) definition and making the weak definition be an 81 // alias. Then a test of the address of the weak function against the new 82 // strong definition's address would be an effective way to determine the 83 // safety of optimizing a direct call edge. 84 for (BasicBlock &BB : *F) 85 for (Instruction &I : BB) { 86 if (auto CS = CallSite(&I)) 87 if (Function *Callee = CS.getCalledFunction()) 88 if (!Callee->isDeclaration()) 89 if (Callees.insert(Callee).second) { 90 Visited.insert(Callee); 91 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee), 92 LazyCallGraph::Edge::Call); 93 } 94 95 for (Value *Op : I.operand_values()) 96 if (Constant *C = dyn_cast<Constant>(Op)) 97 if (Visited.insert(C).second) 98 Worklist.push_back(C); 99 } 100 101 // We've collected all the constant (and thus potentially function or 102 // function containing) operands to all of the instructions in the function. 103 // Process them (recursively) collecting every function found. 104 visitReferences(Worklist, Visited, [&](Function &F) { 105 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F), 106 LazyCallGraph::Edge::Ref); 107 }); 108 109 return *Edges; 110 } 111 112 void LazyCallGraph::Node::replaceFunction(Function &NewF) { 113 assert(F != &NewF && "Must not replace a function with itself!"); 114 F = &NewF; 115 } 116 117 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 118 LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const { 119 dbgs() << *this << '\n'; 120 } 121 #endif 122 123 LazyCallGraph::LazyCallGraph(Module &M) { 124 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier() 125 << "\n"); 126 for (Function &F : M) 127 if (!F.isDeclaration() && !F.hasLocalLinkage()) { 128 DEBUG(dbgs() << " Adding '" << F.getName() 129 << "' to entry set of the graph.\n"); 130 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref); 131 } 132 133 // Now add entry nodes for functions reachable via initializers to globals. 134 SmallVector<Constant *, 16> Worklist; 135 SmallPtrSet<Constant *, 16> Visited; 136 for (GlobalVariable &GV : M.globals()) 137 if (GV.hasInitializer()) 138 if (Visited.insert(GV.getInitializer()).second) 139 Worklist.push_back(GV.getInitializer()); 140 141 DEBUG(dbgs() << " Adding functions referenced by global initializers to the " 142 "entry set.\n"); 143 visitReferences(Worklist, Visited, [&](Function &F) { 144 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), 145 LazyCallGraph::Edge::Ref); 146 }); 147 } 148 149 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G) 150 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)), 151 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)), 152 SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)) { 153 updateGraphPtrs(); 154 } 155 156 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) { 157 BPA = std::move(G.BPA); 158 NodeMap = std::move(G.NodeMap); 159 EntryEdges = std::move(G.EntryEdges); 160 SCCBPA = std::move(G.SCCBPA); 161 SCCMap = std::move(G.SCCMap); 162 LeafRefSCCs = std::move(G.LeafRefSCCs); 163 updateGraphPtrs(); 164 return *this; 165 } 166 167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 168 LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const { 169 dbgs() << *this << '\n'; 170 } 171 #endif 172 173 #ifndef NDEBUG 174 void LazyCallGraph::SCC::verify() { 175 assert(OuterRefSCC && "Can't have a null RefSCC!"); 176 assert(!Nodes.empty() && "Can't have an empty SCC!"); 177 178 for (Node *N : Nodes) { 179 assert(N && "Can't have a null node!"); 180 assert(OuterRefSCC->G->lookupSCC(*N) == this && 181 "Node does not map to this SCC!"); 182 assert(N->DFSNumber == -1 && 183 "Must set DFS numbers to -1 when adding a node to an SCC!"); 184 assert(N->LowLink == -1 && 185 "Must set low link to -1 when adding a node to an SCC!"); 186 for (Edge &E : **N) 187 assert(E.getNode() && "Can't have an unpopulated node!"); 188 } 189 } 190 #endif 191 192 bool LazyCallGraph::SCC::isParentOf(const SCC &C) const { 193 if (this == &C) 194 return false; 195 196 for (Node &N : *this) 197 for (Edge &E : N->calls()) 198 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C) 199 return true; 200 201 // No edges found. 202 return false; 203 } 204 205 bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const { 206 if (this == &TargetC) 207 return false; 208 209 LazyCallGraph &G = *OuterRefSCC->G; 210 211 // Start with this SCC. 212 SmallPtrSet<const SCC *, 16> Visited = {this}; 213 SmallVector<const SCC *, 16> Worklist = {this}; 214 215 // Walk down the graph until we run out of edges or find a path to TargetC. 216 do { 217 const SCC &C = *Worklist.pop_back_val(); 218 for (Node &N : C) 219 for (Edge &E : N->calls()) { 220 SCC *CalleeC = G.lookupSCC(E.getNode()); 221 if (!CalleeC) 222 continue; 223 224 // If the callee's SCC is the TargetC, we're done. 225 if (CalleeC == &TargetC) 226 return true; 227 228 // If this is the first time we've reached this SCC, put it on the 229 // worklist to recurse through. 230 if (Visited.insert(CalleeC).second) 231 Worklist.push_back(CalleeC); 232 } 233 } while (!Worklist.empty()); 234 235 // No paths found. 236 return false; 237 } 238 239 LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {} 240 241 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 242 LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const { 243 dbgs() << *this << '\n'; 244 } 245 #endif 246 247 #ifndef NDEBUG 248 void LazyCallGraph::RefSCC::verify() { 249 assert(G && "Can't have a null graph!"); 250 assert(!SCCs.empty() && "Can't have an empty SCC!"); 251 252 // Verify basic properties of the SCCs. 253 SmallPtrSet<SCC *, 4> SCCSet; 254 for (SCC *C : SCCs) { 255 assert(C && "Can't have a null SCC!"); 256 C->verify(); 257 assert(&C->getOuterRefSCC() == this && 258 "SCC doesn't think it is inside this RefSCC!"); 259 bool Inserted = SCCSet.insert(C).second; 260 assert(Inserted && "Found a duplicate SCC!"); 261 auto IndexIt = SCCIndices.find(C); 262 assert(IndexIt != SCCIndices.end() && 263 "Found an SCC that doesn't have an index!"); 264 } 265 266 // Check that our indices map correctly. 267 for (auto &SCCIndexPair : SCCIndices) { 268 SCC *C = SCCIndexPair.first; 269 int i = SCCIndexPair.second; 270 assert(C && "Can't have a null SCC in the indices!"); 271 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!"); 272 assert(SCCs[i] == C && "Index doesn't point to SCC!"); 273 } 274 275 // Check that the SCCs are in fact in post-order. 276 for (int i = 0, Size = SCCs.size(); i < Size; ++i) { 277 SCC &SourceSCC = *SCCs[i]; 278 for (Node &N : SourceSCC) 279 for (Edge &E : *N) { 280 if (!E.isCall()) 281 continue; 282 SCC &TargetSCC = *G->lookupSCC(E.getNode()); 283 if (&TargetSCC.getOuterRefSCC() == this) { 284 assert(SCCIndices.find(&TargetSCC)->second <= i && 285 "Edge between SCCs violates post-order relationship."); 286 continue; 287 } 288 assert(TargetSCC.getOuterRefSCC().Parents.count(this) && 289 "Edge to a RefSCC missing us in its parent set."); 290 } 291 } 292 293 // Check that our parents are actually parents. 294 for (RefSCC *ParentRC : Parents) { 295 assert(ParentRC != this && "Cannot be our own parent!"); 296 auto HasConnectingEdge = [&] { 297 for (SCC &C : *ParentRC) 298 for (Node &N : C) 299 for (Edge &E : *N) 300 if (G->lookupRefSCC(E.getNode()) == this) 301 return true; 302 return false; 303 }; 304 assert(HasConnectingEdge() && "No edge connects the parent to us!"); 305 } 306 } 307 #endif 308 309 bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const { 310 // Walk up the parents of this SCC and verify that we eventually find C. 311 SmallVector<const RefSCC *, 4> AncestorWorklist; 312 AncestorWorklist.push_back(this); 313 do { 314 const RefSCC *AncestorC = AncestorWorklist.pop_back_val(); 315 if (AncestorC->isChildOf(C)) 316 return true; 317 for (const RefSCC *ParentC : AncestorC->Parents) 318 AncestorWorklist.push_back(ParentC); 319 } while (!AncestorWorklist.empty()); 320 321 return false; 322 } 323 324 /// Generic helper that updates a postorder sequence of SCCs for a potentially 325 /// cycle-introducing edge insertion. 326 /// 327 /// A postorder sequence of SCCs of a directed graph has one fundamental 328 /// property: all deges in the DAG of SCCs point "up" the sequence. That is, 329 /// all edges in the SCC DAG point to prior SCCs in the sequence. 330 /// 331 /// This routine both updates a postorder sequence and uses that sequence to 332 /// compute the set of SCCs connected into a cycle. It should only be called to 333 /// insert a "downward" edge which will require changing the sequence to 334 /// restore it to a postorder. 335 /// 336 /// When inserting an edge from an earlier SCC to a later SCC in some postorder 337 /// sequence, all of the SCCs which may be impacted are in the closed range of 338 /// those two within the postorder sequence. The algorithm used here to restore 339 /// the state is as follows: 340 /// 341 /// 1) Starting from the source SCC, construct a set of SCCs which reach the 342 /// source SCC consisting of just the source SCC. Then scan toward the 343 /// target SCC in postorder and for each SCC, if it has an edge to an SCC 344 /// in the set, add it to the set. Otherwise, the source SCC is not 345 /// a successor, move it in the postorder sequence to immediately before 346 /// the source SCC, shifting the source SCC and all SCCs in the set one 347 /// position toward the target SCC. Stop scanning after processing the 348 /// target SCC. 349 /// 2) If the source SCC is now past the target SCC in the postorder sequence, 350 /// and thus the new edge will flow toward the start, we are done. 351 /// 3) Otherwise, starting from the target SCC, walk all edges which reach an 352 /// SCC between the source and the target, and add them to the set of 353 /// connected SCCs, then recurse through them. Once a complete set of the 354 /// SCCs the target connects to is known, hoist the remaining SCCs between 355 /// the source and the target to be above the target. Note that there is no 356 /// need to process the source SCC, it is already known to connect. 357 /// 4) At this point, all of the SCCs in the closed range between the source 358 /// SCC and the target SCC in the postorder sequence are connected, 359 /// including the target SCC and the source SCC. Inserting the edge from 360 /// the source SCC to the target SCC will form a cycle out of precisely 361 /// these SCCs. Thus we can merge all of the SCCs in this closed range into 362 /// a single SCC. 363 /// 364 /// This process has various important properties: 365 /// - Only mutates the SCCs when adding the edge actually changes the SCC 366 /// structure. 367 /// - Never mutates SCCs which are unaffected by the change. 368 /// - Updates the postorder sequence to correctly satisfy the postorder 369 /// constraint after the edge is inserted. 370 /// - Only reorders SCCs in the closed postorder sequence from the source to 371 /// the target, so easy to bound how much has changed even in the ordering. 372 /// - Big-O is the number of edges in the closed postorder range of SCCs from 373 /// source to target. 374 /// 375 /// This helper routine, in addition to updating the postorder sequence itself 376 /// will also update a map from SCCs to indices within that sequecne. 377 /// 378 /// The sequence and the map must operate on pointers to the SCC type. 379 /// 380 /// Two callbacks must be provided. The first computes the subset of SCCs in 381 /// the postorder closed range from the source to the target which connect to 382 /// the source SCC via some (transitive) set of edges. The second computes the 383 /// subset of the same range which the target SCC connects to via some 384 /// (transitive) set of edges. Both callbacks should populate the set argument 385 /// provided. 386 template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT, 387 typename ComputeSourceConnectedSetCallableT, 388 typename ComputeTargetConnectedSetCallableT> 389 static iterator_range<typename PostorderSequenceT::iterator> 390 updatePostorderSequenceForEdgeInsertion( 391 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs, 392 SCCIndexMapT &SCCIndices, 393 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet, 394 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) { 395 int SourceIdx = SCCIndices[&SourceSCC]; 396 int TargetIdx = SCCIndices[&TargetSCC]; 397 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!"); 398 399 SmallPtrSet<SCCT *, 4> ConnectedSet; 400 401 // Compute the SCCs which (transitively) reach the source. 402 ComputeSourceConnectedSet(ConnectedSet); 403 404 // Partition the SCCs in this part of the port-order sequence so only SCCs 405 // connecting to the source remain between it and the target. This is 406 // a benign partition as it preserves postorder. 407 auto SourceI = std::stable_partition( 408 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1, 409 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); }); 410 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i) 411 SCCIndices.find(SCCs[i])->second = i; 412 413 // If the target doesn't connect to the source, then we've corrected the 414 // post-order and there are no cycles formed. 415 if (!ConnectedSet.count(&TargetSCC)) { 416 assert(SourceI > (SCCs.begin() + SourceIdx) && 417 "Must have moved the source to fix the post-order."); 418 assert(*std::prev(SourceI) == &TargetSCC && 419 "Last SCC to move should have bene the target."); 420 421 // Return an empty range at the target SCC indicating there is nothing to 422 // merge. 423 return make_range(std::prev(SourceI), std::prev(SourceI)); 424 } 425 426 assert(SCCs[TargetIdx] == &TargetSCC && 427 "Should not have moved target if connected!"); 428 SourceIdx = SourceI - SCCs.begin(); 429 assert(SCCs[SourceIdx] == &SourceSCC && 430 "Bad updated index computation for the source SCC!"); 431 432 433 // See whether there are any remaining intervening SCCs between the source 434 // and target. If so we need to make sure they all are reachable form the 435 // target. 436 if (SourceIdx + 1 < TargetIdx) { 437 ConnectedSet.clear(); 438 ComputeTargetConnectedSet(ConnectedSet); 439 440 // Partition SCCs so that only SCCs reached from the target remain between 441 // the source and the target. This preserves postorder. 442 auto TargetI = std::stable_partition( 443 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1, 444 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); }); 445 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i) 446 SCCIndices.find(SCCs[i])->second = i; 447 TargetIdx = std::prev(TargetI) - SCCs.begin(); 448 assert(SCCs[TargetIdx] == &TargetSCC && 449 "Should always end with the target!"); 450 } 451 452 // At this point, we know that connecting source to target forms a cycle 453 // because target connects back to source, and we know that all of the SCCs 454 // between the source and target in the postorder sequence participate in that 455 // cycle. 456 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx); 457 } 458 459 bool 460 LazyCallGraph::RefSCC::switchInternalEdgeToCall( 461 Node &SourceN, Node &TargetN, 462 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) { 463 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!"); 464 SmallVector<SCC *, 1> DeletedSCCs; 465 466 #ifndef NDEBUG 467 // In a debug build, verify the RefSCC is valid to start with and when this 468 // routine finishes. 469 verify(); 470 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 471 #endif 472 473 SCC &SourceSCC = *G->lookupSCC(SourceN); 474 SCC &TargetSCC = *G->lookupSCC(TargetN); 475 476 // If the two nodes are already part of the same SCC, we're also done as 477 // we've just added more connectivity. 478 if (&SourceSCC == &TargetSCC) { 479 SourceN->setEdgeKind(TargetN, Edge::Call); 480 return false; // No new cycle. 481 } 482 483 // At this point we leverage the postorder list of SCCs to detect when the 484 // insertion of an edge changes the SCC structure in any way. 485 // 486 // First and foremost, we can eliminate the need for any changes when the 487 // edge is toward the beginning of the postorder sequence because all edges 488 // flow in that direction already. Thus adding a new one cannot form a cycle. 489 int SourceIdx = SCCIndices[&SourceSCC]; 490 int TargetIdx = SCCIndices[&TargetSCC]; 491 if (TargetIdx < SourceIdx) { 492 SourceN->setEdgeKind(TargetN, Edge::Call); 493 return false; // No new cycle. 494 } 495 496 // Compute the SCCs which (transitively) reach the source. 497 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) { 498 #ifndef NDEBUG 499 // Check that the RefSCC is still valid before computing this as the 500 // results will be nonsensical of we've broken its invariants. 501 verify(); 502 #endif 503 ConnectedSet.insert(&SourceSCC); 504 auto IsConnected = [&](SCC &C) { 505 for (Node &N : C) 506 for (Edge &E : N->calls()) 507 if (ConnectedSet.count(G->lookupSCC(E.getNode()))) 508 return true; 509 510 return false; 511 }; 512 513 for (SCC *C : 514 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1)) 515 if (IsConnected(*C)) 516 ConnectedSet.insert(C); 517 }; 518 519 // Use a normal worklist to find which SCCs the target connects to. We still 520 // bound the search based on the range in the postorder list we care about, 521 // but because this is forward connectivity we just "recurse" through the 522 // edges. 523 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) { 524 #ifndef NDEBUG 525 // Check that the RefSCC is still valid before computing this as the 526 // results will be nonsensical of we've broken its invariants. 527 verify(); 528 #endif 529 ConnectedSet.insert(&TargetSCC); 530 SmallVector<SCC *, 4> Worklist; 531 Worklist.push_back(&TargetSCC); 532 do { 533 SCC &C = *Worklist.pop_back_val(); 534 for (Node &N : C) 535 for (Edge &E : *N) { 536 if (!E.isCall()) 537 continue; 538 SCC &EdgeC = *G->lookupSCC(E.getNode()); 539 if (&EdgeC.getOuterRefSCC() != this) 540 // Not in this RefSCC... 541 continue; 542 if (SCCIndices.find(&EdgeC)->second <= SourceIdx) 543 // Not in the postorder sequence between source and target. 544 continue; 545 546 if (ConnectedSet.insert(&EdgeC).second) 547 Worklist.push_back(&EdgeC); 548 } 549 } while (!Worklist.empty()); 550 }; 551 552 // Use a generic helper to update the postorder sequence of SCCs and return 553 // a range of any SCCs connected into a cycle by inserting this edge. This 554 // routine will also take care of updating the indices into the postorder 555 // sequence. 556 auto MergeRange = updatePostorderSequenceForEdgeInsertion( 557 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet, 558 ComputeTargetConnectedSet); 559 560 // Run the user's callback on the merged SCCs before we actually merge them. 561 if (MergeCB) 562 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end())); 563 564 // If the merge range is empty, then adding the edge didn't actually form any 565 // new cycles. We're done. 566 if (MergeRange.begin() == MergeRange.end()) { 567 // Now that the SCC structure is finalized, flip the kind to call. 568 SourceN->setEdgeKind(TargetN, Edge::Call); 569 return false; // No new cycle. 570 } 571 572 #ifndef NDEBUG 573 // Before merging, check that the RefSCC remains valid after all the 574 // postorder updates. 575 verify(); 576 #endif 577 578 // Otherwise we need to merge all of the SCCs in the cycle into a single 579 // result SCC. 580 // 581 // NB: We merge into the target because all of these functions were already 582 // reachable from the target, meaning any SCC-wide properties deduced about it 583 // other than the set of functions within it will not have changed. 584 for (SCC *C : MergeRange) { 585 assert(C != &TargetSCC && 586 "We merge *into* the target and shouldn't process it here!"); 587 SCCIndices.erase(C); 588 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end()); 589 for (Node *N : C->Nodes) 590 G->SCCMap[N] = &TargetSCC; 591 C->clear(); 592 DeletedSCCs.push_back(C); 593 } 594 595 // Erase the merged SCCs from the list and update the indices of the 596 // remaining SCCs. 597 int IndexOffset = MergeRange.end() - MergeRange.begin(); 598 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end()); 599 for (SCC *C : make_range(EraseEnd, SCCs.end())) 600 SCCIndices[C] -= IndexOffset; 601 602 // Now that the SCC structure is finalized, flip the kind to call. 603 SourceN->setEdgeKind(TargetN, Edge::Call); 604 605 // And we're done, but we did form a new cycle. 606 return true; 607 } 608 609 void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN, 610 Node &TargetN) { 611 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!"); 612 613 #ifndef NDEBUG 614 // In a debug build, verify the RefSCC is valid to start with and when this 615 // routine finishes. 616 verify(); 617 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 618 #endif 619 620 assert(G->lookupRefSCC(SourceN) == this && 621 "Source must be in this RefSCC."); 622 assert(G->lookupRefSCC(TargetN) == this && 623 "Target must be in this RefSCC."); 624 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) && 625 "Source and Target must be in separate SCCs for this to be trivial!"); 626 627 // Set the edge kind. 628 SourceN->setEdgeKind(TargetN, Edge::Ref); 629 } 630 631 iterator_range<LazyCallGraph::RefSCC::iterator> 632 LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) { 633 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!"); 634 635 #ifndef NDEBUG 636 // In a debug build, verify the RefSCC is valid to start with and when this 637 // routine finishes. 638 verify(); 639 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 640 #endif 641 642 assert(G->lookupRefSCC(SourceN) == this && 643 "Source must be in this RefSCC."); 644 assert(G->lookupRefSCC(TargetN) == this && 645 "Target must be in this RefSCC."); 646 647 SCC &TargetSCC = *G->lookupSCC(TargetN); 648 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in " 649 "the same SCC to require the " 650 "full CG update."); 651 652 // Set the edge kind. 653 SourceN->setEdgeKind(TargetN, Edge::Ref); 654 655 // Otherwise we are removing a call edge from a single SCC. This may break 656 // the cycle. In order to compute the new set of SCCs, we need to do a small 657 // DFS over the nodes within the SCC to form any sub-cycles that remain as 658 // distinct SCCs and compute a postorder over the resulting SCCs. 659 // 660 // However, we specially handle the target node. The target node is known to 661 // reach all other nodes in the original SCC by definition. This means that 662 // we want the old SCC to be replaced with an SCC contaning that node as it 663 // will be the root of whatever SCC DAG results from the DFS. Assumptions 664 // about an SCC such as the set of functions called will continue to hold, 665 // etc. 666 667 SCC &OldSCC = TargetSCC; 668 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack; 669 SmallVector<Node *, 16> PendingSCCStack; 670 SmallVector<SCC *, 4> NewSCCs; 671 672 // Prepare the nodes for a fresh DFS. 673 SmallVector<Node *, 16> Worklist; 674 Worklist.swap(OldSCC.Nodes); 675 for (Node *N : Worklist) { 676 N->DFSNumber = N->LowLink = 0; 677 G->SCCMap.erase(N); 678 } 679 680 // Force the target node to be in the old SCC. This also enables us to take 681 // a very significant short-cut in the standard Tarjan walk to re-form SCCs 682 // below: whenever we build an edge that reaches the target node, we know 683 // that the target node eventually connects back to all other nodes in our 684 // walk. As a consequence, we can detect and handle participants in that 685 // cycle without walking all the edges that form this connection, and instead 686 // by relying on the fundamental guarantee coming into this operation (all 687 // nodes are reachable from the target due to previously forming an SCC). 688 TargetN.DFSNumber = TargetN.LowLink = -1; 689 OldSCC.Nodes.push_back(&TargetN); 690 G->SCCMap[&TargetN] = &OldSCC; 691 692 // Scan down the stack and DFS across the call edges. 693 for (Node *RootN : Worklist) { 694 assert(DFSStack.empty() && 695 "Cannot begin a new root with a non-empty DFS stack!"); 696 assert(PendingSCCStack.empty() && 697 "Cannot begin a new root with pending nodes for an SCC!"); 698 699 // Skip any nodes we've already reached in the DFS. 700 if (RootN->DFSNumber != 0) { 701 assert(RootN->DFSNumber == -1 && 702 "Shouldn't have any mid-DFS root nodes!"); 703 continue; 704 } 705 706 RootN->DFSNumber = RootN->LowLink = 1; 707 int NextDFSNumber = 2; 708 709 DFSStack.push_back({RootN, (*RootN)->call_begin()}); 710 do { 711 Node *N; 712 EdgeSequence::call_iterator I; 713 std::tie(N, I) = DFSStack.pop_back_val(); 714 auto E = (*N)->call_end(); 715 while (I != E) { 716 Node &ChildN = I->getNode(); 717 if (ChildN.DFSNumber == 0) { 718 // We haven't yet visited this child, so descend, pushing the current 719 // node onto the stack. 720 DFSStack.push_back({N, I}); 721 722 assert(!G->SCCMap.count(&ChildN) && 723 "Found a node with 0 DFS number but already in an SCC!"); 724 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++; 725 N = &ChildN; 726 I = (*N)->call_begin(); 727 E = (*N)->call_end(); 728 continue; 729 } 730 731 // Check for the child already being part of some component. 732 if (ChildN.DFSNumber == -1) { 733 if (G->lookupSCC(ChildN) == &OldSCC) { 734 // If the child is part of the old SCC, we know that it can reach 735 // every other node, so we have formed a cycle. Pull the entire DFS 736 // and pending stacks into it. See the comment above about setting 737 // up the old SCC for why we do this. 738 int OldSize = OldSCC.size(); 739 OldSCC.Nodes.push_back(N); 740 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end()); 741 PendingSCCStack.clear(); 742 while (!DFSStack.empty()) 743 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first); 744 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) { 745 N.DFSNumber = N.LowLink = -1; 746 G->SCCMap[&N] = &OldSCC; 747 } 748 N = nullptr; 749 break; 750 } 751 752 // If the child has already been added to some child component, it 753 // couldn't impact the low-link of this parent because it isn't 754 // connected, and thus its low-link isn't relevant so skip it. 755 ++I; 756 continue; 757 } 758 759 // Track the lowest linked child as the lowest link for this node. 760 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!"); 761 if (ChildN.LowLink < N->LowLink) 762 N->LowLink = ChildN.LowLink; 763 764 // Move to the next edge. 765 ++I; 766 } 767 if (!N) 768 // Cleared the DFS early, start another round. 769 break; 770 771 // We've finished processing N and its descendents, put it on our pending 772 // SCC stack to eventually get merged into an SCC of nodes. 773 PendingSCCStack.push_back(N); 774 775 // If this node is linked to some lower entry, continue walking up the 776 // stack. 777 if (N->LowLink != N->DFSNumber) 778 continue; 779 780 // Otherwise, we've completed an SCC. Append it to our post order list of 781 // SCCs. 782 int RootDFSNumber = N->DFSNumber; 783 // Find the range of the node stack by walking down until we pass the 784 // root DFS number. 785 auto SCCNodes = make_range( 786 PendingSCCStack.rbegin(), 787 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) { 788 return N->DFSNumber < RootDFSNumber; 789 })); 790 791 // Form a new SCC out of these nodes and then clear them off our pending 792 // stack. 793 NewSCCs.push_back(G->createSCC(*this, SCCNodes)); 794 for (Node &N : *NewSCCs.back()) { 795 N.DFSNumber = N.LowLink = -1; 796 G->SCCMap[&N] = NewSCCs.back(); 797 } 798 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end()); 799 } while (!DFSStack.empty()); 800 } 801 802 // Insert the remaining SCCs before the old one. The old SCC can reach all 803 // other SCCs we form because it contains the target node of the removed edge 804 // of the old SCC. This means that we will have edges into all of the new 805 // SCCs, which means the old one must come last for postorder. 806 int OldIdx = SCCIndices[&OldSCC]; 807 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end()); 808 809 // Update the mapping from SCC* to index to use the new SCC*s, and remove the 810 // old SCC from the mapping. 811 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx) 812 SCCIndices[SCCs[Idx]] = Idx; 813 814 return make_range(SCCs.begin() + OldIdx, 815 SCCs.begin() + OldIdx + NewSCCs.size()); 816 } 817 818 void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN, 819 Node &TargetN) { 820 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!"); 821 822 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC."); 823 assert(G->lookupRefSCC(TargetN) != this && 824 "Target must not be in this RefSCC."); 825 #ifdef EXPENSIVE_CHECKS 826 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) && 827 "Target must be a descendant of the Source."); 828 #endif 829 830 // Edges between RefSCCs are the same regardless of call or ref, so we can 831 // just flip the edge here. 832 SourceN->setEdgeKind(TargetN, Edge::Call); 833 834 #ifndef NDEBUG 835 // Check that the RefSCC is still valid. 836 verify(); 837 #endif 838 } 839 840 void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN, 841 Node &TargetN) { 842 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!"); 843 844 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC."); 845 assert(G->lookupRefSCC(TargetN) != this && 846 "Target must not be in this RefSCC."); 847 #ifdef EXPENSIVE_CHECKS 848 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) && 849 "Target must be a descendant of the Source."); 850 #endif 851 852 // Edges between RefSCCs are the same regardless of call or ref, so we can 853 // just flip the edge here. 854 SourceN->setEdgeKind(TargetN, Edge::Ref); 855 856 #ifndef NDEBUG 857 // Check that the RefSCC is still valid. 858 verify(); 859 #endif 860 } 861 862 void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN, 863 Node &TargetN) { 864 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC."); 865 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC."); 866 867 SourceN->insertEdgeInternal(TargetN, Edge::Ref); 868 869 #ifndef NDEBUG 870 // Check that the RefSCC is still valid. 871 verify(); 872 #endif 873 } 874 875 void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN, 876 Edge::Kind EK) { 877 // First insert it into the caller. 878 SourceN->insertEdgeInternal(TargetN, EK); 879 880 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC."); 881 882 RefSCC &TargetC = *G->lookupRefSCC(TargetN); 883 assert(&TargetC != this && "Target must not be in this RefSCC."); 884 #ifdef EXPENSIVE_CHECKS 885 assert(TargetC.isDescendantOf(*this) && 886 "Target must be a descendant of the Source."); 887 #endif 888 889 // The only change required is to add this SCC to the parent set of the 890 // callee. 891 TargetC.Parents.insert(this); 892 893 #ifndef NDEBUG 894 // Check that the RefSCC is still valid. 895 verify(); 896 #endif 897 } 898 899 SmallVector<LazyCallGraph::RefSCC *, 1> 900 LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) { 901 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC."); 902 RefSCC &SourceC = *G->lookupRefSCC(SourceN); 903 assert(&SourceC != this && "Source must not be in this RefSCC."); 904 #ifdef EXPENSIVE_CHECKS 905 assert(SourceC.isDescendantOf(*this) && 906 "Source must be a descendant of the Target."); 907 #endif 908 909 SmallVector<RefSCC *, 1> DeletedRefSCCs; 910 911 #ifndef NDEBUG 912 // In a debug build, verify the RefSCC is valid to start with and when this 913 // routine finishes. 914 verify(); 915 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 916 #endif 917 918 int SourceIdx = G->RefSCCIndices[&SourceC]; 919 int TargetIdx = G->RefSCCIndices[this]; 920 assert(SourceIdx < TargetIdx && 921 "Postorder list doesn't see edge as incoming!"); 922 923 // Compute the RefSCCs which (transitively) reach the source. We do this by 924 // working backwards from the source using the parent set in each RefSCC, 925 // skipping any RefSCCs that don't fall in the postorder range. This has the 926 // advantage of walking the sparser parent edge (in high fan-out graphs) but 927 // more importantly this removes examining all forward edges in all RefSCCs 928 // within the postorder range which aren't in fact connected. Only connected 929 // RefSCCs (and their edges) are visited here. 930 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) { 931 Set.insert(&SourceC); 932 SmallVector<RefSCC *, 4> Worklist; 933 Worklist.push_back(&SourceC); 934 do { 935 RefSCC &RC = *Worklist.pop_back_val(); 936 for (RefSCC &ParentRC : RC.parents()) { 937 // Skip any RefSCCs outside the range of source to target in the 938 // postorder sequence. 939 int ParentIdx = G->getRefSCCIndex(ParentRC); 940 assert(ParentIdx > SourceIdx && "Parent cannot precede source in postorder!"); 941 if (ParentIdx > TargetIdx) 942 continue; 943 if (Set.insert(&ParentRC).second) 944 // First edge connecting to this parent, add it to our worklist. 945 Worklist.push_back(&ParentRC); 946 } 947 } while (!Worklist.empty()); 948 }; 949 950 // Use a normal worklist to find which SCCs the target connects to. We still 951 // bound the search based on the range in the postorder list we care about, 952 // but because this is forward connectivity we just "recurse" through the 953 // edges. 954 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) { 955 Set.insert(this); 956 SmallVector<RefSCC *, 4> Worklist; 957 Worklist.push_back(this); 958 do { 959 RefSCC &RC = *Worklist.pop_back_val(); 960 for (SCC &C : RC) 961 for (Node &N : C) 962 for (Edge &E : *N) { 963 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode()); 964 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx) 965 // Not in the postorder sequence between source and target. 966 continue; 967 968 if (Set.insert(&EdgeRC).second) 969 Worklist.push_back(&EdgeRC); 970 } 971 } while (!Worklist.empty()); 972 }; 973 974 // Use a generic helper to update the postorder sequence of RefSCCs and return 975 // a range of any RefSCCs connected into a cycle by inserting this edge. This 976 // routine will also take care of updating the indices into the postorder 977 // sequence. 978 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange = 979 updatePostorderSequenceForEdgeInsertion( 980 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices, 981 ComputeSourceConnectedSet, ComputeTargetConnectedSet); 982 983 // Build a set so we can do fast tests for whether a RefSCC will end up as 984 // part of the merged RefSCC. 985 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end()); 986 987 // This RefSCC will always be part of that set, so just insert it here. 988 MergeSet.insert(this); 989 990 // Now that we have identified all of the SCCs which need to be merged into 991 // a connected set with the inserted edge, merge all of them into this SCC. 992 SmallVector<SCC *, 16> MergedSCCs; 993 int SCCIndex = 0; 994 for (RefSCC *RC : MergeRange) { 995 assert(RC != this && "We're merging into the target RefSCC, so it " 996 "shouldn't be in the range."); 997 998 // Merge the parents which aren't part of the merge into the our parents. 999 for (RefSCC *ParentRC : RC->Parents) 1000 if (!MergeSet.count(ParentRC)) 1001 Parents.insert(ParentRC); 1002 RC->Parents.clear(); 1003 1004 // Walk the inner SCCs to update their up-pointer and walk all the edges to 1005 // update any parent sets. 1006 // FIXME: We should try to find a way to avoid this (rather expensive) edge 1007 // walk by updating the parent sets in some other manner. 1008 for (SCC &InnerC : *RC) { 1009 InnerC.OuterRefSCC = this; 1010 SCCIndices[&InnerC] = SCCIndex++; 1011 for (Node &N : InnerC) { 1012 G->SCCMap[&N] = &InnerC; 1013 for (Edge &E : *N) { 1014 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode()); 1015 if (MergeSet.count(&ChildRC)) 1016 continue; 1017 ChildRC.Parents.erase(RC); 1018 ChildRC.Parents.insert(this); 1019 } 1020 } 1021 } 1022 1023 // Now merge in the SCCs. We can actually move here so try to reuse storage 1024 // the first time through. 1025 if (MergedSCCs.empty()) 1026 MergedSCCs = std::move(RC->SCCs); 1027 else 1028 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end()); 1029 RC->SCCs.clear(); 1030 DeletedRefSCCs.push_back(RC); 1031 } 1032 1033 // Append our original SCCs to the merged list and move it into place. 1034 for (SCC &InnerC : *this) 1035 SCCIndices[&InnerC] = SCCIndex++; 1036 MergedSCCs.append(SCCs.begin(), SCCs.end()); 1037 SCCs = std::move(MergedSCCs); 1038 1039 // Remove the merged away RefSCCs from the post order sequence. 1040 for (RefSCC *RC : MergeRange) 1041 G->RefSCCIndices.erase(RC); 1042 int IndexOffset = MergeRange.end() - MergeRange.begin(); 1043 auto EraseEnd = 1044 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end()); 1045 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end())) 1046 G->RefSCCIndices[RC] -= IndexOffset; 1047 1048 // At this point we have a merged RefSCC with a post-order SCCs list, just 1049 // connect the nodes to form the new edge. 1050 SourceN->insertEdgeInternal(TargetN, Edge::Ref); 1051 1052 // We return the list of SCCs which were merged so that callers can 1053 // invalidate any data they have associated with those SCCs. Note that these 1054 // SCCs are no longer in an interesting state (they are totally empty) but 1055 // the pointers will remain stable for the life of the graph itself. 1056 return DeletedRefSCCs; 1057 } 1058 1059 void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) { 1060 assert(G->lookupRefSCC(SourceN) == this && 1061 "The source must be a member of this RefSCC."); 1062 1063 RefSCC &TargetRC = *G->lookupRefSCC(TargetN); 1064 assert(&TargetRC != this && "The target must not be a member of this RefSCC"); 1065 1066 assert(!is_contained(G->LeafRefSCCs, this) && 1067 "Cannot have a leaf RefSCC source."); 1068 1069 #ifndef NDEBUG 1070 // In a debug build, verify the RefSCC is valid to start with and when this 1071 // routine finishes. 1072 verify(); 1073 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 1074 #endif 1075 1076 // First remove it from the node. 1077 bool Removed = SourceN->removeEdgeInternal(TargetN); 1078 (void)Removed; 1079 assert(Removed && "Target not in the edge set for this caller?"); 1080 1081 bool HasOtherEdgeToChildRC = false; 1082 bool HasOtherChildRC = false; 1083 for (SCC *InnerC : SCCs) { 1084 for (Node &N : *InnerC) { 1085 for (Edge &E : *N) { 1086 RefSCC &OtherChildRC = *G->lookupRefSCC(E.getNode()); 1087 if (&OtherChildRC == &TargetRC) { 1088 HasOtherEdgeToChildRC = true; 1089 break; 1090 } 1091 if (&OtherChildRC != this) 1092 HasOtherChildRC = true; 1093 } 1094 if (HasOtherEdgeToChildRC) 1095 break; 1096 } 1097 if (HasOtherEdgeToChildRC) 1098 break; 1099 } 1100 // Because the SCCs form a DAG, deleting such an edge cannot change the set 1101 // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making 1102 // the source SCC no longer connected to the target SCC. If so, we need to 1103 // update the target SCC's map of its parents. 1104 if (!HasOtherEdgeToChildRC) { 1105 bool Removed = TargetRC.Parents.erase(this); 1106 (void)Removed; 1107 assert(Removed && 1108 "Did not find the source SCC in the target SCC's parent list!"); 1109 1110 // It may orphan an SCC if it is the last edge reaching it, but that does 1111 // not violate any invariants of the graph. 1112 if (TargetRC.Parents.empty()) 1113 DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName() 1114 << " -> " << TargetN.getFunction().getName() 1115 << " edge orphaned the callee's SCC!\n"); 1116 1117 // It may make the Source SCC a leaf SCC. 1118 if (!HasOtherChildRC) 1119 G->LeafRefSCCs.push_back(this); 1120 } 1121 } 1122 1123 SmallVector<LazyCallGraph::RefSCC *, 1> 1124 LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) { 1125 assert(!(*SourceN)[TargetN].isCall() && 1126 "Cannot remove a call edge, it must first be made a ref edge"); 1127 1128 #ifndef NDEBUG 1129 // In a debug build, verify the RefSCC is valid to start with and when this 1130 // routine finishes. 1131 verify(); 1132 auto VerifyOnExit = make_scope_exit([&]() { verify(); }); 1133 #endif 1134 1135 // First remove the actual edge. 1136 bool Removed = SourceN->removeEdgeInternal(TargetN); 1137 (void)Removed; 1138 assert(Removed && "Target not in the edge set for this caller?"); 1139 1140 // We return a list of the resulting *new* RefSCCs in post-order. 1141 SmallVector<RefSCC *, 1> Result; 1142 1143 // Direct recursion doesn't impact the SCC graph at all. 1144 if (&SourceN == &TargetN) 1145 return Result; 1146 1147 // If this ref edge is within an SCC then there are sufficient other edges to 1148 // form a cycle without this edge so removing it is a no-op. 1149 SCC &SourceC = *G->lookupSCC(SourceN); 1150 SCC &TargetC = *G->lookupSCC(TargetN); 1151 if (&SourceC == &TargetC) 1152 return Result; 1153 1154 // We build somewhat synthetic new RefSCCs by providing a postorder mapping 1155 // for each inner SCC. We also store these associated with *nodes* rather 1156 // than SCCs because this saves a round-trip through the node->SCC map and in 1157 // the common case, SCCs are small. We will verify that we always give the 1158 // same number to every node in the SCC such that these are equivalent. 1159 const int RootPostOrderNumber = 0; 1160 int PostOrderNumber = RootPostOrderNumber + 1; 1161 SmallDenseMap<Node *, int> PostOrderMapping; 1162 1163 // Every node in the target SCC can already reach every node in this RefSCC 1164 // (by definition). It is the only node we know will stay inside this RefSCC. 1165 // Everything which transitively reaches Target will also remain in the 1166 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map 1167 // back to the root post order number. 1168 // 1169 // This also enables us to take a very significant short-cut in the standard 1170 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that 1171 // references the target node, we know that the target node eventually 1172 // references all other nodes in our walk. As a consequence, we can detect 1173 // and handle participants in that cycle without walking all the edges that 1174 // form the connections, and instead by relying on the fundamental guarantee 1175 // coming into this operation. 1176 for (Node &N : TargetC) 1177 PostOrderMapping[&N] = RootPostOrderNumber; 1178 1179 // Reset all the other nodes to prepare for a DFS over them, and add them to 1180 // our worklist. 1181 SmallVector<Node *, 8> Worklist; 1182 for (SCC *C : SCCs) { 1183 if (C == &TargetC) 1184 continue; 1185 1186 for (Node &N : *C) 1187 N.DFSNumber = N.LowLink = 0; 1188 1189 Worklist.append(C->Nodes.begin(), C->Nodes.end()); 1190 } 1191 1192 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) { 1193 N.DFSNumber = N.LowLink = -1; 1194 PostOrderMapping[&N] = Number; 1195 }; 1196 1197 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack; 1198 SmallVector<Node *, 4> PendingRefSCCStack; 1199 do { 1200 assert(DFSStack.empty() && 1201 "Cannot begin a new root with a non-empty DFS stack!"); 1202 assert(PendingRefSCCStack.empty() && 1203 "Cannot begin a new root with pending nodes for an SCC!"); 1204 1205 Node *RootN = Worklist.pop_back_val(); 1206 // Skip any nodes we've already reached in the DFS. 1207 if (RootN->DFSNumber != 0) { 1208 assert(RootN->DFSNumber == -1 && 1209 "Shouldn't have any mid-DFS root nodes!"); 1210 continue; 1211 } 1212 1213 RootN->DFSNumber = RootN->LowLink = 1; 1214 int NextDFSNumber = 2; 1215 1216 DFSStack.push_back({RootN, (*RootN)->begin()}); 1217 do { 1218 Node *N; 1219 EdgeSequence::iterator I; 1220 std::tie(N, I) = DFSStack.pop_back_val(); 1221 auto E = (*N)->end(); 1222 1223 assert(N->DFSNumber != 0 && "We should always assign a DFS number " 1224 "before processing a node."); 1225 1226 while (I != E) { 1227 Node &ChildN = I->getNode(); 1228 if (ChildN.DFSNumber == 0) { 1229 // Mark that we should start at this child when next this node is the 1230 // top of the stack. We don't start at the next child to ensure this 1231 // child's lowlink is reflected. 1232 DFSStack.push_back({N, I}); 1233 1234 // Continue, resetting to the child node. 1235 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++; 1236 N = &ChildN; 1237 I = ChildN->begin(); 1238 E = ChildN->end(); 1239 continue; 1240 } 1241 if (ChildN.DFSNumber == -1) { 1242 // Check if this edge's target node connects to the deleted edge's 1243 // target node. If so, we know that every node connected will end up 1244 // in this RefSCC, so collapse the entire current stack into the root 1245 // slot in our SCC numbering. See above for the motivation of 1246 // optimizing the target connected nodes in this way. 1247 auto PostOrderI = PostOrderMapping.find(&ChildN); 1248 if (PostOrderI != PostOrderMapping.end() && 1249 PostOrderI->second == RootPostOrderNumber) { 1250 MarkNodeForSCCNumber(*N, RootPostOrderNumber); 1251 while (!PendingRefSCCStack.empty()) 1252 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(), 1253 RootPostOrderNumber); 1254 while (!DFSStack.empty()) 1255 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first, 1256 RootPostOrderNumber); 1257 // Ensure we break all the way out of the enclosing loop. 1258 N = nullptr; 1259 break; 1260 } 1261 1262 // If this child isn't currently in this RefSCC, no need to process 1263 // it. However, we do need to remove this RefSCC from its RefSCC's 1264 // parent set. 1265 RefSCC &ChildRC = *G->lookupRefSCC(ChildN); 1266 ChildRC.Parents.erase(this); 1267 ++I; 1268 continue; 1269 } 1270 1271 // Track the lowest link of the children, if any are still in the stack. 1272 // Any child not on the stack will have a LowLink of -1. 1273 assert(ChildN.LowLink != 0 && 1274 "Low-link must not be zero with a non-zero DFS number."); 1275 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink) 1276 N->LowLink = ChildN.LowLink; 1277 ++I; 1278 } 1279 if (!N) 1280 // We short-circuited this node. 1281 break; 1282 1283 // We've finished processing N and its descendents, put it on our pending 1284 // stack to eventually get merged into a RefSCC. 1285 PendingRefSCCStack.push_back(N); 1286 1287 // If this node is linked to some lower entry, continue walking up the 1288 // stack. 1289 if (N->LowLink != N->DFSNumber) { 1290 assert(!DFSStack.empty() && 1291 "We never found a viable root for a RefSCC to pop off!"); 1292 continue; 1293 } 1294 1295 // Otherwise, form a new RefSCC from the top of the pending node stack. 1296 int RootDFSNumber = N->DFSNumber; 1297 // Find the range of the node stack by walking down until we pass the 1298 // root DFS number. 1299 auto RefSCCNodes = make_range( 1300 PendingRefSCCStack.rbegin(), 1301 find_if(reverse(PendingRefSCCStack), [RootDFSNumber](const Node *N) { 1302 return N->DFSNumber < RootDFSNumber; 1303 })); 1304 1305 // Mark the postorder number for these nodes and clear them off the 1306 // stack. We'll use the postorder number to pull them into RefSCCs at the 1307 // end. FIXME: Fuse with the loop above. 1308 int RefSCCNumber = PostOrderNumber++; 1309 for (Node *N : RefSCCNodes) 1310 MarkNodeForSCCNumber(*N, RefSCCNumber); 1311 1312 PendingRefSCCStack.erase(RefSCCNodes.end().base(), 1313 PendingRefSCCStack.end()); 1314 } while (!DFSStack.empty()); 1315 1316 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!"); 1317 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!"); 1318 } while (!Worklist.empty()); 1319 1320 // We now have a post-order numbering for RefSCCs and a mapping from each 1321 // node in this RefSCC to its final RefSCC. We create each new RefSCC node 1322 // (re-using this RefSCC node for the root) and build a radix-sort style map 1323 // from postorder number to the RefSCC. We then append SCCs to each of these 1324 // RefSCCs in the order they occured in the original SCCs container. 1325 for (int i = 1; i < PostOrderNumber; ++i) 1326 Result.push_back(G->createRefSCC(*G)); 1327 1328 // Insert the resulting postorder sequence into the global graph postorder 1329 // sequence before the current RefSCC in that sequence. The idea being that 1330 // this RefSCC is the target of the reference edge removed, and thus has 1331 // a direct or indirect edge to every other RefSCC formed and so must be at 1332 // the end of any postorder traversal. 1333 // 1334 // FIXME: It'd be nice to change the APIs so that we returned an iterator 1335 // range over the global postorder sequence and generally use that sequence 1336 // rather than building a separate result vector here. 1337 if (!Result.empty()) { 1338 int Idx = G->getRefSCCIndex(*this); 1339 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, 1340 Result.begin(), Result.end()); 1341 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size())) 1342 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i; 1343 assert(G->PostOrderRefSCCs[G->getRefSCCIndex(*this)] == this && 1344 "Failed to update this RefSCC's index after insertion!"); 1345 } 1346 1347 for (SCC *C : SCCs) { 1348 auto PostOrderI = PostOrderMapping.find(&*C->begin()); 1349 assert(PostOrderI != PostOrderMapping.end() && 1350 "Cannot have missing mappings for nodes!"); 1351 int SCCNumber = PostOrderI->second; 1352 #ifndef NDEBUG 1353 for (Node &N : *C) 1354 assert(PostOrderMapping.find(&N)->second == SCCNumber && 1355 "Cannot have different numbers for nodes in the same SCC!"); 1356 #endif 1357 if (SCCNumber == 0) 1358 // The root node is handled separately by removing the SCCs. 1359 continue; 1360 1361 RefSCC &RC = *Result[SCCNumber - 1]; 1362 int SCCIndex = RC.SCCs.size(); 1363 RC.SCCs.push_back(C); 1364 RC.SCCIndices[C] = SCCIndex; 1365 C->OuterRefSCC = &RC; 1366 } 1367 1368 // FIXME: We re-walk the edges in each RefSCC to establish whether it is 1369 // a leaf and connect it to the rest of the graph's parents lists. This is 1370 // really wasteful. We should instead do this during the DFS to avoid yet 1371 // another edge walk. 1372 for (RefSCC *RC : Result) 1373 G->connectRefSCC(*RC); 1374 1375 // Now erase all but the root's SCCs. 1376 SCCs.erase(remove_if(SCCs, 1377 [&](SCC *C) { 1378 return PostOrderMapping.lookup(&*C->begin()) != 1379 RootPostOrderNumber; 1380 }), 1381 SCCs.end()); 1382 SCCIndices.clear(); 1383 for (int i = 0, Size = SCCs.size(); i < Size; ++i) 1384 SCCIndices[SCCs[i]] = i; 1385 1386 #ifndef NDEBUG 1387 // Now we need to reconnect the current (root) SCC to the graph. We do this 1388 // manually because we can special case our leaf handling and detect errors. 1389 bool IsLeaf = true; 1390 #endif 1391 for (SCC *C : SCCs) 1392 for (Node &N : *C) { 1393 for (Edge &E : *N) { 1394 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode()); 1395 if (&ChildRC == this) 1396 continue; 1397 ChildRC.Parents.insert(this); 1398 #ifndef NDEBUG 1399 IsLeaf = false; 1400 #endif 1401 } 1402 } 1403 #ifndef NDEBUG 1404 if (!Result.empty()) 1405 assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new " 1406 "SCCs by removing this edge."); 1407 if (none_of(G->LeafRefSCCs, [&](RefSCC *C) { return C == this; })) 1408 assert(!IsLeaf && "This SCC cannot be a leaf as it already had child " 1409 "SCCs before we removed this edge."); 1410 #endif 1411 // And connect both this RefSCC and all the new ones to the correct parents. 1412 // The easiest way to do this is just to re-analyze the old parent set. 1413 SmallVector<RefSCC *, 4> OldParents(Parents.begin(), Parents.end()); 1414 Parents.clear(); 1415 for (RefSCC *ParentRC : OldParents) 1416 for (SCC &ParentC : *ParentRC) 1417 for (Node &ParentN : ParentC) 1418 for (Edge &E : *ParentN) { 1419 RefSCC &RC = *G->lookupRefSCC(E.getNode()); 1420 if (&RC != ParentRC) 1421 RC.Parents.insert(ParentRC); 1422 } 1423 1424 // If this SCC stopped being a leaf through this edge removal, remove it from 1425 // the leaf SCC list. Note that this DTRT in the case where this was never 1426 // a leaf. 1427 // FIXME: As LeafRefSCCs could be very large, we might want to not walk the 1428 // entire list if this RefSCC wasn't a leaf before the edge removal. 1429 if (!Result.empty()) 1430 G->LeafRefSCCs.erase( 1431 std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this), 1432 G->LeafRefSCCs.end()); 1433 1434 #ifndef NDEBUG 1435 // Verify all of the new RefSCCs. 1436 for (RefSCC *RC : Result) 1437 RC->verify(); 1438 #endif 1439 1440 // Return the new list of SCCs. 1441 return Result; 1442 } 1443 1444 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN, 1445 Node &TargetN) { 1446 // The only trivial case that requires any graph updates is when we add new 1447 // ref edge and may connect different RefSCCs along that path. This is only 1448 // because of the parents set. Every other part of the graph remains constant 1449 // after this edge insertion. 1450 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC."); 1451 RefSCC &TargetRC = *G->lookupRefSCC(TargetN); 1452 if (&TargetRC == this) { 1453 1454 return; 1455 } 1456 1457 #ifdef EXPENSIVE_CHECKS 1458 assert(TargetRC.isDescendantOf(*this) && 1459 "Target must be a descendant of the Source."); 1460 #endif 1461 // The only change required is to add this RefSCC to the parent set of the 1462 // target. This is a set and so idempotent if the edge already existed. 1463 TargetRC.Parents.insert(this); 1464 } 1465 1466 void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN, 1467 Node &TargetN) { 1468 #ifndef NDEBUG 1469 // Check that the RefSCC is still valid when we finish. 1470 auto ExitVerifier = make_scope_exit([this] { verify(); }); 1471 1472 #ifdef EXPENSIVE_CHECKS 1473 // Check that we aren't breaking some invariants of the SCC graph. Note that 1474 // this is quadratic in the number of edges in the call graph! 1475 SCC &SourceC = *G->lookupSCC(SourceN); 1476 SCC &TargetC = *G->lookupSCC(TargetN); 1477 if (&SourceC != &TargetC) 1478 assert(SourceC.isAncestorOf(TargetC) && 1479 "Call edge is not trivial in the SCC graph!"); 1480 #endif // EXPENSIVE_CHECKS 1481 #endif // NDEBUG 1482 1483 // First insert it into the source or find the existing edge. 1484 auto InsertResult = 1485 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()}); 1486 if (!InsertResult.second) { 1487 // Already an edge, just update it. 1488 Edge &E = SourceN->Edges[InsertResult.first->second]; 1489 if (E.isCall()) 1490 return; // Nothing to do! 1491 E.setKind(Edge::Call); 1492 } else { 1493 // Create the new edge. 1494 SourceN->Edges.emplace_back(TargetN, Edge::Call); 1495 } 1496 1497 // Now that we have the edge, handle the graph fallout. 1498 handleTrivialEdgeInsertion(SourceN, TargetN); 1499 } 1500 1501 void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) { 1502 #ifndef NDEBUG 1503 // Check that the RefSCC is still valid when we finish. 1504 auto ExitVerifier = make_scope_exit([this] { verify(); }); 1505 1506 #ifdef EXPENSIVE_CHECKS 1507 // Check that we aren't breaking some invariants of the RefSCC graph. 1508 RefSCC &SourceRC = *G->lookupRefSCC(SourceN); 1509 RefSCC &TargetRC = *G->lookupRefSCC(TargetN); 1510 if (&SourceRC != &TargetRC) 1511 assert(SourceRC.isAncestorOf(TargetRC) && 1512 "Ref edge is not trivial in the RefSCC graph!"); 1513 #endif // EXPENSIVE_CHECKS 1514 #endif // NDEBUG 1515 1516 // First insert it into the source or find the existing edge. 1517 auto InsertResult = 1518 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()}); 1519 if (!InsertResult.second) 1520 // Already an edge, we're done. 1521 return; 1522 1523 // Create the new edge. 1524 SourceN->Edges.emplace_back(TargetN, Edge::Ref); 1525 1526 // Now that we have the edge, handle the graph fallout. 1527 handleTrivialEdgeInsertion(SourceN, TargetN); 1528 } 1529 1530 void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) { 1531 Function &OldF = N.getFunction(); 1532 1533 #ifndef NDEBUG 1534 // Check that the RefSCC is still valid when we finish. 1535 auto ExitVerifier = make_scope_exit([this] { verify(); }); 1536 1537 assert(G->lookupRefSCC(N) == this && 1538 "Cannot replace the function of a node outside this RefSCC."); 1539 1540 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() && 1541 "Must not have already walked the new function!'"); 1542 1543 // It is important that this replacement not introduce graph changes so we 1544 // insist that the caller has already removed every use of the original 1545 // function and that all uses of the new function correspond to existing 1546 // edges in the graph. The common and expected way to use this is when 1547 // replacing the function itself in the IR without changing the call graph 1548 // shape and just updating the analysis based on that. 1549 assert(&OldF != &NewF && "Cannot replace a function with itself!"); 1550 assert(OldF.use_empty() && 1551 "Must have moved all uses from the old function to the new!"); 1552 #endif 1553 1554 N.replaceFunction(NewF); 1555 1556 // Update various call graph maps. 1557 G->NodeMap.erase(&OldF); 1558 G->NodeMap[&NewF] = &N; 1559 } 1560 1561 void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) { 1562 assert(SCCMap.empty() && 1563 "This method cannot be called after SCCs have been formed!"); 1564 1565 return SourceN->insertEdgeInternal(TargetN, EK); 1566 } 1567 1568 void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) { 1569 assert(SCCMap.empty() && 1570 "This method cannot be called after SCCs have been formed!"); 1571 1572 bool Removed = SourceN->removeEdgeInternal(TargetN); 1573 (void)Removed; 1574 assert(Removed && "Target not in the edge set for this caller?"); 1575 } 1576 1577 void LazyCallGraph::removeDeadFunction(Function &F) { 1578 // FIXME: This is unnecessarily restrictive. We should be able to remove 1579 // functions which recursively call themselves. 1580 assert(F.use_empty() && 1581 "This routine should only be called on trivially dead functions!"); 1582 1583 auto NI = NodeMap.find(&F); 1584 if (NI == NodeMap.end()) 1585 // Not in the graph at all! 1586 return; 1587 1588 Node &N = *NI->second; 1589 NodeMap.erase(NI); 1590 1591 // Remove this from the entry edges if present. 1592 EntryEdges.removeEdgeInternal(N); 1593 1594 if (SCCMap.empty()) { 1595 // No SCCs have been formed, so removing this is fine and there is nothing 1596 // else necessary at this point but clearing out the node. 1597 N.clear(); 1598 return; 1599 } 1600 1601 // Cannot remove a function which has yet to be visited in the DFS walk, so 1602 // if we have a node at all then we must have an SCC and RefSCC. 1603 auto CI = SCCMap.find(&N); 1604 assert(CI != SCCMap.end() && 1605 "Tried to remove a node without an SCC after DFS walk started!"); 1606 SCC &C = *CI->second; 1607 SCCMap.erase(CI); 1608 RefSCC &RC = C.getOuterRefSCC(); 1609 1610 // This node must be the only member of its SCC as it has no callers, and 1611 // that SCC must be the only member of a RefSCC as it has no references. 1612 // Validate these properties first. 1613 assert(C.size() == 1 && "Dead functions must be in a singular SCC"); 1614 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC"); 1615 1616 // Clean up any remaining reference edges. Note that we walk an unordered set 1617 // here but are just removing and so the order doesn't matter. 1618 for (RefSCC &ParentRC : RC.parents()) 1619 for (SCC &ParentC : ParentRC) 1620 for (Node &ParentN : ParentC) 1621 if (ParentN) 1622 ParentN->removeEdgeInternal(N); 1623 1624 // Now remove this RefSCC from any parents sets and the leaf list. 1625 for (Edge &E : *N) 1626 if (RefSCC *TargetRC = lookupRefSCC(E.getNode())) 1627 TargetRC->Parents.erase(&RC); 1628 // FIXME: This is a linear operation which could become hot and benefit from 1629 // an index map. 1630 auto LRI = find(LeafRefSCCs, &RC); 1631 if (LRI != LeafRefSCCs.end()) 1632 LeafRefSCCs.erase(LRI); 1633 1634 auto RCIndexI = RefSCCIndices.find(&RC); 1635 int RCIndex = RCIndexI->second; 1636 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex); 1637 RefSCCIndices.erase(RCIndexI); 1638 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i) 1639 RefSCCIndices[PostOrderRefSCCs[i]] = i; 1640 1641 // Finally clear out all the data structures from the node down through the 1642 // components. 1643 N.clear(); 1644 C.clear(); 1645 RC.clear(); 1646 1647 // Nothing to delete as all the objects are allocated in stable bump pointer 1648 // allocators. 1649 } 1650 1651 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) { 1652 return *new (MappedN = BPA.Allocate()) Node(*this, F); 1653 } 1654 1655 void LazyCallGraph::updateGraphPtrs() { 1656 // Process all nodes updating the graph pointers. 1657 { 1658 SmallVector<Node *, 16> Worklist; 1659 for (Edge &E : EntryEdges) 1660 Worklist.push_back(&E.getNode()); 1661 1662 while (!Worklist.empty()) { 1663 Node &N = *Worklist.pop_back_val(); 1664 N.G = this; 1665 if (N) 1666 for (Edge &E : *N) 1667 Worklist.push_back(&E.getNode()); 1668 } 1669 } 1670 1671 // Process all SCCs updating the graph pointers. 1672 { 1673 SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end()); 1674 1675 while (!Worklist.empty()) { 1676 RefSCC &C = *Worklist.pop_back_val(); 1677 C.G = this; 1678 for (RefSCC &ParentC : C.parents()) 1679 Worklist.push_back(&ParentC); 1680 } 1681 } 1682 } 1683 1684 template <typename RootsT, typename GetBeginT, typename GetEndT, 1685 typename GetNodeT, typename FormSCCCallbackT> 1686 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin, 1687 GetEndT &&GetEnd, GetNodeT &&GetNode, 1688 FormSCCCallbackT &&FormSCC) { 1689 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT; 1690 1691 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack; 1692 SmallVector<Node *, 16> PendingSCCStack; 1693 1694 // Scan down the stack and DFS across the call edges. 1695 for (Node *RootN : Roots) { 1696 assert(DFSStack.empty() && 1697 "Cannot begin a new root with a non-empty DFS stack!"); 1698 assert(PendingSCCStack.empty() && 1699 "Cannot begin a new root with pending nodes for an SCC!"); 1700 1701 // Skip any nodes we've already reached in the DFS. 1702 if (RootN->DFSNumber != 0) { 1703 assert(RootN->DFSNumber == -1 && 1704 "Shouldn't have any mid-DFS root nodes!"); 1705 continue; 1706 } 1707 1708 RootN->DFSNumber = RootN->LowLink = 1; 1709 int NextDFSNumber = 2; 1710 1711 DFSStack.push_back({RootN, GetBegin(*RootN)}); 1712 do { 1713 Node *N; 1714 EdgeItT I; 1715 std::tie(N, I) = DFSStack.pop_back_val(); 1716 auto E = GetEnd(*N); 1717 while (I != E) { 1718 Node &ChildN = GetNode(I); 1719 if (ChildN.DFSNumber == 0) { 1720 // We haven't yet visited this child, so descend, pushing the current 1721 // node onto the stack. 1722 DFSStack.push_back({N, I}); 1723 1724 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++; 1725 N = &ChildN; 1726 I = GetBegin(*N); 1727 E = GetEnd(*N); 1728 continue; 1729 } 1730 1731 // If the child has already been added to some child component, it 1732 // couldn't impact the low-link of this parent because it isn't 1733 // connected, and thus its low-link isn't relevant so skip it. 1734 if (ChildN.DFSNumber == -1) { 1735 ++I; 1736 continue; 1737 } 1738 1739 // Track the lowest linked child as the lowest link for this node. 1740 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!"); 1741 if (ChildN.LowLink < N->LowLink) 1742 N->LowLink = ChildN.LowLink; 1743 1744 // Move to the next edge. 1745 ++I; 1746 } 1747 1748 // We've finished processing N and its descendents, put it on our pending 1749 // SCC stack to eventually get merged into an SCC of nodes. 1750 PendingSCCStack.push_back(N); 1751 1752 // If this node is linked to some lower entry, continue walking up the 1753 // stack. 1754 if (N->LowLink != N->DFSNumber) 1755 continue; 1756 1757 // Otherwise, we've completed an SCC. Append it to our post order list of 1758 // SCCs. 1759 int RootDFSNumber = N->DFSNumber; 1760 // Find the range of the node stack by walking down until we pass the 1761 // root DFS number. 1762 auto SCCNodes = make_range( 1763 PendingSCCStack.rbegin(), 1764 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) { 1765 return N->DFSNumber < RootDFSNumber; 1766 })); 1767 // Form a new SCC out of these nodes and then clear them off our pending 1768 // stack. 1769 FormSCC(SCCNodes); 1770 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end()); 1771 } while (!DFSStack.empty()); 1772 } 1773 } 1774 1775 /// Build the internal SCCs for a RefSCC from a sequence of nodes. 1776 /// 1777 /// Appends the SCCs to the provided vector and updates the map with their 1778 /// indices. Both the vector and map must be empty when passed into this 1779 /// routine. 1780 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) { 1781 assert(RC.SCCs.empty() && "Already built SCCs!"); 1782 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!"); 1783 1784 for (Node *N : Nodes) { 1785 assert(N->LowLink >= (*Nodes.begin())->LowLink && 1786 "We cannot have a low link in an SCC lower than its root on the " 1787 "stack!"); 1788 1789 // This node will go into the next RefSCC, clear out its DFS and low link 1790 // as we scan. 1791 N->DFSNumber = N->LowLink = 0; 1792 } 1793 1794 // Each RefSCC contains a DAG of the call SCCs. To build these, we do 1795 // a direct walk of the call edges using Tarjan's algorithm. We reuse the 1796 // internal storage as we won't need it for the outer graph's DFS any longer. 1797 buildGenericSCCs( 1798 Nodes, [](Node &N) { return N->call_begin(); }, 1799 [](Node &N) { return N->call_end(); }, 1800 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); }, 1801 [this, &RC](node_stack_range Nodes) { 1802 RC.SCCs.push_back(createSCC(RC, Nodes)); 1803 for (Node &N : *RC.SCCs.back()) { 1804 N.DFSNumber = N.LowLink = -1; 1805 SCCMap[&N] = RC.SCCs.back(); 1806 } 1807 }); 1808 1809 // Wire up the SCC indices. 1810 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i) 1811 RC.SCCIndices[RC.SCCs[i]] = i; 1812 } 1813 1814 void LazyCallGraph::buildRefSCCs() { 1815 if (EntryEdges.empty() || !PostOrderRefSCCs.empty()) 1816 // RefSCCs are either non-existent or already built! 1817 return; 1818 1819 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!"); 1820 1821 SmallVector<Node *, 16> Roots; 1822 for (Edge &E : *this) 1823 Roots.push_back(&E.getNode()); 1824 1825 // The roots will be popped of a stack, so use reverse to get a less 1826 // surprising order. This doesn't change any of the semantics anywhere. 1827 std::reverse(Roots.begin(), Roots.end()); 1828 1829 buildGenericSCCs( 1830 Roots, 1831 [](Node &N) { 1832 // We need to populate each node as we begin to walk its edges. 1833 N.populate(); 1834 return N->begin(); 1835 }, 1836 [](Node &N) { return N->end(); }, 1837 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); }, 1838 [this](node_stack_range Nodes) { 1839 RefSCC *NewRC = createRefSCC(*this); 1840 buildSCCs(*NewRC, Nodes); 1841 connectRefSCC(*NewRC); 1842 1843 // Push the new node into the postorder list and remember its position 1844 // in the index map. 1845 bool Inserted = 1846 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second; 1847 (void)Inserted; 1848 assert(Inserted && "Cannot already have this RefSCC in the index map!"); 1849 PostOrderRefSCCs.push_back(NewRC); 1850 #ifndef NDEBUG 1851 NewRC->verify(); 1852 #endif 1853 }); 1854 } 1855 1856 // FIXME: We should move callers of this to embed the parent linking and leaf 1857 // tracking into their DFS in order to remove a full walk of all edges. 1858 void LazyCallGraph::connectRefSCC(RefSCC &RC) { 1859 // Walk all edges in the RefSCC (this remains linear as we only do this once 1860 // when we build the RefSCC) to connect it to the parent sets of its 1861 // children. 1862 bool IsLeaf = true; 1863 for (SCC &C : RC) 1864 for (Node &N : C) 1865 for (Edge &E : *N) { 1866 RefSCC &ChildRC = *lookupRefSCC(E.getNode()); 1867 if (&ChildRC == &RC) 1868 continue; 1869 ChildRC.Parents.insert(&RC); 1870 IsLeaf = false; 1871 } 1872 1873 // For the SCCs where we find no child SCCs, add them to the leaf list. 1874 if (IsLeaf) 1875 LeafRefSCCs.push_back(&RC); 1876 } 1877 1878 AnalysisKey LazyCallGraphAnalysis::Key; 1879 1880 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {} 1881 1882 static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) { 1883 OS << " Edges in function: " << N.getFunction().getName() << "\n"; 1884 for (LazyCallGraph::Edge &E : N.populate()) 1885 OS << " " << (E.isCall() ? "call" : "ref ") << " -> " 1886 << E.getFunction().getName() << "\n"; 1887 1888 OS << "\n"; 1889 } 1890 1891 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) { 1892 ptrdiff_t Size = std::distance(C.begin(), C.end()); 1893 OS << " SCC with " << Size << " functions:\n"; 1894 1895 for (LazyCallGraph::Node &N : C) 1896 OS << " " << N.getFunction().getName() << "\n"; 1897 } 1898 1899 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) { 1900 ptrdiff_t Size = std::distance(C.begin(), C.end()); 1901 OS << " RefSCC with " << Size << " call SCCs:\n"; 1902 1903 for (LazyCallGraph::SCC &InnerC : C) 1904 printSCC(OS, InnerC); 1905 1906 OS << "\n"; 1907 } 1908 1909 PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M, 1910 ModuleAnalysisManager &AM) { 1911 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M); 1912 1913 OS << "Printing the call graph for module: " << M.getModuleIdentifier() 1914 << "\n\n"; 1915 1916 for (Function &F : M) 1917 printNode(OS, G.get(F)); 1918 1919 G.buildRefSCCs(); 1920 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs()) 1921 printRefSCC(OS, C); 1922 1923 return PreservedAnalyses::all(); 1924 } 1925 1926 LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS) 1927 : OS(OS) {} 1928 1929 static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) { 1930 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\""; 1931 1932 for (LazyCallGraph::Edge &E : N.populate()) { 1933 OS << " " << Name << " -> \"" 1934 << DOT::EscapeString(E.getFunction().getName()) << "\""; 1935 if (!E.isCall()) // It is a ref edge. 1936 OS << " [style=dashed,label=\"ref\"]"; 1937 OS << ";\n"; 1938 } 1939 1940 OS << "\n"; 1941 } 1942 1943 PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M, 1944 ModuleAnalysisManager &AM) { 1945 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M); 1946 1947 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n"; 1948 1949 for (Function &F : M) 1950 printNodeDOT(OS, G.get(F)); 1951 1952 OS << "}\n"; 1953 1954 return PreservedAnalyses::all(); 1955 } 1956