LLVM  mainline
Inliner.cpp
Go to the documentation of this file.
00001 //===- Inliner.cpp - Code common to all inliners --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the mechanics required to implement inlining without
00011 // missing any calls and updating the call graph.  The decisions of which calls
00012 // are profitable to inline are implemented elsewhere.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/IPO/InlinerPass.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/AssumptionCache.h"
00021 #include "llvm/Analysis/BasicAliasAnalysis.h"
00022 #include "llvm/Analysis/CallGraph.h"
00023 #include "llvm/Analysis/InlineCost.h"
00024 #include "llvm/Analysis/TargetLibraryInfo.h"
00025 #include "llvm/IR/CallSite.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/DiagnosticInfo.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/Module.h"
00031 #include "llvm/Support/CommandLine.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/Transforms/Utils/Cloning.h"
00035 #include "llvm/Transforms/Utils/Local.h"
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "inline"
00039 
00040 STATISTIC(NumInlined, "Number of functions inlined");
00041 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
00042 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
00043 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
00044 
00045 // This weirdly named statistic tracks the number of times that, when attempting
00046 // to inline a function A into B, we analyze the callers of B in order to see
00047 // if those would be more profitable and blocked inline steps.
00048 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
00049 
00050 Inliner::Inliner(char &ID) : CallGraphSCCPass(ID), InsertLifetime(true) {}
00051 
00052 Inliner::Inliner(char &ID, bool InsertLifetime)
00053     : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {}
00054 
00055 /// For this class, we declare that we require and preserve the call graph.
00056 /// If the derived class implements this method, it should
00057 /// always explicitly call the implementation here.
00058 void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
00059   AU.addRequired<AssumptionCacheTracker>();
00060   AU.addRequired<TargetLibraryInfoWrapperPass>();
00061   CallGraphSCCPass::getAnalysisUsage(AU);
00062 }
00063 
00064 
00065 typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
00066 InlinedArrayAllocasTy;
00067 
00068 /// If it is possible to inline the specified call site,
00069 /// do so and update the CallGraph for this operation.
00070 ///
00071 /// This function also does some basic book-keeping to update the IR.  The
00072 /// InlinedArrayAllocas map keeps track of any allocas that are already
00073 /// available from other functions inlined into the caller.  If we are able to
00074 /// inline this call site we attempt to reuse already available allocas or add
00075 /// any new allocas to the set if not possible.
00076 static bool InlineCallIfPossible(Pass &P, CallSite CS, InlineFunctionInfo &IFI,
00077                                  InlinedArrayAllocasTy &InlinedArrayAllocas,
00078                                  int InlineHistory, bool InsertLifetime) {
00079   Function *Callee = CS.getCalledFunction();
00080   Function *Caller = CS.getCaller();
00081 
00082   // We need to manually construct BasicAA directly in order to disable
00083   // its use of other function analyses.
00084   BasicAAResult BAR(createLegacyPMBasicAAResult(P, *Callee));
00085 
00086   // Construct our own AA results for this function. We do this manually to
00087   // work around the limitations of the legacy pass manager.
00088   AAResults AAR(createLegacyPMAAResults(P, *Callee, BAR));
00089 
00090   // Try to inline the function.  Get the list of static allocas that were
00091   // inlined.
00092   if (!InlineFunction(CS, IFI, &AAR, InsertLifetime))
00093     return false;
00094 
00095   AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee);
00096 
00097   // Look at all of the allocas that we inlined through this call site.  If we
00098   // have already inlined other allocas through other calls into this function,
00099   // then we know that they have disjoint lifetimes and that we can merge them.
00100   //
00101   // There are many heuristics possible for merging these allocas, and the
00102   // different options have different tradeoffs.  One thing that we *really*
00103   // don't want to hurt is SRoA: once inlining happens, often allocas are no
00104   // longer address taken and so they can be promoted.
00105   //
00106   // Our "solution" for that is to only merge allocas whose outermost type is an
00107   // array type.  These are usually not promoted because someone is using a
00108   // variable index into them.  These are also often the most important ones to
00109   // merge.
00110   //
00111   // A better solution would be to have real memory lifetime markers in the IR
00112   // and not have the inliner do any merging of allocas at all.  This would
00113   // allow the backend to do proper stack slot coloring of all allocas that
00114   // *actually make it to the backend*, which is really what we want.
00115   //
00116   // Because we don't have this information, we do this simple and useful hack.
00117   //
00118   SmallPtrSet<AllocaInst*, 16> UsedAllocas;
00119   
00120   // When processing our SCC, check to see if CS was inlined from some other
00121   // call site.  For example, if we're processing "A" in this code:
00122   //   A() { B() }
00123   //   B() { x = alloca ... C() }
00124   //   C() { y = alloca ... }
00125   // Assume that C was not inlined into B initially, and so we're processing A
00126   // and decide to inline B into A.  Doing this makes an alloca available for
00127   // reuse and makes a callsite (C) available for inlining.  When we process
00128   // the C call site we don't want to do any alloca merging between X and Y
00129   // because their scopes are not disjoint.  We could make this smarter by
00130   // keeping track of the inline history for each alloca in the
00131   // InlinedArrayAllocas but this isn't likely to be a significant win.
00132   if (InlineHistory != -1)  // Only do merging for top-level call sites in SCC.
00133     return true;
00134   
00135   // Loop over all the allocas we have so far and see if they can be merged with
00136   // a previously inlined alloca.  If not, remember that we had it.
00137   for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
00138        AllocaNo != e; ++AllocaNo) {
00139     AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
00140     
00141     // Don't bother trying to merge array allocations (they will usually be
00142     // canonicalized to be an allocation *of* an array), or allocations whose
00143     // type is not itself an array (because we're afraid of pessimizing SRoA).
00144     ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
00145     if (!ATy || AI->isArrayAllocation())
00146       continue;
00147     
00148     // Get the list of all available allocas for this array type.
00149     std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
00150     
00151     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
00152     // that we have to be careful not to reuse the same "available" alloca for
00153     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
00154     // set to keep track of which "available" allocas are being used by this
00155     // function.  Also, AllocasForType can be empty of course!
00156     bool MergedAwayAlloca = false;
00157     for (AllocaInst *AvailableAlloca : AllocasForType) {
00158 
00159       unsigned Align1 = AI->getAlignment(),
00160                Align2 = AvailableAlloca->getAlignment();
00161       
00162       // The available alloca has to be in the right function, not in some other
00163       // function in this SCC.
00164       if (AvailableAlloca->getParent() != AI->getParent())
00165         continue;
00166       
00167       // If the inlined function already uses this alloca then we can't reuse
00168       // it.
00169       if (!UsedAllocas.insert(AvailableAlloca).second)
00170         continue;
00171       
00172       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
00173       // success!
00174       DEBUG(dbgs() << "    ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
00175                    << *AvailableAlloca << '\n');
00176       
00177       // Move affected dbg.declare calls immediately after the new alloca to
00178       // avoid the situation when a dbg.declare preceeds its alloca.
00179       if (auto *L = LocalAsMetadata::getIfExists(AI))
00180         if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
00181           for (User *U : MDV->users())
00182             if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
00183               DDI->moveBefore(AvailableAlloca->getNextNode());
00184 
00185       AI->replaceAllUsesWith(AvailableAlloca);
00186 
00187       if (Align1 != Align2) {
00188         if (!Align1 || !Align2) {
00189           const DataLayout &DL = Caller->getParent()->getDataLayout();
00190           unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType());
00191 
00192           Align1 = Align1 ? Align1 : TypeAlign;
00193           Align2 = Align2 ? Align2 : TypeAlign;
00194         }
00195 
00196         if (Align1 > Align2)
00197           AvailableAlloca->setAlignment(AI->getAlignment());
00198       }
00199 
00200       AI->eraseFromParent();
00201       MergedAwayAlloca = true;
00202       ++NumMergedAllocas;
00203       IFI.StaticAllocas[AllocaNo] = nullptr;
00204       break;
00205     }
00206 
00207     // If we already nuked the alloca, we're done with it.
00208     if (MergedAwayAlloca)
00209       continue;
00210     
00211     // If we were unable to merge away the alloca either because there are no
00212     // allocas of the right type available or because we reused them all
00213     // already, remember that this alloca came from an inlined function and mark
00214     // it used so we don't reuse it for other allocas from this inline
00215     // operation.
00216     AllocasForType.push_back(AI);
00217     UsedAllocas.insert(AI);
00218   }
00219   
00220   return true;
00221 }
00222 
00223 static void emitAnalysis(CallSite CS, const Twine &Msg) {
00224   Function *Caller = CS.getCaller();
00225   LLVMContext &Ctx = Caller->getContext();
00226   DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00227   emitOptimizationRemarkAnalysis(Ctx, DEBUG_TYPE, *Caller, DLoc, Msg);
00228 }
00229 
00230 /// Return true if the inliner should attempt to inline at the given CallSite.
00231 bool Inliner::shouldInline(CallSite CS) {
00232   InlineCost IC = getInlineCost(CS);
00233   
00234   if (IC.isAlways()) {
00235     DEBUG(dbgs() << "    Inlining: cost=always"
00236           << ", Call: " << *CS.getInstruction() << "\n");
00237     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName()) +
00238                          " should always be inlined (cost=always)");
00239     return true;
00240   }
00241   
00242   if (IC.isNever()) {
00243     DEBUG(dbgs() << "    NOT Inlining: cost=never"
00244           << ", Call: " << *CS.getInstruction() << "\n");
00245     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
00246                            " should never be inlined (cost=never)"));
00247     return false;
00248   }
00249   
00250   Function *Caller = CS.getCaller();
00251   if (!IC) {
00252     DEBUG(dbgs() << "    NOT Inlining: cost=" << IC.getCost()
00253           << ", thres=" << (IC.getCostDelta() + IC.getCost())
00254           << ", Call: " << *CS.getInstruction() << "\n");
00255     emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
00256                            " too costly to inline (cost=") +
00257                          Twine(IC.getCost()) + ", threshold=" +
00258                          Twine(IC.getCostDelta() + IC.getCost()) + ")");
00259     return false;
00260   }
00261   
00262   // Try to detect the case where the current inlining candidate caller (call
00263   // it B) is a static or linkonce-ODR function and is an inlining candidate
00264   // elsewhere, and the current candidate callee (call it C) is large enough
00265   // that inlining it into B would make B too big to inline later. In these
00266   // circumstances it may be best not to inline C into B, but to inline B into
00267   // its callers.
00268   //
00269   // This only applies to static and linkonce-ODR functions because those are
00270   // expected to be available for inlining in the translation units where they
00271   // are used. Thus we will always have the opportunity to make local inlining
00272   // decisions. Importantly the linkonce-ODR linkage covers inline functions
00273   // and templates in C++.
00274   //
00275   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
00276   // the internal implementation of the inline cost metrics rather than
00277   // treating them as truly abstract units etc.
00278   if (Caller->hasLocalLinkage() || Caller->hasLinkOnceODRLinkage()) {
00279     int TotalSecondaryCost = 0;
00280     // The candidate cost to be imposed upon the current function.
00281     int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
00282     // This bool tracks what happens if we do NOT inline C into B.
00283     bool callerWillBeRemoved = Caller->hasLocalLinkage();
00284     // This bool tracks what happens if we DO inline C into B.
00285     bool inliningPreventsSomeOuterInline = false;
00286     for (User *U : Caller->users()) {
00287       CallSite CS2(U);
00288 
00289       // If this isn't a call to Caller (it could be some other sort
00290       // of reference) skip it.  Such references will prevent the caller
00291       // from being removed.
00292       if (!CS2 || CS2.getCalledFunction() != Caller) {
00293         callerWillBeRemoved = false;
00294         continue;
00295       }
00296 
00297       InlineCost IC2 = getInlineCost(CS2);
00298       ++NumCallerCallersAnalyzed;
00299       if (!IC2) {
00300         callerWillBeRemoved = false;
00301         continue;
00302       }
00303       if (IC2.isAlways())
00304         continue;
00305 
00306       // See if inlining or original callsite would erase the cost delta of
00307       // this callsite. We subtract off the penalty for the call instruction,
00308       // which we would be deleting.
00309       if (IC2.getCostDelta() <= CandidateCost) {
00310         inliningPreventsSomeOuterInline = true;
00311         TotalSecondaryCost += IC2.getCost();
00312       }
00313     }
00314     // If all outer calls to Caller would get inlined, the cost for the last
00315     // one is set very low by getInlineCost, in anticipation that Caller will
00316     // be removed entirely.  We did not account for this above unless there
00317     // is only one caller of Caller.
00318     if (callerWillBeRemoved && !Caller->use_empty())
00319       TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
00320 
00321     if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
00322       DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<
00323            " Cost = " << IC.getCost() <<
00324            ", outer Cost = " << TotalSecondaryCost << '\n');
00325       emitAnalysis(
00326           CS, Twine("Not inlining. Cost of inlining " +
00327                     CS.getCalledFunction()->getName() +
00328                     " increases the cost of inlining " +
00329                     CS.getCaller()->getName() + " in other contexts"));
00330       return false;
00331     }
00332   }
00333 
00334   DEBUG(dbgs() << "    Inlining: cost=" << IC.getCost()
00335         << ", thres=" << (IC.getCostDelta() + IC.getCost())
00336         << ", Call: " << *CS.getInstruction() << '\n');
00337   emitAnalysis(
00338       CS, CS.getCalledFunction()->getName() + Twine(" can be inlined into ") +
00339               CS.getCaller()->getName() + " with cost=" + Twine(IC.getCost()) +
00340               " (threshold=" + Twine(IC.getCostDelta() + IC.getCost()) + ")");
00341   return true;
00342 }
00343 
00344 /// Return true if the specified inline history ID
00345 /// indicates an inline history that includes the specified function.
00346 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
00347             const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
00348   while (InlineHistoryID != -1) {
00349     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
00350            "Invalid inline history ID");
00351     if (InlineHistory[InlineHistoryID].first == F)
00352       return true;
00353     InlineHistoryID = InlineHistory[InlineHistoryID].second;
00354   }
00355   return false;
00356 }
00357 
00358 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
00359   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00360   ACT = &getAnalysis<AssumptionCacheTracker>();
00361   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00362 
00363   SmallPtrSet<Function*, 8> SCCFunctions;
00364   DEBUG(dbgs() << "Inliner visiting SCC:");
00365   for (CallGraphNode *Node : SCC) {
00366     Function *F = Node->getFunction();
00367     if (F) SCCFunctions.insert(F);
00368     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
00369   }
00370 
00371   // Scan through and identify all call sites ahead of time so that we only
00372   // inline call sites in the original functions, not call sites that result
00373   // from inlining other functions.
00374   SmallVector<std::pair<CallSite, int>, 16> CallSites;
00375   
00376   // When inlining a callee produces new call sites, we want to keep track of
00377   // the fact that they were inlined from the callee.  This allows us to avoid
00378   // infinite inlining in some obscure cases.  To represent this, we use an
00379   // index into the InlineHistory vector.
00380   SmallVector<std::pair<Function*, int>, 8> InlineHistory;
00381 
00382   for (CallGraphNode *Node : SCC) {
00383     Function *F = Node->getFunction();
00384     if (!F) continue;
00385     
00386     for (BasicBlock &BB : *F)
00387       for (Instruction &I : BB) {
00388         CallSite CS(cast<Value>(&I));
00389         // If this isn't a call, or it is a call to an intrinsic, it can
00390         // never be inlined.
00391         if (!CS || isa<IntrinsicInst>(I))
00392           continue;
00393         
00394         // If this is a direct call to an external function, we can never inline
00395         // it.  If it is an indirect call, inlining may resolve it to be a
00396         // direct call, so we keep it.
00397         if (Function *Callee = CS.getCalledFunction())
00398           if (Callee->isDeclaration())
00399             continue;
00400         
00401         CallSites.push_back(std::make_pair(CS, -1));
00402       }
00403   }
00404 
00405   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
00406 
00407   // If there are no calls in this function, exit early.
00408   if (CallSites.empty())
00409     return false;
00410 
00411   // Now that we have all of the call sites, move the ones to functions in the
00412   // current SCC to the end of the list.
00413   unsigned FirstCallInSCC = CallSites.size();
00414   for (unsigned i = 0; i < FirstCallInSCC; ++i)
00415     if (Function *F = CallSites[i].first.getCalledFunction())
00416       if (SCCFunctions.count(F))
00417         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
00418 
00419   
00420   InlinedArrayAllocasTy InlinedArrayAllocas;
00421   InlineFunctionInfo InlineInfo(&CG, ACT);
00422 
00423   // Now that we have all of the call sites, loop over them and inline them if
00424   // it looks profitable to do so.
00425   bool Changed = false;
00426   bool LocalChange;
00427   do {
00428     LocalChange = false;
00429     // Iterate over the outer loop because inlining functions can cause indirect
00430     // calls to become direct calls.
00431     // CallSites may be modified inside so ranged for loop can not be used.
00432     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
00433       CallSite CS = CallSites[CSi].first;
00434       
00435       Function *Caller = CS.getCaller();
00436       Function *Callee = CS.getCalledFunction();
00437 
00438       // If this call site is dead and it is to a readonly function, we should
00439       // just delete the call instead of trying to inline it, regardless of
00440       // size.  This happens because IPSCCP propagates the result out of the
00441       // call and then we're left with the dead call.
00442       if (isInstructionTriviallyDead(CS.getInstruction(), &TLI)) {
00443         DEBUG(dbgs() << "    -> Deleting dead call: "
00444                      << *CS.getInstruction() << "\n");
00445         // Update the call graph by deleting the edge from Callee to Caller.
00446         CG[Caller]->removeCallEdgeFor(CS);
00447         CS.getInstruction()->eraseFromParent();
00448         ++NumCallsDeleted;
00449       } else {
00450         // We can only inline direct calls to non-declarations.
00451         if (!Callee || Callee->isDeclaration()) continue;
00452       
00453         // If this call site was obtained by inlining another function, verify
00454         // that the include path for the function did not include the callee
00455         // itself.  If so, we'd be recursively inlining the same function,
00456         // which would provide the same callsites, which would cause us to
00457         // infinitely inline.
00458         int InlineHistoryID = CallSites[CSi].second;
00459         if (InlineHistoryID != -1 &&
00460             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
00461           continue;
00462         
00463         LLVMContext &CallerCtx = Caller->getContext();
00464 
00465         // Get DebugLoc to report. CS will be invalid after Inliner.
00466         DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00467 
00468         // If the policy determines that we should inline this function,
00469         // try to do so.
00470         if (!shouldInline(CS)) {
00471           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00472                                        Twine(Callee->getName() +
00473                                              " will not be inlined into " +
00474                                              Caller->getName()));
00475           continue;
00476         }
00477 
00478         // Attempt to inline the function.
00479         if (!InlineCallIfPossible(*this, CS, InlineInfo, InlinedArrayAllocas,
00480                                   InlineHistoryID, InsertLifetime)) {
00481           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00482                                        Twine(Callee->getName() +
00483                                              " will not be inlined into " +
00484                                              Caller->getName()));
00485           continue;
00486         }
00487         ++NumInlined;
00488 
00489         // Report the inline decision.
00490         emitOptimizationRemark(
00491             CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00492             Twine(Callee->getName() + " inlined into " + Caller->getName()));
00493 
00494         // If inlining this function gave us any new call sites, throw them
00495         // onto our worklist to process.  They are useful inline candidates.
00496         if (!InlineInfo.InlinedCalls.empty()) {
00497           // Create a new inline history entry for this, so that we remember
00498           // that these new callsites came about due to inlining Callee.
00499           int NewHistoryID = InlineHistory.size();
00500           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
00501 
00502           for (Value *Ptr : InlineInfo.InlinedCalls)
00503             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
00504         }
00505       }
00506       
00507       // If we inlined or deleted the last possible call site to the function,
00508       // delete the function body now.
00509       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
00510           // TODO: Can remove if in SCC now.
00511           !SCCFunctions.count(Callee) &&
00512           
00513           // The function may be apparently dead, but if there are indirect
00514           // callgraph references to the node, we cannot delete it yet, this
00515           // could invalidate the CGSCC iterator.
00516           CG[Callee]->getNumReferences() == 0) {
00517         DEBUG(dbgs() << "    -> Deleting dead function: "
00518               << Callee->getName() << "\n");
00519         CallGraphNode *CalleeNode = CG[Callee];
00520 
00521         // Remove any call graph edges from the callee to its callees.
00522         CalleeNode->removeAllCalledFunctions();
00523         
00524         // Removing the node for callee from the call graph and delete it.
00525         delete CG.removeFunctionFromModule(CalleeNode);
00526         ++NumDeleted;
00527       }
00528 
00529       // Remove this call site from the list.  If possible, use 
00530       // swap/pop_back for efficiency, but do not use it if doing so would
00531       // move a call site to a function in this SCC before the
00532       // 'FirstCallInSCC' barrier.
00533       if (SCC.isSingular()) {
00534         CallSites[CSi] = CallSites.back();
00535         CallSites.pop_back();
00536       } else {
00537         CallSites.erase(CallSites.begin()+CSi);
00538       }
00539       --CSi;
00540 
00541       Changed = true;
00542       LocalChange = true;
00543     }
00544   } while (LocalChange);
00545 
00546   return Changed;
00547 }
00548 
00549 /// Remove now-dead linkonce functions at the end of
00550 /// processing to avoid breaking the SCC traversal.
00551 bool Inliner::doFinalization(CallGraph &CG) {
00552   return removeDeadFunctions(CG);
00553 }
00554 
00555 /// Remove dead functions that are not included in DNR (Do Not Remove) list.
00556 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
00557   SmallVector<CallGraphNode*, 16> FunctionsToRemove;
00558   SmallVector<CallGraphNode *, 16> DeadFunctionsInComdats;
00559   SmallDenseMap<const Comdat *, int, 16> ComdatEntriesAlive;
00560 
00561   auto RemoveCGN = [&](CallGraphNode *CGN) {
00562     // Remove any call graph edges from the function to its callees.
00563     CGN->removeAllCalledFunctions();
00564 
00565     // Remove any edges from the external node to the function's call graph
00566     // node.  These edges might have been made irrelegant due to
00567     // optimization of the program.
00568     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
00569 
00570     // Removing the node for callee from the call graph and delete it.
00571     FunctionsToRemove.push_back(CGN);
00572   };
00573 
00574   // Scan for all of the functions, looking for ones that should now be removed
00575   // from the program.  Insert the dead ones in the FunctionsToRemove set.
00576   for (const auto &I : CG) {
00577     CallGraphNode *CGN = I.second.get();
00578     Function *F = CGN->getFunction();
00579     if (!F || F->isDeclaration())
00580       continue;
00581 
00582     // Handle the case when this function is called and we only want to care
00583     // about always-inline functions. This is a bit of a hack to share code
00584     // between here and the InlineAlways pass.
00585     if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline))
00586       continue;
00587 
00588     // If the only remaining users of the function are dead constants, remove
00589     // them.
00590     F->removeDeadConstantUsers();
00591 
00592     if (!F->isDefTriviallyDead())
00593       continue;
00594 
00595     // It is unsafe to drop a function with discardable linkage from a COMDAT
00596     // without also dropping the other members of the COMDAT.
00597     // The inliner doesn't visit non-function entities which are in COMDAT
00598     // groups so it is unsafe to do so *unless* the linkage is local.
00599     if (!F->hasLocalLinkage()) {
00600       if (const Comdat *C = F->getComdat()) {
00601         --ComdatEntriesAlive[C];
00602         DeadFunctionsInComdats.push_back(CGN);
00603         continue;
00604       }
00605     }
00606 
00607     RemoveCGN(CGN);
00608   }
00609   if (!DeadFunctionsInComdats.empty()) {
00610     // Count up all the entities in COMDAT groups
00611     auto ComdatGroupReferenced = [&](const Comdat *C) {
00612       auto I = ComdatEntriesAlive.find(C);
00613       if (I != ComdatEntriesAlive.end())
00614         ++(I->getSecond());
00615     };
00616     for (const Function &F : CG.getModule())
00617       if (const Comdat *C = F.getComdat())
00618         ComdatGroupReferenced(C);
00619     for (const GlobalVariable &GV : CG.getModule().globals())
00620       if (const Comdat *C = GV.getComdat())
00621         ComdatGroupReferenced(C);
00622     for (const GlobalAlias &GA : CG.getModule().aliases())
00623       if (const Comdat *C = GA.getComdat())
00624         ComdatGroupReferenced(C);
00625     for (CallGraphNode *CGN : DeadFunctionsInComdats) {
00626       Function *F = CGN->getFunction();
00627       const Comdat *C = F->getComdat();
00628       int NumAlive = ComdatEntriesAlive[C];
00629       // We can remove functions in a COMDAT group if the entire group is dead.
00630       assert(NumAlive >= 0);
00631       if (NumAlive > 0)
00632         continue;
00633 
00634       RemoveCGN(CGN);
00635     }
00636   }
00637 
00638   if (FunctionsToRemove.empty())
00639     return false;
00640 
00641   // Now that we know which functions to delete, do so.  We didn't want to do
00642   // this inline, because that would invalidate our CallGraph::iterator
00643   // objects. :(
00644   //
00645   // Note that it doesn't matter that we are iterating over a non-stable order
00646   // here to do this, it doesn't matter which order the functions are deleted
00647   // in.
00648   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
00649   FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
00650                                       FunctionsToRemove.end()),
00651                           FunctionsToRemove.end());
00652   for (CallGraphNode *CGN : FunctionsToRemove) {
00653     delete CG.removeFunctionFromModule(CGN);
00654     ++NumDeleted;
00655   }
00656   return true;
00657 }