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