xref: /openbsd-src/gnu/llvm/llvm/lib/Analysis/CallGraphSCCPass.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the CallGraphSCCPass class, which is used for passes
1009467b48Spatrick // which are implemented as bottom-up traversals on the call graph.  Because
1109467b48Spatrick // there may be cycles in the call graph, passes of this type operate on the
1209467b48Spatrick // call-graph in SCC order: that is, they process function bottom-up, except for
1309467b48Spatrick // recursive functions, which they process all at once.
1409467b48Spatrick //
1509467b48Spatrick //===----------------------------------------------------------------------===//
1609467b48Spatrick 
1709467b48Spatrick #include "llvm/Analysis/CallGraphSCCPass.h"
1809467b48Spatrick #include "llvm/ADT/DenseMap.h"
1909467b48Spatrick #include "llvm/ADT/SCCIterator.h"
2009467b48Spatrick #include "llvm/ADT/Statistic.h"
2109467b48Spatrick #include "llvm/Analysis/CallGraph.h"
22097a140dSpatrick #include "llvm/IR/AbstractCallSite.h"
2309467b48Spatrick #include "llvm/IR/Function.h"
2409467b48Spatrick #include "llvm/IR/Intrinsics.h"
2509467b48Spatrick #include "llvm/IR/LLVMContext.h"
2609467b48Spatrick #include "llvm/IR/LegacyPassManagers.h"
2709467b48Spatrick #include "llvm/IR/Module.h"
2809467b48Spatrick #include "llvm/IR/OptBisect.h"
2909467b48Spatrick #include "llvm/IR/PassTimingInfo.h"
3073471bf0Spatrick #include "llvm/IR/PrintPasses.h"
3109467b48Spatrick #include "llvm/Pass.h"
3209467b48Spatrick #include "llvm/Support/CommandLine.h"
3309467b48Spatrick #include "llvm/Support/Debug.h"
3409467b48Spatrick #include "llvm/Support/Timer.h"
3509467b48Spatrick #include "llvm/Support/raw_ostream.h"
3609467b48Spatrick #include <cassert>
3709467b48Spatrick #include <string>
3809467b48Spatrick #include <utility>
3909467b48Spatrick #include <vector>
4009467b48Spatrick 
4109467b48Spatrick using namespace llvm;
4209467b48Spatrick 
4309467b48Spatrick #define DEBUG_TYPE "cgscc-passmgr"
4409467b48Spatrick 
4573471bf0Spatrick namespace llvm {
4673471bf0Spatrick cl::opt<unsigned> MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden,
4773471bf0Spatrick                                       cl::init(4));
4873471bf0Spatrick }
4909467b48Spatrick 
5009467b48Spatrick STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
5109467b48Spatrick 
5209467b48Spatrick //===----------------------------------------------------------------------===//
5309467b48Spatrick // CGPassManager
5409467b48Spatrick //
5509467b48Spatrick /// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
5609467b48Spatrick 
5709467b48Spatrick namespace {
5809467b48Spatrick 
5909467b48Spatrick class CGPassManager : public ModulePass, public PMDataManager {
6009467b48Spatrick public:
6109467b48Spatrick   static char ID;
6209467b48Spatrick 
CGPassManager()63*d415bd75Srobert   explicit CGPassManager() : ModulePass(ID) {}
6409467b48Spatrick 
6509467b48Spatrick   /// Execute all of the passes scheduled for execution.  Keep track of
6609467b48Spatrick   /// whether any of the passes modifies the module, and if so, return true.
6709467b48Spatrick   bool runOnModule(Module &M) override;
6809467b48Spatrick 
6909467b48Spatrick   using ModulePass::doInitialization;
7009467b48Spatrick   using ModulePass::doFinalization;
7109467b48Spatrick 
7209467b48Spatrick   bool doInitialization(CallGraph &CG);
7309467b48Spatrick   bool doFinalization(CallGraph &CG);
7409467b48Spatrick 
7509467b48Spatrick   /// Pass Manager itself does not invalidate any analysis info.
getAnalysisUsage(AnalysisUsage & Info) const7609467b48Spatrick   void getAnalysisUsage(AnalysisUsage &Info) const override {
7709467b48Spatrick     // CGPassManager walks SCC and it needs CallGraph.
7809467b48Spatrick     Info.addRequired<CallGraphWrapperPass>();
7909467b48Spatrick     Info.setPreservesAll();
8009467b48Spatrick   }
8109467b48Spatrick 
getPassName() const8209467b48Spatrick   StringRef getPassName() const override { return "CallGraph Pass Manager"; }
8309467b48Spatrick 
getAsPMDataManager()8409467b48Spatrick   PMDataManager *getAsPMDataManager() override { return this; }
getAsPass()8509467b48Spatrick   Pass *getAsPass() override { return this; }
8609467b48Spatrick 
8709467b48Spatrick   // Print passes managed by this manager
dumpPassStructure(unsigned Offset)8809467b48Spatrick   void dumpPassStructure(unsigned Offset) override {
8909467b48Spatrick     errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
9009467b48Spatrick     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
9109467b48Spatrick       Pass *P = getContainedPass(Index);
9209467b48Spatrick       P->dumpPassStructure(Offset + 1);
9309467b48Spatrick       dumpLastUses(P, Offset+1);
9409467b48Spatrick     }
9509467b48Spatrick   }
9609467b48Spatrick 
getContainedPass(unsigned N)9709467b48Spatrick   Pass *getContainedPass(unsigned N) {
9809467b48Spatrick     assert(N < PassVector.size() && "Pass number out of range!");
9909467b48Spatrick     return static_cast<Pass *>(PassVector[N]);
10009467b48Spatrick   }
10109467b48Spatrick 
getPassManagerType() const10209467b48Spatrick   PassManagerType getPassManagerType() const override {
10309467b48Spatrick     return PMT_CallGraphPassManager;
10409467b48Spatrick   }
10509467b48Spatrick 
10609467b48Spatrick private:
10709467b48Spatrick   bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
10809467b48Spatrick                          bool &DevirtualizedCall);
10909467b48Spatrick 
11009467b48Spatrick   bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
11109467b48Spatrick                     CallGraph &CG, bool &CallGraphUpToDate,
11209467b48Spatrick                     bool &DevirtualizedCall);
11309467b48Spatrick   bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
11409467b48Spatrick                         bool IsCheckingMode);
11509467b48Spatrick };
11609467b48Spatrick 
11709467b48Spatrick } // end anonymous namespace.
11809467b48Spatrick 
11909467b48Spatrick char CGPassManager::ID = 0;
12009467b48Spatrick 
RunPassOnSCC(Pass * P,CallGraphSCC & CurSCC,CallGraph & CG,bool & CallGraphUpToDate,bool & DevirtualizedCall)12109467b48Spatrick bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
12209467b48Spatrick                                  CallGraph &CG, bool &CallGraphUpToDate,
12309467b48Spatrick                                  bool &DevirtualizedCall) {
12409467b48Spatrick   bool Changed = false;
12509467b48Spatrick   PMDataManager *PM = P->getAsPMDataManager();
12609467b48Spatrick   Module &M = CG.getModule();
12709467b48Spatrick 
12809467b48Spatrick   if (!PM) {
12909467b48Spatrick     CallGraphSCCPass *CGSP = (CallGraphSCCPass *)P;
13009467b48Spatrick     if (!CallGraphUpToDate) {
13109467b48Spatrick       DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
13209467b48Spatrick       CallGraphUpToDate = true;
13309467b48Spatrick     }
13409467b48Spatrick 
13509467b48Spatrick     {
13609467b48Spatrick       unsigned InstrCount, SCCCount = 0;
13709467b48Spatrick       StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
13809467b48Spatrick       bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
13909467b48Spatrick       TimeRegion PassTimer(getPassTimer(CGSP));
14009467b48Spatrick       if (EmitICRemark)
14109467b48Spatrick         InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
14209467b48Spatrick       Changed = CGSP->runOnSCC(CurSCC);
14309467b48Spatrick 
14409467b48Spatrick       if (EmitICRemark) {
14509467b48Spatrick         // FIXME: Add getInstructionCount to CallGraphSCC.
14609467b48Spatrick         SCCCount = M.getInstructionCount();
14709467b48Spatrick         // Is there a difference in the number of instructions in the module?
14809467b48Spatrick         if (SCCCount != InstrCount) {
14909467b48Spatrick           // Yep. Emit a remark and update InstrCount.
15009467b48Spatrick           int64_t Delta =
15109467b48Spatrick               static_cast<int64_t>(SCCCount) - static_cast<int64_t>(InstrCount);
15209467b48Spatrick           emitInstrCountChangedRemark(P, M, Delta, InstrCount,
15309467b48Spatrick                                       FunctionToInstrCount);
15409467b48Spatrick           InstrCount = SCCCount;
15509467b48Spatrick         }
15609467b48Spatrick       }
15709467b48Spatrick     }
15809467b48Spatrick 
15909467b48Spatrick     // After the CGSCCPass is done, when assertions are enabled, use
16009467b48Spatrick     // RefreshCallGraph to verify that the callgraph was correctly updated.
16109467b48Spatrick #ifndef NDEBUG
16209467b48Spatrick     if (Changed)
16309467b48Spatrick       RefreshCallGraph(CurSCC, CG, true);
16409467b48Spatrick #endif
16509467b48Spatrick 
16609467b48Spatrick     return Changed;
16709467b48Spatrick   }
16809467b48Spatrick 
16909467b48Spatrick   assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
17009467b48Spatrick          "Invalid CGPassManager member");
17109467b48Spatrick   FPPassManager *FPP = (FPPassManager*)P;
17209467b48Spatrick 
17309467b48Spatrick   // Run pass P on all functions in the current SCC.
17409467b48Spatrick   for (CallGraphNode *CGN : CurSCC) {
17509467b48Spatrick     if (Function *F = CGN->getFunction()) {
17609467b48Spatrick       dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
17709467b48Spatrick       {
17809467b48Spatrick         TimeRegion PassTimer(getPassTimer(FPP));
17909467b48Spatrick         Changed |= FPP->runOnFunction(*F);
18009467b48Spatrick       }
18109467b48Spatrick       F->getContext().yield();
18209467b48Spatrick     }
18309467b48Spatrick   }
18409467b48Spatrick 
18509467b48Spatrick   // The function pass(es) modified the IR, they may have clobbered the
18609467b48Spatrick   // callgraph.
18709467b48Spatrick   if (Changed && CallGraphUpToDate) {
18809467b48Spatrick     LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: " << P->getPassName()
18909467b48Spatrick                       << '\n');
19009467b48Spatrick     CallGraphUpToDate = false;
19109467b48Spatrick   }
19209467b48Spatrick   return Changed;
19309467b48Spatrick }
19409467b48Spatrick 
19509467b48Spatrick /// Scan the functions in the specified CFG and resync the
19609467b48Spatrick /// callgraph with the call sites found in it.  This is used after
19709467b48Spatrick /// FunctionPasses have potentially munged the callgraph, and can be used after
19809467b48Spatrick /// CallGraphSCC passes to verify that they correctly updated the callgraph.
19909467b48Spatrick ///
20009467b48Spatrick /// This function returns true if it devirtualized an existing function call,
20109467b48Spatrick /// meaning it turned an indirect call into a direct call.  This happens when
20209467b48Spatrick /// a function pass like GVN optimizes away stuff feeding the indirect call.
20309467b48Spatrick /// This never happens in checking mode.
RefreshCallGraph(const CallGraphSCC & CurSCC,CallGraph & CG,bool CheckingMode)20409467b48Spatrick bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
20509467b48Spatrick                                      bool CheckingMode) {
20609467b48Spatrick   DenseMap<Value *, CallGraphNode *> Calls;
20709467b48Spatrick 
20809467b48Spatrick   LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
20909467b48Spatrick                     << " nodes:\n";
21009467b48Spatrick              for (CallGraphNode *CGN
21109467b48Spatrick                   : CurSCC) CGN->dump(););
21209467b48Spatrick 
21309467b48Spatrick   bool MadeChange = false;
21409467b48Spatrick   bool DevirtualizedCall = false;
21509467b48Spatrick 
21609467b48Spatrick   // Scan all functions in the SCC.
21709467b48Spatrick   unsigned FunctionNo = 0;
21809467b48Spatrick   for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
21909467b48Spatrick        SCCIdx != E; ++SCCIdx, ++FunctionNo) {
22009467b48Spatrick     CallGraphNode *CGN = *SCCIdx;
22109467b48Spatrick     Function *F = CGN->getFunction();
22209467b48Spatrick     if (!F || F->isDeclaration()) continue;
22309467b48Spatrick 
22409467b48Spatrick     // Walk the function body looking for call sites.  Sync up the call sites in
22509467b48Spatrick     // CGN with those actually in the function.
22609467b48Spatrick 
22709467b48Spatrick     // Keep track of the number of direct and indirect calls that were
22809467b48Spatrick     // invalidated and removed.
22909467b48Spatrick     unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
23009467b48Spatrick 
231097a140dSpatrick     CallGraphNode::iterator CGNEnd = CGN->end();
232097a140dSpatrick 
233097a140dSpatrick     auto RemoveAndCheckForDone = [&](CallGraphNode::iterator I) {
234097a140dSpatrick       // Just remove the edge from the set of callees, keep track of whether
235097a140dSpatrick       // I points to the last element of the vector.
236097a140dSpatrick       bool WasLast = I + 1 == CGNEnd;
237097a140dSpatrick       CGN->removeCallEdge(I);
238097a140dSpatrick 
239097a140dSpatrick       // If I pointed to the last element of the vector, we have to bail out:
240097a140dSpatrick       // iterator checking rejects comparisons of the resultant pointer with
241097a140dSpatrick       // end.
242097a140dSpatrick       if (WasLast)
243097a140dSpatrick         return true;
244097a140dSpatrick 
245097a140dSpatrick       CGNEnd = CGN->end();
246097a140dSpatrick       return false;
247097a140dSpatrick     };
248097a140dSpatrick 
24909467b48Spatrick     // Get the set of call sites currently in the function.
250097a140dSpatrick     for (CallGraphNode::iterator I = CGN->begin(); I != CGNEnd;) {
251097a140dSpatrick       // Delete "reference" call records that do not have call instruction. We
252097a140dSpatrick       // reinsert them as needed later. However, keep them in checking mode.
253097a140dSpatrick       if (!I->first) {
254097a140dSpatrick         if (CheckingMode) {
255097a140dSpatrick           ++I;
256097a140dSpatrick           continue;
257097a140dSpatrick         }
258097a140dSpatrick         if (RemoveAndCheckForDone(I))
259097a140dSpatrick           break;
260097a140dSpatrick         continue;
261097a140dSpatrick       }
262097a140dSpatrick 
26309467b48Spatrick       // If this call site is null, then the function pass deleted the call
26409467b48Spatrick       // entirely and the WeakTrackingVH nulled it out.
265097a140dSpatrick       auto *Call = dyn_cast_or_null<CallBase>(*I->first);
266097a140dSpatrick       if (!Call ||
26709467b48Spatrick           // If we've already seen this call site, then the FunctionPass RAUW'd
26809467b48Spatrick           // one call with another, which resulted in two "uses" in the edge
26909467b48Spatrick           // list of the same call.
270*d415bd75Srobert           Calls.count(Call)) {
27109467b48Spatrick         assert(!CheckingMode &&
27209467b48Spatrick                "CallGraphSCCPass did not update the CallGraph correctly!");
27309467b48Spatrick 
27409467b48Spatrick         // If this was an indirect call site, count it.
27509467b48Spatrick         if (!I->second->getFunction())
27609467b48Spatrick           ++NumIndirectRemoved;
27709467b48Spatrick         else
27809467b48Spatrick           ++NumDirectRemoved;
27909467b48Spatrick 
280097a140dSpatrick         if (RemoveAndCheckForDone(I))
28109467b48Spatrick           break;
28209467b48Spatrick         continue;
28309467b48Spatrick       }
28409467b48Spatrick 
285097a140dSpatrick       assert(!Calls.count(Call) && "Call site occurs in node multiple times");
28609467b48Spatrick 
28709467b48Spatrick       if (Call) {
28809467b48Spatrick         Function *Callee = Call->getCalledFunction();
28909467b48Spatrick         // Ignore intrinsics because they're not really function calls.
29009467b48Spatrick         if (!Callee || !(Callee->isIntrinsic()))
291097a140dSpatrick           Calls.insert(std::make_pair(Call, I->second));
29209467b48Spatrick       }
29309467b48Spatrick       ++I;
29409467b48Spatrick     }
29509467b48Spatrick 
29609467b48Spatrick     // Loop over all of the instructions in the function, getting the callsites.
29709467b48Spatrick     // Keep track of the number of direct/indirect calls added.
29809467b48Spatrick     unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
29909467b48Spatrick 
30009467b48Spatrick     for (BasicBlock &BB : *F)
30109467b48Spatrick       for (Instruction &I : BB) {
30209467b48Spatrick         auto *Call = dyn_cast<CallBase>(&I);
30309467b48Spatrick         if (!Call)
30409467b48Spatrick           continue;
30509467b48Spatrick         Function *Callee = Call->getCalledFunction();
30609467b48Spatrick         if (Callee && Callee->isIntrinsic())
30709467b48Spatrick           continue;
30809467b48Spatrick 
309097a140dSpatrick         // If we are not in checking mode, insert potential callback calls as
310097a140dSpatrick         // references. This is not a requirement but helps to iterate over the
311097a140dSpatrick         // functions in the right order.
312097a140dSpatrick         if (!CheckingMode) {
313097a140dSpatrick           forEachCallbackFunction(*Call, [&](Function *CB) {
314097a140dSpatrick             CGN->addCalledFunction(nullptr, CG.getOrInsertFunction(CB));
315097a140dSpatrick           });
316097a140dSpatrick         }
317097a140dSpatrick 
31809467b48Spatrick         // If this call site already existed in the callgraph, just verify it
31909467b48Spatrick         // matches up to expectations and remove it from Calls.
32009467b48Spatrick         DenseMap<Value *, CallGraphNode *>::iterator ExistingIt =
32109467b48Spatrick             Calls.find(Call);
32209467b48Spatrick         if (ExistingIt != Calls.end()) {
32309467b48Spatrick           CallGraphNode *ExistingNode = ExistingIt->second;
32409467b48Spatrick 
32509467b48Spatrick           // Remove from Calls since we have now seen it.
32609467b48Spatrick           Calls.erase(ExistingIt);
32709467b48Spatrick 
32809467b48Spatrick           // Verify that the callee is right.
32909467b48Spatrick           if (ExistingNode->getFunction() == Call->getCalledFunction())
33009467b48Spatrick             continue;
33109467b48Spatrick 
33209467b48Spatrick           // If we are in checking mode, we are not allowed to actually mutate
33309467b48Spatrick           // the callgraph.  If this is a case where we can infer that the
33409467b48Spatrick           // callgraph is less precise than it could be (e.g. an indirect call
33509467b48Spatrick           // site could be turned direct), don't reject it in checking mode, and
33609467b48Spatrick           // don't tweak it to be more precise.
33709467b48Spatrick           if (CheckingMode && Call->getCalledFunction() &&
33809467b48Spatrick               ExistingNode->getFunction() == nullptr)
33909467b48Spatrick             continue;
34009467b48Spatrick 
34109467b48Spatrick           assert(!CheckingMode &&
34209467b48Spatrick                  "CallGraphSCCPass did not update the CallGraph correctly!");
34309467b48Spatrick 
34409467b48Spatrick           // If not, we either went from a direct call to indirect, indirect to
34509467b48Spatrick           // direct, or direct to different direct.
34609467b48Spatrick           CallGraphNode *CalleeNode;
34709467b48Spatrick           if (Function *Callee = Call->getCalledFunction()) {
34809467b48Spatrick             CalleeNode = CG.getOrInsertFunction(Callee);
34909467b48Spatrick             // Keep track of whether we turned an indirect call into a direct
35009467b48Spatrick             // one.
35109467b48Spatrick             if (!ExistingNode->getFunction()) {
35209467b48Spatrick               DevirtualizedCall = true;
35309467b48Spatrick               LLVM_DEBUG(dbgs() << "  CGSCCPASSMGR: Devirtualized call to '"
35409467b48Spatrick                                 << Callee->getName() << "'\n");
35509467b48Spatrick             }
35609467b48Spatrick           } else {
35709467b48Spatrick             CalleeNode = CG.getCallsExternalNode();
35809467b48Spatrick           }
35909467b48Spatrick 
36009467b48Spatrick           // Update the edge target in CGN.
36109467b48Spatrick           CGN->replaceCallEdge(*Call, *Call, CalleeNode);
36209467b48Spatrick           MadeChange = true;
36309467b48Spatrick           continue;
36409467b48Spatrick         }
36509467b48Spatrick 
36609467b48Spatrick         assert(!CheckingMode &&
36709467b48Spatrick                "CallGraphSCCPass did not update the CallGraph correctly!");
36809467b48Spatrick 
36909467b48Spatrick         // If the call site didn't exist in the CGN yet, add it.
37009467b48Spatrick         CallGraphNode *CalleeNode;
37109467b48Spatrick         if (Function *Callee = Call->getCalledFunction()) {
37209467b48Spatrick           CalleeNode = CG.getOrInsertFunction(Callee);
37309467b48Spatrick           ++NumDirectAdded;
37409467b48Spatrick         } else {
37509467b48Spatrick           CalleeNode = CG.getCallsExternalNode();
37609467b48Spatrick           ++NumIndirectAdded;
37709467b48Spatrick         }
37809467b48Spatrick 
37909467b48Spatrick         CGN->addCalledFunction(Call, CalleeNode);
38009467b48Spatrick         MadeChange = true;
38109467b48Spatrick       }
38209467b48Spatrick 
38309467b48Spatrick     // We scanned the old callgraph node, removing invalidated call sites and
38409467b48Spatrick     // then added back newly found call sites.  One thing that can happen is
38509467b48Spatrick     // that an old indirect call site was deleted and replaced with a new direct
38609467b48Spatrick     // call.  In this case, we have devirtualized a call, and CGSCCPM would like
38709467b48Spatrick     // to iteratively optimize the new code.  Unfortunately, we don't really
38809467b48Spatrick     // have a great way to detect when this happens.  As an approximation, we
38909467b48Spatrick     // just look at whether the number of indirect calls is reduced and the
39009467b48Spatrick     // number of direct calls is increased.  There are tons of ways to fool this
39109467b48Spatrick     // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
39209467b48Spatrick     // direct call) but this is close enough.
39309467b48Spatrick     if (NumIndirectRemoved > NumIndirectAdded &&
39409467b48Spatrick         NumDirectRemoved < NumDirectAdded)
39509467b48Spatrick       DevirtualizedCall = true;
39609467b48Spatrick 
39709467b48Spatrick     // After scanning this function, if we still have entries in callsites, then
39809467b48Spatrick     // they are dangling pointers.  WeakTrackingVH should save us for this, so
39909467b48Spatrick     // abort if
40009467b48Spatrick     // this happens.
40109467b48Spatrick     assert(Calls.empty() && "Dangling pointers found in call sites map");
40209467b48Spatrick 
40309467b48Spatrick     // Periodically do an explicit clear to remove tombstones when processing
40409467b48Spatrick     // large scc's.
40509467b48Spatrick     if ((FunctionNo & 15) == 15)
40609467b48Spatrick       Calls.clear();
40709467b48Spatrick   }
40809467b48Spatrick 
40909467b48Spatrick   LLVM_DEBUG(if (MadeChange) {
41009467b48Spatrick     dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
41109467b48Spatrick     for (CallGraphNode *CGN : CurSCC)
41209467b48Spatrick       CGN->dump();
41309467b48Spatrick     if (DevirtualizedCall)
41409467b48Spatrick       dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
41509467b48Spatrick   } else {
41609467b48Spatrick     dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
41709467b48Spatrick   });
41809467b48Spatrick   (void)MadeChange;
41909467b48Spatrick 
42009467b48Spatrick   return DevirtualizedCall;
42109467b48Spatrick }
42209467b48Spatrick 
42309467b48Spatrick /// Execute the body of the entire pass manager on the specified SCC.
42409467b48Spatrick /// This keeps track of whether a function pass devirtualizes
42509467b48Spatrick /// any calls and returns it in DevirtualizedCall.
RunAllPassesOnSCC(CallGraphSCC & CurSCC,CallGraph & CG,bool & DevirtualizedCall)42609467b48Spatrick bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
42709467b48Spatrick                                       bool &DevirtualizedCall) {
42809467b48Spatrick   bool Changed = false;
42909467b48Spatrick 
43009467b48Spatrick   // Keep track of whether the callgraph is known to be up-to-date or not.
43109467b48Spatrick   // The CGSSC pass manager runs two types of passes:
43209467b48Spatrick   // CallGraphSCC Passes and other random function passes.  Because other
43309467b48Spatrick   // random function passes are not CallGraph aware, they may clobber the
43409467b48Spatrick   // call graph by introducing new calls or deleting other ones.  This flag
43509467b48Spatrick   // is set to false when we run a function pass so that we know to clean up
43609467b48Spatrick   // the callgraph when we need to run a CGSCCPass again.
43709467b48Spatrick   bool CallGraphUpToDate = true;
43809467b48Spatrick 
43909467b48Spatrick   // Run all passes on current SCC.
44009467b48Spatrick   for (unsigned PassNo = 0, e = getNumContainedPasses();
44109467b48Spatrick        PassNo != e; ++PassNo) {
44209467b48Spatrick     Pass *P = getContainedPass(PassNo);
44309467b48Spatrick 
44409467b48Spatrick     // If we're in -debug-pass=Executions mode, construct the SCC node list,
44509467b48Spatrick     // otherwise avoid constructing this string as it is expensive.
44609467b48Spatrick     if (isPassDebuggingExecutionsOrMore()) {
44709467b48Spatrick       std::string Functions;
44809467b48Spatrick   #ifndef NDEBUG
44909467b48Spatrick       raw_string_ostream OS(Functions);
45073471bf0Spatrick       ListSeparator LS;
45173471bf0Spatrick       for (const CallGraphNode *CGN : CurSCC) {
45273471bf0Spatrick         OS << LS;
45373471bf0Spatrick         CGN->print(OS);
45409467b48Spatrick       }
45509467b48Spatrick       OS.flush();
45609467b48Spatrick   #endif
45709467b48Spatrick       dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
45809467b48Spatrick     }
45909467b48Spatrick     dumpRequiredSet(P);
46009467b48Spatrick 
46109467b48Spatrick     initializeAnalysisImpl(P);
46209467b48Spatrick 
46373471bf0Spatrick #ifdef EXPENSIVE_CHECKS
464*d415bd75Srobert     uint64_t RefHash = P->structuralHash(CG.getModule());
46573471bf0Spatrick #endif
46609467b48Spatrick 
46773471bf0Spatrick     // Actually run this pass on the current SCC.
46873471bf0Spatrick     bool LocalChanged =
46973471bf0Spatrick         RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate, DevirtualizedCall);
47073471bf0Spatrick 
47173471bf0Spatrick     Changed |= LocalChanged;
47273471bf0Spatrick 
47373471bf0Spatrick #ifdef EXPENSIVE_CHECKS
474*d415bd75Srobert     if (!LocalChanged && (RefHash != P->structuralHash(CG.getModule()))) {
47573471bf0Spatrick       llvm::errs() << "Pass modifies its input and doesn't report it: "
47673471bf0Spatrick                    << P->getPassName() << "\n";
47773471bf0Spatrick       llvm_unreachable("Pass modifies its input and doesn't report it");
47873471bf0Spatrick     }
47973471bf0Spatrick #endif
48073471bf0Spatrick     if (LocalChanged)
48109467b48Spatrick       dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
48209467b48Spatrick     dumpPreservedSet(P);
48309467b48Spatrick 
48409467b48Spatrick     verifyPreservedAnalysis(P);
48573471bf0Spatrick     if (LocalChanged)
48609467b48Spatrick       removeNotPreservedAnalysis(P);
48709467b48Spatrick     recordAvailableAnalysis(P);
48809467b48Spatrick     removeDeadPasses(P, "", ON_CG_MSG);
48909467b48Spatrick   }
49009467b48Spatrick 
49109467b48Spatrick   // If the callgraph was left out of date (because the last pass run was a
49209467b48Spatrick   // functionpass), refresh it before we move on to the next SCC.
49309467b48Spatrick   if (!CallGraphUpToDate)
49409467b48Spatrick     DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
49509467b48Spatrick   return Changed;
49609467b48Spatrick }
49709467b48Spatrick 
49809467b48Spatrick /// Execute all of the passes scheduled for execution.  Keep track of
49909467b48Spatrick /// whether any of the passes modifies the module, and if so, return true.
runOnModule(Module & M)50009467b48Spatrick bool CGPassManager::runOnModule(Module &M) {
50109467b48Spatrick   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
50209467b48Spatrick   bool Changed = doInitialization(CG);
50309467b48Spatrick 
50409467b48Spatrick   // Walk the callgraph in bottom-up SCC order.
50509467b48Spatrick   scc_iterator<CallGraph*> CGI = scc_begin(&CG);
50609467b48Spatrick 
50709467b48Spatrick   CallGraphSCC CurSCC(CG, &CGI);
50809467b48Spatrick   while (!CGI.isAtEnd()) {
50909467b48Spatrick     // Copy the current SCC and increment past it so that the pass can hack
51009467b48Spatrick     // on the SCC if it wants to without invalidating our iterator.
51109467b48Spatrick     const std::vector<CallGraphNode *> &NodeVec = *CGI;
51209467b48Spatrick     CurSCC.initialize(NodeVec);
51309467b48Spatrick     ++CGI;
51409467b48Spatrick 
51509467b48Spatrick     // At the top level, we run all the passes in this pass manager on the
51609467b48Spatrick     // functions in this SCC.  However, we support iterative compilation in the
51709467b48Spatrick     // case where a function pass devirtualizes a call to a function.  For
51809467b48Spatrick     // example, it is very common for a function pass (often GVN or instcombine)
51909467b48Spatrick     // to eliminate the addressing that feeds into a call.  With that improved
52009467b48Spatrick     // information, we would like the call to be an inline candidate, infer
52109467b48Spatrick     // mod-ref information etc.
52209467b48Spatrick     //
52309467b48Spatrick     // Because of this, we allow iteration up to a specified iteration count.
52409467b48Spatrick     // This only happens in the case of a devirtualized call, so we only burn
52509467b48Spatrick     // compile time in the case that we're making progress.  We also have a hard
52609467b48Spatrick     // iteration count limit in case there is crazy code.
52709467b48Spatrick     unsigned Iteration = 0;
52809467b48Spatrick     bool DevirtualizedCall = false;
52909467b48Spatrick     do {
53009467b48Spatrick       LLVM_DEBUG(if (Iteration) dbgs()
53109467b48Spatrick                  << "  SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration
53209467b48Spatrick                  << '\n');
53309467b48Spatrick       DevirtualizedCall = false;
53409467b48Spatrick       Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
53573471bf0Spatrick     } while (Iteration++ < MaxDevirtIterations && DevirtualizedCall);
53609467b48Spatrick 
53709467b48Spatrick     if (DevirtualizedCall)
53809467b48Spatrick       LLVM_DEBUG(dbgs() << "  CGSCCPASSMGR: Stopped iteration after "
53909467b48Spatrick                         << Iteration
54073471bf0Spatrick                         << " times, due to -max-devirt-iterations\n");
54109467b48Spatrick 
54209467b48Spatrick     MaxSCCIterations.updateMax(Iteration);
54309467b48Spatrick   }
54409467b48Spatrick   Changed |= doFinalization(CG);
54509467b48Spatrick   return Changed;
54609467b48Spatrick }
54709467b48Spatrick 
54809467b48Spatrick /// Initialize CG
doInitialization(CallGraph & CG)54909467b48Spatrick bool CGPassManager::doInitialization(CallGraph &CG) {
55009467b48Spatrick   bool Changed = false;
55109467b48Spatrick   for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
55209467b48Spatrick     if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
55309467b48Spatrick       assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
55409467b48Spatrick              "Invalid CGPassManager member");
55509467b48Spatrick       Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
55609467b48Spatrick     } else {
55709467b48Spatrick       Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
55809467b48Spatrick     }
55909467b48Spatrick   }
56009467b48Spatrick   return Changed;
56109467b48Spatrick }
56209467b48Spatrick 
56309467b48Spatrick /// Finalize CG
doFinalization(CallGraph & CG)56409467b48Spatrick bool CGPassManager::doFinalization(CallGraph &CG) {
56509467b48Spatrick   bool Changed = false;
56609467b48Spatrick   for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
56709467b48Spatrick     if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
56809467b48Spatrick       assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
56909467b48Spatrick              "Invalid CGPassManager member");
57009467b48Spatrick       Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
57109467b48Spatrick     } else {
57209467b48Spatrick       Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
57309467b48Spatrick     }
57409467b48Spatrick   }
57509467b48Spatrick   return Changed;
57609467b48Spatrick }
57709467b48Spatrick 
57809467b48Spatrick //===----------------------------------------------------------------------===//
57909467b48Spatrick // CallGraphSCC Implementation
58009467b48Spatrick //===----------------------------------------------------------------------===//
58109467b48Spatrick 
58209467b48Spatrick /// This informs the SCC and the pass manager that the specified
58309467b48Spatrick /// Old node has been deleted, and New is to be used in its place.
ReplaceNode(CallGraphNode * Old,CallGraphNode * New)58409467b48Spatrick void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
58509467b48Spatrick   assert(Old != New && "Should not replace node with self");
58609467b48Spatrick   for (unsigned i = 0; ; ++i) {
58709467b48Spatrick     assert(i != Nodes.size() && "Node not in SCC");
58809467b48Spatrick     if (Nodes[i] != Old) continue;
589097a140dSpatrick     if (New)
59009467b48Spatrick       Nodes[i] = New;
591097a140dSpatrick     else
592097a140dSpatrick       Nodes.erase(Nodes.begin() + i);
59309467b48Spatrick     break;
59409467b48Spatrick   }
59509467b48Spatrick 
59609467b48Spatrick   // Update the active scc_iterator so that it doesn't contain dangling
59709467b48Spatrick   // pointers to the old CallGraphNode.
59809467b48Spatrick   scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
59909467b48Spatrick   CGI->ReplaceNode(Old, New);
60009467b48Spatrick }
60109467b48Spatrick 
DeleteNode(CallGraphNode * Old)602097a140dSpatrick void CallGraphSCC::DeleteNode(CallGraphNode *Old) {
603097a140dSpatrick   ReplaceNode(Old, /*New=*/nullptr);
604097a140dSpatrick }
605097a140dSpatrick 
60609467b48Spatrick //===----------------------------------------------------------------------===//
60709467b48Spatrick // CallGraphSCCPass Implementation
60809467b48Spatrick //===----------------------------------------------------------------------===//
60909467b48Spatrick 
61009467b48Spatrick /// Assign pass manager to manage this pass.
assignPassManager(PMStack & PMS,PassManagerType PreferredType)61109467b48Spatrick void CallGraphSCCPass::assignPassManager(PMStack &PMS,
61209467b48Spatrick                                          PassManagerType PreferredType) {
61309467b48Spatrick   // Find CGPassManager
61409467b48Spatrick   while (!PMS.empty() &&
61509467b48Spatrick          PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
61609467b48Spatrick     PMS.pop();
61709467b48Spatrick 
61809467b48Spatrick   assert(!PMS.empty() && "Unable to handle Call Graph Pass");
61909467b48Spatrick   CGPassManager *CGP;
62009467b48Spatrick 
62109467b48Spatrick   if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
62209467b48Spatrick     CGP = (CGPassManager*)PMS.top();
62309467b48Spatrick   else {
62409467b48Spatrick     // Create new Call Graph SCC Pass Manager if it does not exist.
62509467b48Spatrick     assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
62609467b48Spatrick     PMDataManager *PMD = PMS.top();
62709467b48Spatrick 
62809467b48Spatrick     // [1] Create new Call Graph Pass Manager
62909467b48Spatrick     CGP = new CGPassManager();
63009467b48Spatrick 
63109467b48Spatrick     // [2] Set up new manager's top level manager
63209467b48Spatrick     PMTopLevelManager *TPM = PMD->getTopLevelManager();
63309467b48Spatrick     TPM->addIndirectPassManager(CGP);
63409467b48Spatrick 
63509467b48Spatrick     // [3] Assign manager to manage this new manager. This may create
63609467b48Spatrick     // and push new managers into PMS
63709467b48Spatrick     Pass *P = CGP;
63809467b48Spatrick     TPM->schedulePass(P);
63909467b48Spatrick 
64009467b48Spatrick     // [4] Push new manager into PMS
64109467b48Spatrick     PMS.push(CGP);
64209467b48Spatrick   }
64309467b48Spatrick 
64409467b48Spatrick   CGP->add(this);
64509467b48Spatrick }
64609467b48Spatrick 
64709467b48Spatrick /// For this class, we declare that we require and preserve the call graph.
64809467b48Spatrick /// If the derived class implements this method, it should
64909467b48Spatrick /// always explicitly call the implementation here.
getAnalysisUsage(AnalysisUsage & AU) const65009467b48Spatrick void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
65109467b48Spatrick   AU.addRequired<CallGraphWrapperPass>();
65209467b48Spatrick   AU.addPreserved<CallGraphWrapperPass>();
65309467b48Spatrick }
65409467b48Spatrick 
65509467b48Spatrick //===----------------------------------------------------------------------===//
65609467b48Spatrick // PrintCallGraphPass Implementation
65709467b48Spatrick //===----------------------------------------------------------------------===//
65809467b48Spatrick 
65909467b48Spatrick namespace {
66009467b48Spatrick 
66109467b48Spatrick   /// PrintCallGraphPass - Print a Module corresponding to a call graph.
66209467b48Spatrick   ///
66309467b48Spatrick   class PrintCallGraphPass : public CallGraphSCCPass {
66409467b48Spatrick     std::string Banner;
66509467b48Spatrick     raw_ostream &OS;       // raw_ostream to print on.
66609467b48Spatrick 
66709467b48Spatrick   public:
66809467b48Spatrick     static char ID;
66909467b48Spatrick 
PrintCallGraphPass(const std::string & B,raw_ostream & OS)67009467b48Spatrick     PrintCallGraphPass(const std::string &B, raw_ostream &OS)
67109467b48Spatrick       : CallGraphSCCPass(ID), Banner(B), OS(OS) {}
67209467b48Spatrick 
getAnalysisUsage(AnalysisUsage & AU) const67309467b48Spatrick     void getAnalysisUsage(AnalysisUsage &AU) const override {
67409467b48Spatrick       AU.setPreservesAll();
67509467b48Spatrick     }
67609467b48Spatrick 
runOnSCC(CallGraphSCC & SCC)67709467b48Spatrick     bool runOnSCC(CallGraphSCC &SCC) override {
67809467b48Spatrick       bool BannerPrinted = false;
67909467b48Spatrick       auto PrintBannerOnce = [&]() {
68009467b48Spatrick         if (BannerPrinted)
68109467b48Spatrick           return;
68209467b48Spatrick         OS << Banner;
68309467b48Spatrick         BannerPrinted = true;
68409467b48Spatrick       };
68509467b48Spatrick 
68609467b48Spatrick       bool NeedModule = llvm::forcePrintModuleIR();
68709467b48Spatrick       if (isFunctionInPrintList("*") && NeedModule) {
68809467b48Spatrick         PrintBannerOnce();
68909467b48Spatrick         OS << "\n";
69009467b48Spatrick         SCC.getCallGraph().getModule().print(OS, nullptr);
69109467b48Spatrick         return false;
69209467b48Spatrick       }
69309467b48Spatrick       bool FoundFunction = false;
69409467b48Spatrick       for (CallGraphNode *CGN : SCC) {
69509467b48Spatrick         if (Function *F = CGN->getFunction()) {
69609467b48Spatrick           if (!F->isDeclaration() && isFunctionInPrintList(F->getName())) {
69709467b48Spatrick             FoundFunction = true;
69809467b48Spatrick             if (!NeedModule) {
69909467b48Spatrick               PrintBannerOnce();
70009467b48Spatrick               F->print(OS);
70109467b48Spatrick             }
70209467b48Spatrick           }
70309467b48Spatrick         } else if (isFunctionInPrintList("*")) {
70409467b48Spatrick           PrintBannerOnce();
70509467b48Spatrick           OS << "\nPrinting <null> Function\n";
70609467b48Spatrick         }
70709467b48Spatrick       }
70809467b48Spatrick       if (NeedModule && FoundFunction) {
70909467b48Spatrick         PrintBannerOnce();
71009467b48Spatrick         OS << "\n";
71109467b48Spatrick         SCC.getCallGraph().getModule().print(OS, nullptr);
71209467b48Spatrick       }
71309467b48Spatrick       return false;
71409467b48Spatrick     }
71509467b48Spatrick 
getPassName() const71609467b48Spatrick     StringRef getPassName() const override { return "Print CallGraph IR"; }
71709467b48Spatrick   };
71809467b48Spatrick 
71909467b48Spatrick } // end anonymous namespace.
72009467b48Spatrick 
72109467b48Spatrick char PrintCallGraphPass::ID = 0;
72209467b48Spatrick 
createPrinterPass(raw_ostream & OS,const std::string & Banner) const72309467b48Spatrick Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &OS,
72409467b48Spatrick                                           const std::string &Banner) const {
72509467b48Spatrick   return new PrintCallGraphPass(Banner, OS);
72609467b48Spatrick }
72709467b48Spatrick 
getDescription(const CallGraphSCC & SCC)72809467b48Spatrick static std::string getDescription(const CallGraphSCC &SCC) {
72909467b48Spatrick   std::string Desc = "SCC (";
73073471bf0Spatrick   ListSeparator LS;
73109467b48Spatrick   for (CallGraphNode *CGN : SCC) {
73273471bf0Spatrick     Desc += LS;
73309467b48Spatrick     Function *F = CGN->getFunction();
73409467b48Spatrick     if (F)
73509467b48Spatrick       Desc += F->getName();
73609467b48Spatrick     else
73709467b48Spatrick       Desc += "<<null function>>";
73809467b48Spatrick   }
73909467b48Spatrick   Desc += ")";
74009467b48Spatrick   return Desc;
74109467b48Spatrick }
74209467b48Spatrick 
skipSCC(CallGraphSCC & SCC) const74309467b48Spatrick bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const {
74409467b48Spatrick   OptPassGate &Gate =
74509467b48Spatrick       SCC.getCallGraph().getModule().getContext().getOptPassGate();
746*d415bd75Srobert   return Gate.isEnabled() &&
747*d415bd75Srobert          !Gate.shouldRunPass(this->getPassName(), getDescription(SCC));
74809467b48Spatrick }
74909467b48Spatrick 
75009467b48Spatrick char DummyCGSCCPass::ID = 0;
75109467b48Spatrick 
75209467b48Spatrick INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,
75309467b48Spatrick                 false)
754