CallGraphSCCPass.cpp 23 KB

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