LCOV - code coverage report
Current view: top level - lib/Analysis - CallGraphSCCPass.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 175 180 97.2 %
Date: 2018-07-13 00:08:38 Functions: 28 30 93.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13