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