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/AssumptionTracker.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/Target/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<AssumptionTracker>();
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))
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   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
00447   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00448   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
00449   const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
00450   AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
00451 
00452   SmallPtrSet<Function*, 8> SCCFunctions;
00453   DEBUG(dbgs() << "Inliner visiting SCC:");
00454   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00455     Function *F = (*I)->getFunction();
00456     if (F) SCCFunctions.insert(F);
00457     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
00458   }
00459 
00460   // Scan through and identify all call sites ahead of time so that we only
00461   // inline call sites in the original functions, not call sites that result
00462   // from inlining other functions.
00463   SmallVector<std::pair<CallSite, int>, 16> CallSites;
00464   
00465   // When inlining a callee produces new call sites, we want to keep track of
00466   // the fact that they were inlined from the callee.  This allows us to avoid
00467   // infinite inlining in some obscure cases.  To represent this, we use an
00468   // index into the InlineHistory vector.
00469   SmallVector<std::pair<Function*, int>, 8> InlineHistory;
00470 
00471   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00472     Function *F = (*I)->getFunction();
00473     if (!F) continue;
00474     
00475     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00476       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00477         CallSite CS(cast<Value>(I));
00478         // If this isn't a call, or it is a call to an intrinsic, it can
00479         // never be inlined.
00480         if (!CS || isa<IntrinsicInst>(I))
00481           continue;
00482         
00483         // If this is a direct call to an external function, we can never inline
00484         // it.  If it is an indirect call, inlining may resolve it to be a
00485         // direct call, so we keep it.
00486         if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
00487           continue;
00488         
00489         CallSites.push_back(std::make_pair(CS, -1));
00490       }
00491   }
00492 
00493   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
00494 
00495   // If there are no calls in this function, exit early.
00496   if (CallSites.empty())
00497     return false;
00498   
00499   // Now that we have all of the call sites, move the ones to functions in the
00500   // current SCC to the end of the list.
00501   unsigned FirstCallInSCC = CallSites.size();
00502   for (unsigned i = 0; i < FirstCallInSCC; ++i)
00503     if (Function *F = CallSites[i].first.getCalledFunction())
00504       if (SCCFunctions.count(F))
00505         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
00506 
00507   
00508   InlinedArrayAllocasTy InlinedArrayAllocas;
00509   InlineFunctionInfo InlineInfo(&CG, DL, AA, AT);
00510   
00511   // Now that we have all of the call sites, loop over them and inline them if
00512   // it looks profitable to do so.
00513   bool Changed = false;
00514   bool LocalChange;
00515   do {
00516     LocalChange = false;
00517     // Iterate over the outer loop because inlining functions can cause indirect
00518     // calls to become direct calls.
00519     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
00520       CallSite CS = CallSites[CSi].first;
00521       
00522       Function *Caller = CS.getCaller();
00523       Function *Callee = CS.getCalledFunction();
00524 
00525       // If this call site is dead and it is to a readonly function, we should
00526       // just delete the call instead of trying to inline it, regardless of
00527       // size.  This happens because IPSCCP propagates the result out of the
00528       // call and then we're left with the dead call.
00529       if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
00530         DEBUG(dbgs() << "    -> Deleting dead call: "
00531                      << *CS.getInstruction() << "\n");
00532         // Update the call graph by deleting the edge from Callee to Caller.
00533         CG[Caller]->removeCallEdgeFor(CS);
00534         CS.getInstruction()->eraseFromParent();
00535         ++NumCallsDeleted;
00536       } else {
00537         // We can only inline direct calls to non-declarations.
00538         if (!Callee || Callee->isDeclaration()) continue;
00539       
00540         // If this call site was obtained by inlining another function, verify
00541         // that the include path for the function did not include the callee
00542         // itself.  If so, we'd be recursively inlining the same function,
00543         // which would provide the same callsites, which would cause us to
00544         // infinitely inline.
00545         int InlineHistoryID = CallSites[CSi].second;
00546         if (InlineHistoryID != -1 &&
00547             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
00548           continue;
00549         
00550         LLVMContext &CallerCtx = Caller->getContext();
00551 
00552         // Get DebugLoc to report. CS will be invalid after Inliner.
00553         DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
00554 
00555         // If the policy determines that we should inline this function,
00556         // try to do so.
00557         if (!shouldInline(CS)) {
00558           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00559                                        Twine(Callee->getName() +
00560                                              " will not be inlined into " +
00561                                              Caller->getName()));
00562           continue;
00563         }
00564 
00565         // Attempt to inline the function.
00566         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
00567                                   InlineHistoryID, InsertLifetime, DL)) {
00568           emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00569                                        Twine(Callee->getName() +
00570                                              " will not be inlined into " +
00571                                              Caller->getName()));
00572           continue;
00573         }
00574         ++NumInlined;
00575 
00576         // Report the inline decision.
00577         emitOptimizationRemark(
00578             CallerCtx, DEBUG_TYPE, *Caller, DLoc,
00579             Twine(Callee->getName() + " inlined into " + Caller->getName()));
00580 
00581         // If inlining this function gave us any new call sites, throw them
00582         // onto our worklist to process.  They are useful inline candidates.
00583         if (!InlineInfo.InlinedCalls.empty()) {
00584           // Create a new inline history entry for this, so that we remember
00585           // that these new callsites came about due to inlining Callee.
00586           int NewHistoryID = InlineHistory.size();
00587           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
00588 
00589           for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
00590                i != e; ++i) {
00591             Value *Ptr = InlineInfo.InlinedCalls[i];
00592             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
00593           }
00594         }
00595       }
00596       
00597       // If we inlined or deleted the last possible call site to the function,
00598       // delete the function body now.
00599       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
00600           // TODO: Can remove if in SCC now.
00601           !SCCFunctions.count(Callee) &&
00602           
00603           // The function may be apparently dead, but if there are indirect
00604           // callgraph references to the node, we cannot delete it yet, this
00605           // could invalidate the CGSCC iterator.
00606           CG[Callee]->getNumReferences() == 0) {
00607         DEBUG(dbgs() << "    -> Deleting dead function: "
00608               << Callee->getName() << "\n");
00609         CallGraphNode *CalleeNode = CG[Callee];
00610         
00611         // Remove any call graph edges from the callee to its callees.
00612         CalleeNode->removeAllCalledFunctions();
00613         
00614         // Removing the node for callee from the call graph and delete it.
00615         delete CG.removeFunctionFromModule(CalleeNode);
00616         ++NumDeleted;
00617       }
00618 
00619       // Remove this call site from the list.  If possible, use 
00620       // swap/pop_back for efficiency, but do not use it if doing so would
00621       // move a call site to a function in this SCC before the
00622       // 'FirstCallInSCC' barrier.
00623       if (SCC.isSingular()) {
00624         CallSites[CSi] = CallSites.back();
00625         CallSites.pop_back();
00626       } else {
00627         CallSites.erase(CallSites.begin()+CSi);
00628       }
00629       --CSi;
00630 
00631       Changed = true;
00632       LocalChange = true;
00633     }
00634   } while (LocalChange);
00635 
00636   return Changed;
00637 }
00638 
00639 // doFinalization - Remove now-dead linkonce functions at the end of
00640 // processing to avoid breaking the SCC traversal.
00641 bool Inliner::doFinalization(CallGraph &CG) {
00642   return removeDeadFunctions(CG);
00643 }
00644 
00645 /// removeDeadFunctions - Remove dead functions that are not included in
00646 /// DNR (Do Not Remove) list.
00647 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
00648   SmallVector<CallGraphNode*, 16> FunctionsToRemove;
00649 
00650   // Scan for all of the functions, looking for ones that should now be removed
00651   // from the program.  Insert the dead ones in the FunctionsToRemove set.
00652   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
00653     CallGraphNode *CGN = I->second;
00654     Function *F = CGN->getFunction();
00655     if (!F || F->isDeclaration())
00656       continue;
00657 
00658     // Handle the case when this function is called and we only want to care
00659     // about always-inline functions. This is a bit of a hack to share code
00660     // between here and the InlineAlways pass.
00661     if (AlwaysInlineOnly &&
00662         !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00663                                          Attribute::AlwaysInline))
00664       continue;
00665 
00666     // If the only remaining users of the function are dead constants, remove
00667     // them.
00668     F->removeDeadConstantUsers();
00669 
00670     if (!F->isDefTriviallyDead())
00671       continue;
00672     
00673     // Remove any call graph edges from the function to its callees.
00674     CGN->removeAllCalledFunctions();
00675 
00676     // Remove any edges from the external node to the function's call graph
00677     // node.  These edges might have been made irrelegant due to
00678     // optimization of the program.
00679     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
00680 
00681     // Removing the node for callee from the call graph and delete it.
00682     FunctionsToRemove.push_back(CGN);
00683   }
00684   if (FunctionsToRemove.empty())
00685     return false;
00686 
00687   // Now that we know which functions to delete, do so.  We didn't want to do
00688   // this inline, because that would invalidate our CallGraph::iterator
00689   // objects. :(
00690   //
00691   // Note that it doesn't matter that we are iterating over a non-stable order
00692   // here to do this, it doesn't matter which order the functions are deleted
00693   // in.
00694   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
00695   FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
00696                                       FunctionsToRemove.end()),
00697                           FunctionsToRemove.end());
00698   for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
00699                                                   E = FunctionsToRemove.end();
00700        I != E; ++I) {
00701     delete CG.removeFunctionFromModule(*I);
00702     ++NumDeleted;
00703   }
00704   return true;
00705 }