LLVM API Documentation

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