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