1 //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Analysis/CallGraphSCCPass.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LegacyPassManagers.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
31 #define DEBUG_TYPE "cgscc-passmgr"
33 static cl::opt<unsigned>
34 MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
36 STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
38 //===----------------------------------------------------------------------===//
41 /// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
45 class CGPassManager : public ModulePass, public PMDataManager {
48 explicit CGPassManager()
49 : ModulePass(ID), PMDataManager() { }
51 /// run - Execute all of the passes scheduled for execution. Keep track of
52 /// whether any of the passes modifies the module, and if so, return true.
53 bool runOnModule(Module &M) override;
55 using ModulePass::doInitialization;
56 using ModulePass::doFinalization;
58 bool doInitialization(CallGraph &CG);
59 bool doFinalization(CallGraph &CG);
61 /// Pass Manager itself does not invalidate any analysis info.
62 void getAnalysisUsage(AnalysisUsage &Info) const override {
63 // CGPassManager walks SCC and it needs CallGraph.
64 Info.addRequired<CallGraphWrapperPass>();
65 Info.setPreservesAll();
68 const char *getPassName() const override {
69 return "CallGraph Pass Manager";
72 PMDataManager *getAsPMDataManager() override { return this; }
73 Pass *getAsPass() override { return this; }
75 // Print passes managed by this manager
76 void dumpPassStructure(unsigned Offset) override {
77 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
78 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
79 Pass *P = getContainedPass(Index);
80 P->dumpPassStructure(Offset + 1);
81 dumpLastUses(P, Offset+1);
85 Pass *getContainedPass(unsigned N) {
86 assert(N < PassVector.size() && "Pass number out of range!");
87 return static_cast<Pass *>(PassVector[N]);
90 PassManagerType getPassManagerType() const override {
91 return PMT_CallGraphPassManager;
95 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
96 bool &DevirtualizedCall);
98 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
99 CallGraph &CG, bool &CallGraphUpToDate,
100 bool &DevirtualizedCall);
101 bool RefreshCallGraph(CallGraphSCC &CurSCC, CallGraph &CG,
102 bool IsCheckingMode);
105 } // end anonymous namespace.
107 char CGPassManager::ID = 0;
110 bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
111 CallGraph &CG, bool &CallGraphUpToDate,
112 bool &DevirtualizedCall) {
113 bool Changed = false;
114 PMDataManager *PM = P->getAsPMDataManager();
117 CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
118 if (!CallGraphUpToDate) {
119 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
120 CallGraphUpToDate = true;
124 TimeRegion PassTimer(getPassTimer(CGSP));
125 Changed = CGSP->runOnSCC(CurSCC);
128 // After the CGSCCPass is done, when assertions are enabled, use
129 // RefreshCallGraph to verify that the callgraph was correctly updated.
132 RefreshCallGraph(CurSCC, CG, true);
139 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
140 "Invalid CGPassManager member");
141 FPPassManager *FPP = (FPPassManager*)P;
143 // Run pass P on all functions in the current SCC.
144 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
146 if (Function *F = (*I)->getFunction()) {
147 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
148 TimeRegion PassTimer(getPassTimer(FPP));
149 Changed |= FPP->runOnFunction(*F);
153 // The function pass(es) modified the IR, they may have clobbered the
155 if (Changed && CallGraphUpToDate) {
156 DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
157 << P->getPassName() << '\n');
158 CallGraphUpToDate = false;
164 /// RefreshCallGraph - Scan the functions in the specified CFG and resync the
165 /// callgraph with the call sites found in it. This is used after
166 /// FunctionPasses have potentially munged the callgraph, and can be used after
167 /// CallGraphSCC passes to verify that they correctly updated the callgraph.
169 /// This function returns true if it devirtualized an existing function call,
170 /// meaning it turned an indirect call into a direct call. This happens when
171 /// a function pass like GVN optimizes away stuff feeding the indirect call.
172 /// This never happens in checking mode.
174 bool CGPassManager::RefreshCallGraph(CallGraphSCC &CurSCC,
175 CallGraph &CG, bool CheckingMode) {
176 DenseMap<Value*, CallGraphNode*> CallSites;
178 DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
180 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
185 bool MadeChange = false;
186 bool DevirtualizedCall = false;
188 // Scan all functions in the SCC.
189 unsigned FunctionNo = 0;
190 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
191 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
192 CallGraphNode *CGN = *SCCIdx;
193 Function *F = CGN->getFunction();
194 if (!F || F->isDeclaration()) continue;
196 // Walk the function body looking for call sites. Sync up the call sites in
197 // CGN with those actually in the function.
199 // Keep track of the number of direct and indirect calls that were
200 // invalidated and removed.
201 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
203 // Get the set of call sites currently in the function.
204 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
205 // If this call site is null, then the function pass deleted the call
206 // entirely and the WeakVH nulled it out.
208 // If we've already seen this call site, then the FunctionPass RAUW'd
209 // one call with another, which resulted in two "uses" in the edge
210 // list of the same call.
211 CallSites.count(I->first) ||
213 // If the call edge is not from a call or invoke, then the function
214 // pass RAUW'd a call with another value. This can happen when
215 // constant folding happens of well known functions etc.
216 !CallSite(I->first)) {
217 assert(!CheckingMode &&
218 "CallGraphSCCPass did not update the CallGraph correctly!");
220 // If this was an indirect call site, count it.
221 if (!I->second->getFunction())
222 ++NumIndirectRemoved;
226 // Just remove the edge from the set of callees, keep track of whether
227 // I points to the last element of the vector.
228 bool WasLast = I + 1 == E;
229 CGN->removeCallEdge(I);
231 // If I pointed to the last element of the vector, we have to bail out:
232 // iterator checking rejects comparisons of the resultant pointer with
240 assert(!CallSites.count(I->first) &&
241 "Call site occurs in node multiple times");
242 CallSites.insert(std::make_pair(I->first, I->second));
246 // Loop over all of the instructions in the function, getting the callsites.
247 // Keep track of the number of direct/indirect calls added.
248 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
250 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
252 CallSite CS(cast<Value>(I));
254 Function *Callee = CS.getCalledFunction();
255 if (Callee && Callee->isIntrinsic()) continue;
257 // If this call site already existed in the callgraph, just verify it
258 // matches up to expectations and remove it from CallSites.
259 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
260 CallSites.find(CS.getInstruction());
261 if (ExistingIt != CallSites.end()) {
262 CallGraphNode *ExistingNode = ExistingIt->second;
264 // Remove from CallSites since we have now seen it.
265 CallSites.erase(ExistingIt);
267 // Verify that the callee is right.
268 if (ExistingNode->getFunction() == CS.getCalledFunction())
271 // If we are in checking mode, we are not allowed to actually mutate
272 // the callgraph. If this is a case where we can infer that the
273 // callgraph is less precise than it could be (e.g. an indirect call
274 // site could be turned direct), don't reject it in checking mode, and
275 // don't tweak it to be more precise.
276 if (CheckingMode && CS.getCalledFunction() &&
277 ExistingNode->getFunction() == nullptr)
280 assert(!CheckingMode &&
281 "CallGraphSCCPass did not update the CallGraph correctly!");
283 // If not, we either went from a direct call to indirect, indirect to
284 // direct, or direct to different direct.
285 CallGraphNode *CalleeNode;
286 if (Function *Callee = CS.getCalledFunction()) {
287 CalleeNode = CG.getOrInsertFunction(Callee);
288 // Keep track of whether we turned an indirect call into a direct
290 if (!ExistingNode->getFunction()) {
291 DevirtualizedCall = true;
292 DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
293 << Callee->getName() << "'\n");
296 CalleeNode = CG.getCallsExternalNode();
299 // Update the edge target in CGN.
300 CGN->replaceCallEdge(CS, CS, CalleeNode);
305 assert(!CheckingMode &&
306 "CallGraphSCCPass did not update the CallGraph correctly!");
308 // If the call site didn't exist in the CGN yet, add it.
309 CallGraphNode *CalleeNode;
310 if (Function *Callee = CS.getCalledFunction()) {
311 CalleeNode = CG.getOrInsertFunction(Callee);
314 CalleeNode = CG.getCallsExternalNode();
318 CGN->addCalledFunction(CS, CalleeNode);
322 // We scanned the old callgraph node, removing invalidated call sites and
323 // then added back newly found call sites. One thing that can happen is
324 // that an old indirect call site was deleted and replaced with a new direct
325 // call. In this case, we have devirtualized a call, and CGSCCPM would like
326 // to iteratively optimize the new code. Unfortunately, we don't really
327 // have a great way to detect when this happens. As an approximation, we
328 // just look at whether the number of indirect calls is reduced and the
329 // number of direct calls is increased. There are tons of ways to fool this
330 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
331 // direct call) but this is close enough.
332 if (NumIndirectRemoved > NumIndirectAdded &&
333 NumDirectRemoved < NumDirectAdded)
334 DevirtualizedCall = true;
336 // After scanning this function, if we still have entries in callsites, then
337 // they are dangling pointers. WeakVH should save us for this, so abort if
339 assert(CallSites.empty() && "Dangling pointers found in call sites map");
341 // Periodically do an explicit clear to remove tombstones when processing
343 if ((FunctionNo & 15) == 15)
347 DEBUG(if (MadeChange) {
348 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
349 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
352 if (DevirtualizedCall)
353 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
356 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
361 return DevirtualizedCall;
364 /// RunAllPassesOnSCC - Execute the body of the entire pass manager on the
365 /// specified SCC. This keeps track of whether a function pass devirtualizes
366 /// any calls and returns it in DevirtualizedCall.
367 bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
368 bool &DevirtualizedCall) {
369 bool Changed = false;
371 // CallGraphUpToDate - Keep track of whether the callgraph is known to be
372 // up-to-date or not. The CGSSC pass manager runs two types of passes:
373 // CallGraphSCC Passes and other random function passes. Because other
374 // random function passes are not CallGraph aware, they may clobber the
375 // call graph by introducing new calls or deleting other ones. This flag
376 // is set to false when we run a function pass so that we know to clean up
377 // the callgraph when we need to run a CGSCCPass again.
378 bool CallGraphUpToDate = true;
380 // Run all passes on current SCC.
381 for (unsigned PassNo = 0, e = getNumContainedPasses();
382 PassNo != e; ++PassNo) {
383 Pass *P = getContainedPass(PassNo);
385 // If we're in -debug-pass=Executions mode, construct the SCC node list,
386 // otherwise avoid constructing this string as it is expensive.
387 if (isPassDebuggingExecutionsOrMore()) {
388 std::string Functions;
390 raw_string_ostream OS(Functions);
391 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
393 if (I != CurSCC.begin()) OS << ", ";
398 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
402 initializeAnalysisImpl(P);
404 // Actually run this pass on the current SCC.
405 Changed |= RunPassOnSCC(P, CurSCC, CG,
406 CallGraphUpToDate, DevirtualizedCall);
409 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
412 verifyPreservedAnalysis(P);
413 removeNotPreservedAnalysis(P);
414 recordAvailableAnalysis(P);
415 removeDeadPasses(P, "", ON_CG_MSG);
418 // If the callgraph was left out of date (because the last pass run was a
419 // functionpass), refresh it before we move on to the next SCC.
420 if (!CallGraphUpToDate)
421 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
425 /// run - Execute all of the passes scheduled for execution. Keep track of
426 /// whether any of the passes modifies the module, and if so, return true.
427 bool CGPassManager::runOnModule(Module &M) {
428 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
429 bool Changed = doInitialization(CG);
431 // Walk the callgraph in bottom-up SCC order.
432 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
434 CallGraphSCC CurSCC(&CGI);
435 while (!CGI.isAtEnd()) {
436 // Copy the current SCC and increment past it so that the pass can hack
437 // on the SCC if it wants to without invalidating our iterator.
438 const std::vector<CallGraphNode *> &NodeVec = *CGI;
439 CurSCC.initialize(NodeVec.data(), NodeVec.data() + NodeVec.size());
442 // At the top level, we run all the passes in this pass manager on the
443 // functions in this SCC. However, we support iterative compilation in the
444 // case where a function pass devirtualizes a call to a function. For
445 // example, it is very common for a function pass (often GVN or instcombine)
446 // to eliminate the addressing that feeds into a call. With that improved
447 // information, we would like the call to be an inline candidate, infer
448 // mod-ref information etc.
450 // Because of this, we allow iteration up to a specified iteration count.
451 // This only happens in the case of a devirtualized call, so we only burn
452 // compile time in the case that we're making progress. We also have a hard
453 // iteration count limit in case there is crazy code.
454 unsigned Iteration = 0;
455 bool DevirtualizedCall = false;
458 dbgs() << " SCCPASSMGR: Re-visiting SCC, iteration #"
459 << Iteration << '\n');
460 DevirtualizedCall = false;
461 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
462 } while (Iteration++ < MaxIterations && DevirtualizedCall);
464 if (DevirtualizedCall)
465 DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " << Iteration
466 << " times, due to -max-cg-scc-iterations\n");
468 if (Iteration > MaxSCCIterations)
469 MaxSCCIterations = Iteration;
472 Changed |= doFinalization(CG);
478 bool CGPassManager::doInitialization(CallGraph &CG) {
479 bool Changed = false;
480 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
481 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
482 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
483 "Invalid CGPassManager member");
484 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
486 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
493 bool CGPassManager::doFinalization(CallGraph &CG) {
494 bool Changed = false;
495 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
496 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
497 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
498 "Invalid CGPassManager member");
499 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
501 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
507 //===----------------------------------------------------------------------===//
508 // CallGraphSCC Implementation
509 //===----------------------------------------------------------------------===//
511 /// ReplaceNode - This informs the SCC and the pass manager that the specified
512 /// Old node has been deleted, and New is to be used in its place.
513 void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
514 assert(Old != New && "Should not replace node with self");
515 for (unsigned i = 0; ; ++i) {
516 assert(i != Nodes.size() && "Node not in SCC");
517 if (Nodes[i] != Old) continue;
522 // Update the active scc_iterator so that it doesn't contain dangling
523 // pointers to the old CallGraphNode.
524 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
525 CGI->ReplaceNode(Old, New);
529 //===----------------------------------------------------------------------===//
530 // CallGraphSCCPass Implementation
531 //===----------------------------------------------------------------------===//
533 /// Assign pass manager to manage this pass.
534 void CallGraphSCCPass::assignPassManager(PMStack &PMS,
535 PassManagerType PreferredType) {
536 // Find CGPassManager
537 while (!PMS.empty() &&
538 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
541 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
544 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
545 CGP = (CGPassManager*)PMS.top();
547 // Create new Call Graph SCC Pass Manager if it does not exist.
548 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
549 PMDataManager *PMD = PMS.top();
551 // [1] Create new Call Graph Pass Manager
552 CGP = new CGPassManager();
554 // [2] Set up new manager's top level manager
555 PMTopLevelManager *TPM = PMD->getTopLevelManager();
556 TPM->addIndirectPassManager(CGP);
558 // [3] Assign manager to manage this new manager. This may create
559 // and push new managers into PMS
561 TPM->schedulePass(P);
563 // [4] Push new manager into PMS
570 /// getAnalysisUsage - For this class, we declare that we require and preserve
571 /// the call graph. If the derived class implements this method, it should
572 /// always explicitly call the implementation here.
573 void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
574 AU.addRequired<CallGraphWrapperPass>();
575 AU.addPreserved<CallGraphWrapperPass>();
579 //===----------------------------------------------------------------------===//
580 // PrintCallGraphPass Implementation
581 //===----------------------------------------------------------------------===//
584 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
586 class PrintCallGraphPass : public CallGraphSCCPass {
588 raw_ostream &Out; // raw_ostream to print on.
592 PrintCallGraphPass(const std::string &B, raw_ostream &o)
593 : CallGraphSCCPass(ID), Banner(B), Out(o) {}
595 void getAnalysisUsage(AnalysisUsage &AU) const override {
596 AU.setPreservesAll();
599 bool runOnSCC(CallGraphSCC &SCC) override {
601 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
602 (*I)->getFunction()->print(Out);
607 } // end anonymous namespace.
609 char PrintCallGraphPass::ID = 0;
611 Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
612 const std::string &Banner) const {
613 return new PrintCallGraphPass(Banner, O);