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

Generated by: LCOV version 1.13