1 //===- CallGraphSCCPass.cpp - Pass that operates BU on 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 // This file implements the CallGraphSCCPass class, which is used for passes 11 // which are implemented as bottom-up traversals on the call graph. Because 12 // there may be cycles in the call graph, passes of this type operate on the 13 // call-graph in SCC order: that is, they process function bottom-up, except for 14 // recursive functions, which they process all at once. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Analysis/CallGraphSCCPass.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/SCCIterator.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/CallGraph.h" 23 #include "llvm/IR/CallSite.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/Intrinsics.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/LegacyPassManagers.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/OptBisect.h" 30 #include "llvm/IR/PassTimingInfo.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/Timer.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <cassert> 37 #include <string> 38 #include <utility> 39 #include <vector> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "cgscc-passmgr" 44 45 static cl::opt<unsigned> 46 MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4)); 47 48 STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC"); 49 50 //===----------------------------------------------------------------------===// 51 // CGPassManager 52 // 53 /// CGPassManager manages FPPassManagers and CallGraphSCCPasses. 54 55 namespace { 56 57 class CGPassManager : public ModulePass, public PMDataManager { 58 public: 59 static char ID; 60 61 explicit CGPassManager() : ModulePass(ID), PMDataManager() {} 62 63 /// Execute all of the passes scheduled for execution. Keep track of 64 /// whether any of the passes modifies the module, and if so, return true. 65 bool runOnModule(Module &M) override; 66 67 using ModulePass::doInitialization; 68 using ModulePass::doFinalization; 69 70 bool doInitialization(CallGraph &CG); 71 bool doFinalization(CallGraph &CG); 72 73 /// Pass Manager itself does not invalidate any analysis info. 74 void getAnalysisUsage(AnalysisUsage &Info) const override { 75 // CGPassManager walks SCC and it needs CallGraph. 76 Info.addRequired<CallGraphWrapperPass>(); 77 Info.setPreservesAll(); 78 } 79 80 StringRef getPassName() const override { return "CallGraph Pass Manager"; } 81 82 PMDataManager *getAsPMDataManager() override { return this; } 83 Pass *getAsPass() override { return this; } 84 85 // Print passes managed by this manager 86 void dumpPassStructure(unsigned Offset) override { 87 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n"; 88 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 89 Pass *P = getContainedPass(Index); 90 P->dumpPassStructure(Offset + 1); 91 dumpLastUses(P, Offset+1); 92 } 93 } 94 95 Pass *getContainedPass(unsigned N) { 96 assert(N < PassVector.size() && "Pass number out of range!"); 97 return static_cast<Pass *>(PassVector[N]); 98 } 99 100 PassManagerType getPassManagerType() const override { 101 return PMT_CallGraphPassManager; 102 } 103 104 private: 105 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG, 106 bool &DevirtualizedCall); 107 108 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC, 109 CallGraph &CG, bool &CallGraphUpToDate, 110 bool &DevirtualizedCall); 111 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG, 112 bool IsCheckingMode); 113 }; 114 115 } // end anonymous namespace. 116 117 char CGPassManager::ID = 0; 118 119 bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC, 120 CallGraph &CG, bool &CallGraphUpToDate, 121 bool &DevirtualizedCall) { 122 bool Changed = false; 123 PMDataManager *PM = P->getAsPMDataManager(); 124 Module &M = CG.getModule(); 125 126 if (!PM) { 127 CallGraphSCCPass *CGSP = (CallGraphSCCPass *)P; 128 if (!CallGraphUpToDate) { 129 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false); 130 CallGraphUpToDate = true; 131 } 132 133 { 134 unsigned InstrCount, SCCCount = 0; 135 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark(); 136 TimeRegion PassTimer(getPassTimer(CGSP)); 137 if (EmitICRemark) 138 InstrCount = initSizeRemarkInfo(M); 139 Changed = CGSP->runOnSCC(CurSCC); 140 141 if (EmitICRemark) { 142 // FIXME: Add getInstructionCount to CallGraphSCC. 143 SCCCount = M.getInstructionCount(); 144 // Is there a difference in the number of instructions in the module? 145 if (SCCCount != InstrCount) { 146 // Yep. Emit a remark and update InstrCount. 147 int64_t Delta = 148 static_cast<int64_t>(SCCCount) - static_cast<int64_t>(InstrCount); 149 emitInstrCountChangedRemark(P, M, Delta, InstrCount); 150 InstrCount = SCCCount; 151 } 152 } 153 } 154 155 // After the CGSCCPass is done, when assertions are enabled, use 156 // RefreshCallGraph to verify that the callgraph was correctly updated. 157 #ifndef NDEBUG 158 if (Changed) 159 RefreshCallGraph(CurSCC, CG, true); 160 #endif 161 162 return Changed; 163 } 164 165 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 166 "Invalid CGPassManager member"); 167 FPPassManager *FPP = (FPPassManager*)P; 168 169 // Run pass P on all functions in the current SCC. 170 for (CallGraphNode *CGN : CurSCC) { 171 if (Function *F = CGN->getFunction()) { 172 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName()); 173 { 174 TimeRegion PassTimer(getPassTimer(FPP)); 175 Changed |= FPP->runOnFunction(*F); 176 } 177 F->getContext().yield(); 178 } 179 } 180 181 // The function pass(es) modified the IR, they may have clobbered the 182 // callgraph. 183 if (Changed && CallGraphUpToDate) { 184 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: " << P->getPassName() 185 << '\n'); 186 CallGraphUpToDate = false; 187 } 188 return Changed; 189 } 190 191 /// Scan the functions in the specified CFG and resync the 192 /// callgraph with the call sites found in it. This is used after 193 /// FunctionPasses have potentially munged the callgraph, and can be used after 194 /// CallGraphSCC passes to verify that they correctly updated the callgraph. 195 /// 196 /// This function returns true if it devirtualized an existing function call, 197 /// meaning it turned an indirect call into a direct call. This happens when 198 /// a function pass like GVN optimizes away stuff feeding the indirect call. 199 /// This never happens in checking mode. 200 bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG, 201 bool CheckingMode) { 202 DenseMap<Value*, CallGraphNode*> CallSites; 203 204 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size() 205 << " nodes:\n"; 206 for (CallGraphNode *CGN 207 : CurSCC) CGN->dump();); 208 209 bool MadeChange = false; 210 bool DevirtualizedCall = false; 211 212 // Scan all functions in the SCC. 213 unsigned FunctionNo = 0; 214 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end(); 215 SCCIdx != E; ++SCCIdx, ++FunctionNo) { 216 CallGraphNode *CGN = *SCCIdx; 217 Function *F = CGN->getFunction(); 218 if (!F || F->isDeclaration()) continue; 219 220 // Walk the function body looking for call sites. Sync up the call sites in 221 // CGN with those actually in the function. 222 223 // Keep track of the number of direct and indirect calls that were 224 // invalidated and removed. 225 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0; 226 227 // Get the set of call sites currently in the function. 228 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) { 229 // If this call site is null, then the function pass deleted the call 230 // entirely and the WeakTrackingVH nulled it out. 231 if (!I->first || 232 // If we've already seen this call site, then the FunctionPass RAUW'd 233 // one call with another, which resulted in two "uses" in the edge 234 // list of the same call. 235 CallSites.count(I->first) || 236 237 // If the call edge is not from a call or invoke, or it is a 238 // instrinsic call, then the function pass RAUW'd a call with 239 // another value. This can happen when constant folding happens 240 // of well known functions etc. 241 !CallSite(I->first) || 242 (CallSite(I->first).getCalledFunction() && 243 CallSite(I->first).getCalledFunction()->isIntrinsic() && 244 Intrinsic::isLeaf( 245 CallSite(I->first).getCalledFunction()->getIntrinsicID()))) { 246 assert(!CheckingMode && 247 "CallGraphSCCPass did not update the CallGraph correctly!"); 248 249 // If this was an indirect call site, count it. 250 if (!I->second->getFunction()) 251 ++NumIndirectRemoved; 252 else 253 ++NumDirectRemoved; 254 255 // Just remove the edge from the set of callees, keep track of whether 256 // I points to the last element of the vector. 257 bool WasLast = I + 1 == E; 258 CGN->removeCallEdge(I); 259 260 // If I pointed to the last element of the vector, we have to bail out: 261 // iterator checking rejects comparisons of the resultant pointer with 262 // end. 263 if (WasLast) 264 break; 265 E = CGN->end(); 266 continue; 267 } 268 269 assert(!CallSites.count(I->first) && 270 "Call site occurs in node multiple times"); 271 272 CallSite CS(I->first); 273 if (CS) { 274 Function *Callee = CS.getCalledFunction(); 275 // Ignore intrinsics because they're not really function calls. 276 if (!Callee || !(Callee->isIntrinsic())) 277 CallSites.insert(std::make_pair(I->first, I->second)); 278 } 279 ++I; 280 } 281 282 // Loop over all of the instructions in the function, getting the callsites. 283 // Keep track of the number of direct/indirect calls added. 284 unsigned NumDirectAdded = 0, NumIndirectAdded = 0; 285 286 for (BasicBlock &BB : *F) 287 for (Instruction &I : BB) { 288 CallSite CS(&I); 289 if (!CS) continue; 290 Function *Callee = CS.getCalledFunction(); 291 if (Callee && Callee->isIntrinsic()) continue; 292 293 // If this call site already existed in the callgraph, just verify it 294 // matches up to expectations and remove it from CallSites. 295 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt = 296 CallSites.find(CS.getInstruction()); 297 if (ExistingIt != CallSites.end()) { 298 CallGraphNode *ExistingNode = ExistingIt->second; 299 300 // Remove from CallSites since we have now seen it. 301 CallSites.erase(ExistingIt); 302 303 // Verify that the callee is right. 304 if (ExistingNode->getFunction() == CS.getCalledFunction()) 305 continue; 306 307 // If we are in checking mode, we are not allowed to actually mutate 308 // the callgraph. If this is a case where we can infer that the 309 // callgraph is less precise than it could be (e.g. an indirect call 310 // site could be turned direct), don't reject it in checking mode, and 311 // don't tweak it to be more precise. 312 if (CheckingMode && CS.getCalledFunction() && 313 ExistingNode->getFunction() == nullptr) 314 continue; 315 316 assert(!CheckingMode && 317 "CallGraphSCCPass did not update the CallGraph correctly!"); 318 319 // If not, we either went from a direct call to indirect, indirect to 320 // direct, or direct to different direct. 321 CallGraphNode *CalleeNode; 322 if (Function *Callee = CS.getCalledFunction()) { 323 CalleeNode = CG.getOrInsertFunction(Callee); 324 // Keep track of whether we turned an indirect call into a direct 325 // one. 326 if (!ExistingNode->getFunction()) { 327 DevirtualizedCall = true; 328 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '" 329 << Callee->getName() << "'\n"); 330 } 331 } else { 332 CalleeNode = CG.getCallsExternalNode(); 333 } 334 335 // Update the edge target in CGN. 336 CGN->replaceCallEdge(CS, CS, CalleeNode); 337 MadeChange = true; 338 continue; 339 } 340 341 assert(!CheckingMode && 342 "CallGraphSCCPass did not update the CallGraph correctly!"); 343 344 // If the call site didn't exist in the CGN yet, add it. 345 CallGraphNode *CalleeNode; 346 if (Function *Callee = CS.getCalledFunction()) { 347 CalleeNode = CG.getOrInsertFunction(Callee); 348 ++NumDirectAdded; 349 } else { 350 CalleeNode = CG.getCallsExternalNode(); 351 ++NumIndirectAdded; 352 } 353 354 CGN->addCalledFunction(CS, CalleeNode); 355 MadeChange = true; 356 } 357 358 // We scanned the old callgraph node, removing invalidated call sites and 359 // then added back newly found call sites. One thing that can happen is 360 // that an old indirect call site was deleted and replaced with a new direct 361 // call. In this case, we have devirtualized a call, and CGSCCPM would like 362 // to iteratively optimize the new code. Unfortunately, we don't really 363 // have a great way to detect when this happens. As an approximation, we 364 // just look at whether the number of indirect calls is reduced and the 365 // number of direct calls is increased. There are tons of ways to fool this 366 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a 367 // direct call) but this is close enough. 368 if (NumIndirectRemoved > NumIndirectAdded && 369 NumDirectRemoved < NumDirectAdded) 370 DevirtualizedCall = true; 371 372 // After scanning this function, if we still have entries in callsites, then 373 // they are dangling pointers. WeakTrackingVH should save us for this, so 374 // abort if 375 // this happens. 376 assert(CallSites.empty() && "Dangling pointers found in call sites map"); 377 378 // Periodically do an explicit clear to remove tombstones when processing 379 // large scc's. 380 if ((FunctionNo & 15) == 15) 381 CallSites.clear(); 382 } 383 384 LLVM_DEBUG(if (MadeChange) { 385 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n"; 386 for (CallGraphNode *CGN : CurSCC) 387 CGN->dump(); 388 if (DevirtualizedCall) 389 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n"; 390 } else { 391 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n"; 392 }); 393 (void)MadeChange; 394 395 return DevirtualizedCall; 396 } 397 398 /// Execute the body of the entire pass manager on the specified SCC. 399 /// This keeps track of whether a function pass devirtualizes 400 /// any calls and returns it in DevirtualizedCall. 401 bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG, 402 bool &DevirtualizedCall) { 403 bool Changed = false; 404 405 // Keep track of whether the callgraph is known to be up-to-date or not. 406 // The CGSSC pass manager runs two types of passes: 407 // CallGraphSCC Passes and other random function passes. Because other 408 // random function passes are not CallGraph aware, they may clobber the 409 // call graph by introducing new calls or deleting other ones. This flag 410 // is set to false when we run a function pass so that we know to clean up 411 // the callgraph when we need to run a CGSCCPass again. 412 bool CallGraphUpToDate = true; 413 414 // Run all passes on current SCC. 415 for (unsigned PassNo = 0, e = getNumContainedPasses(); 416 PassNo != e; ++PassNo) { 417 Pass *P = getContainedPass(PassNo); 418 419 // If we're in -debug-pass=Executions mode, construct the SCC node list, 420 // otherwise avoid constructing this string as it is expensive. 421 if (isPassDebuggingExecutionsOrMore()) { 422 std::string Functions; 423 #ifndef NDEBUG 424 raw_string_ostream OS(Functions); 425 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end(); 426 I != E; ++I) { 427 if (I != CurSCC.begin()) OS << ", "; 428 (*I)->print(OS); 429 } 430 OS.flush(); 431 #endif 432 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions); 433 } 434 dumpRequiredSet(P); 435 436 initializeAnalysisImpl(P); 437 438 // Actually run this pass on the current SCC. 439 Changed |= RunPassOnSCC(P, CurSCC, CG, 440 CallGraphUpToDate, DevirtualizedCall); 441 442 if (Changed) 443 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, ""); 444 dumpPreservedSet(P); 445 446 verifyPreservedAnalysis(P); 447 removeNotPreservedAnalysis(P); 448 recordAvailableAnalysis(P); 449 removeDeadPasses(P, "", ON_CG_MSG); 450 } 451 452 // If the callgraph was left out of date (because the last pass run was a 453 // functionpass), refresh it before we move on to the next SCC. 454 if (!CallGraphUpToDate) 455 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false); 456 return Changed; 457 } 458 459 /// Execute all of the passes scheduled for execution. Keep track of 460 /// whether any of the passes modifies the module, and if so, return true. 461 bool CGPassManager::runOnModule(Module &M) { 462 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 463 bool Changed = doInitialization(CG); 464 465 // Walk the callgraph in bottom-up SCC order. 466 scc_iterator<CallGraph*> CGI = scc_begin(&CG); 467 468 CallGraphSCC CurSCC(CG, &CGI); 469 while (!CGI.isAtEnd()) { 470 // Copy the current SCC and increment past it so that the pass can hack 471 // on the SCC if it wants to without invalidating our iterator. 472 const std::vector<CallGraphNode *> &NodeVec = *CGI; 473 CurSCC.initialize(NodeVec); 474 ++CGI; 475 476 // At the top level, we run all the passes in this pass manager on the 477 // functions in this SCC. However, we support iterative compilation in the 478 // case where a function pass devirtualizes a call to a function. For 479 // example, it is very common for a function pass (often GVN or instcombine) 480 // to eliminate the addressing that feeds into a call. With that improved 481 // information, we would like the call to be an inline candidate, infer 482 // mod-ref information etc. 483 // 484 // Because of this, we allow iteration up to a specified iteration count. 485 // This only happens in the case of a devirtualized call, so we only burn 486 // compile time in the case that we're making progress. We also have a hard 487 // iteration count limit in case there is crazy code. 488 unsigned Iteration = 0; 489 bool DevirtualizedCall = false; 490 do { 491 LLVM_DEBUG(if (Iteration) dbgs() 492 << " SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration 493 << '\n'); 494 DevirtualizedCall = false; 495 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall); 496 } while (Iteration++ < MaxIterations && DevirtualizedCall); 497 498 if (DevirtualizedCall) 499 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " 500 << Iteration 501 << " times, due to -max-cg-scc-iterations\n"); 502 503 MaxSCCIterations.updateMax(Iteration); 504 } 505 Changed |= doFinalization(CG); 506 return Changed; 507 } 508 509 /// Initialize CG 510 bool CGPassManager::doInitialization(CallGraph &CG) { 511 bool Changed = false; 512 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) { 513 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { 514 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 515 "Invalid CGPassManager member"); 516 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule()); 517 } else { 518 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG); 519 } 520 } 521 return Changed; 522 } 523 524 /// Finalize CG 525 bool CGPassManager::doFinalization(CallGraph &CG) { 526 bool Changed = false; 527 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) { 528 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { 529 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 530 "Invalid CGPassManager member"); 531 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule()); 532 } else { 533 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG); 534 } 535 } 536 return Changed; 537 } 538 539 //===----------------------------------------------------------------------===// 540 // CallGraphSCC Implementation 541 //===----------------------------------------------------------------------===// 542 543 /// This informs the SCC and the pass manager that the specified 544 /// Old node has been deleted, and New is to be used in its place. 545 void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) { 546 assert(Old != New && "Should not replace node with self"); 547 for (unsigned i = 0; ; ++i) { 548 assert(i != Nodes.size() && "Node not in SCC"); 549 if (Nodes[i] != Old) continue; 550 Nodes[i] = New; 551 break; 552 } 553 554 // Update the active scc_iterator so that it doesn't contain dangling 555 // pointers to the old CallGraphNode. 556 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context; 557 CGI->ReplaceNode(Old, New); 558 } 559 560 //===----------------------------------------------------------------------===// 561 // CallGraphSCCPass Implementation 562 //===----------------------------------------------------------------------===// 563 564 /// Assign pass manager to manage this pass. 565 void CallGraphSCCPass::assignPassManager(PMStack &PMS, 566 PassManagerType PreferredType) { 567 // Find CGPassManager 568 while (!PMS.empty() && 569 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager) 570 PMS.pop(); 571 572 assert(!PMS.empty() && "Unable to handle Call Graph Pass"); 573 CGPassManager *CGP; 574 575 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager) 576 CGP = (CGPassManager*)PMS.top(); 577 else { 578 // Create new Call Graph SCC Pass Manager if it does not exist. 579 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager"); 580 PMDataManager *PMD = PMS.top(); 581 582 // [1] Create new Call Graph Pass Manager 583 CGP = new CGPassManager(); 584 585 // [2] Set up new manager's top level manager 586 PMTopLevelManager *TPM = PMD->getTopLevelManager(); 587 TPM->addIndirectPassManager(CGP); 588 589 // [3] Assign manager to manage this new manager. This may create 590 // and push new managers into PMS 591 Pass *P = CGP; 592 TPM->schedulePass(P); 593 594 // [4] Push new manager into PMS 595 PMS.push(CGP); 596 } 597 598 CGP->add(this); 599 } 600 601 /// For this class, we declare that we require and preserve the call graph. 602 /// If the derived class implements this method, it should 603 /// always explicitly call the implementation here. 604 void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const { 605 AU.addRequired<CallGraphWrapperPass>(); 606 AU.addPreserved<CallGraphWrapperPass>(); 607 } 608 609 //===----------------------------------------------------------------------===// 610 // PrintCallGraphPass Implementation 611 //===----------------------------------------------------------------------===// 612 613 namespace { 614 615 /// PrintCallGraphPass - Print a Module corresponding to a call graph. 616 /// 617 class PrintCallGraphPass : public CallGraphSCCPass { 618 std::string Banner; 619 raw_ostream &OS; // raw_ostream to print on. 620 621 public: 622 static char ID; 623 624 PrintCallGraphPass(const std::string &B, raw_ostream &OS) 625 : CallGraphSCCPass(ID), Banner(B), OS(OS) {} 626 627 void getAnalysisUsage(AnalysisUsage &AU) const override { 628 AU.setPreservesAll(); 629 } 630 631 bool runOnSCC(CallGraphSCC &SCC) override { 632 bool BannerPrinted = false; 633 auto PrintBannerOnce = [&] () { 634 if (BannerPrinted) 635 return; 636 OS << Banner; 637 BannerPrinted = true; 638 }; 639 for (CallGraphNode *CGN : SCC) { 640 if (Function *F = CGN->getFunction()) { 641 if (!F->isDeclaration() && isFunctionInPrintList(F->getName())) { 642 PrintBannerOnce(); 643 F->print(OS); 644 } 645 } else if (isFunctionInPrintList("*")) { 646 PrintBannerOnce(); 647 OS << "\nPrinting <null> Function\n"; 648 } 649 } 650 return false; 651 } 652 653 StringRef getPassName() const override { return "Print CallGraph IR"; } 654 }; 655 656 } // end anonymous namespace. 657 658 char PrintCallGraphPass::ID = 0; 659 660 Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &OS, 661 const std::string &Banner) const { 662 return new PrintCallGraphPass(Banner, OS); 663 } 664 665 bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const { 666 return !SCC.getCallGraph().getModule() 667 .getContext() 668 .getOptPassGate() 669 .shouldRunPass(this, SCC); 670 } 671 672 char DummyCGSCCPass::ID = 0; 673 674 INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false, 675 false) 676