LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Inliner.cpp
Go to the documentation of this file.
1 //===- Inliner.cpp - Code common to all inliners --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the mechanics required to implement inlining without
11 // missing any calls and updating the call graph. The decisions of which calls
12 // are profitable to inline are implemented elsewhere.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #define DEBUG_TYPE "inline"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/CallSite.h"
28 #include "llvm/Support/Debug.h"
33 using namespace llvm;
34 
35 STATISTIC(NumInlined, "Number of functions inlined");
36 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
37 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
38 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
39 
40 // This weirdly named statistic tracks the number of times that, when attempting
41 // to inline a function A into B, we analyze the callers of B in order to see
42 // if those would be more profitable and blocked inline steps.
43 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
44 
45 static cl::opt<int>
46 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
47  cl::desc("Control the amount of inlining to perform (default = 225)"));
48 
49 static cl::opt<int>
50 HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
51  cl::desc("Threshold for inlining functions with inline hint"));
52 
53 // Threshold to use when optsize is specified (and there is no -inline-limit).
54 const int OptSizeThreshold = 75;
55 
57  : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
58 
59 Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
60  : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
61  InlineLimit : Threshold),
62  InsertLifetime(InsertLifetime) {}
63 
64 /// getAnalysisUsage - For this class, we declare that we require and preserve
65 /// the call graph. If the derived class implements this method, it should
66 /// always explicitly call the implementation here.
69 }
70 
71 
74 
75 /// \brief If the inlined function had a higher stack protection level than the
76 /// calling function, then bump up the caller's stack protection level.
77 static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
78  // If upgrading the SSP attribute, clear out the old SSP Attributes first.
79  // Having multiple SSP attributes doesn't actually hurt, but it adds useless
80  // clutter to the IR.
81  AttrBuilder B;
84  AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
85  AttributeSet::FunctionIndex,
86  B);
87  AttributeSet CallerAttr = Caller->getAttributes(),
88  CalleeAttr = Callee->getAttributes();
89 
90  if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
92  Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
94  } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
96  !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
98  Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
100  } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
102  !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
104  !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
107 }
108 
109 /// InlineCallIfPossible - If it is possible to inline the specified call site,
110 /// do so and update the CallGraph for this operation.
111 ///
112 /// This function also does some basic book-keeping to update the IR. The
113 /// InlinedArrayAllocas map keeps track of any allocas that are already
114 /// available from other functions inlined into the caller. If we are able to
115 /// inline this call site we attempt to reuse already available allocas or add
116 /// any new allocas to the set if not possible.
118  InlinedArrayAllocasTy &InlinedArrayAllocas,
119  int InlineHistory, bool InsertLifetime,
120  const DataLayout *TD) {
121  Function *Callee = CS.getCalledFunction();
122  Function *Caller = CS.getCaller();
123 
124  // Try to inline the function. Get the list of static allocas that were
125  // inlined.
126  if (!InlineFunction(CS, IFI, InsertLifetime))
127  return false;
128 
129  AdjustCallerSSPLevel(Caller, Callee);
130 
131  // Look at all of the allocas that we inlined through this call site. If we
132  // have already inlined other allocas through other calls into this function,
133  // then we know that they have disjoint lifetimes and that we can merge them.
134  //
135  // There are many heuristics possible for merging these allocas, and the
136  // different options have different tradeoffs. One thing that we *really*
137  // don't want to hurt is SRoA: once inlining happens, often allocas are no
138  // longer address taken and so they can be promoted.
139  //
140  // Our "solution" for that is to only merge allocas whose outermost type is an
141  // array type. These are usually not promoted because someone is using a
142  // variable index into them. These are also often the most important ones to
143  // merge.
144  //
145  // A better solution would be to have real memory lifetime markers in the IR
146  // and not have the inliner do any merging of allocas at all. This would
147  // allow the backend to do proper stack slot coloring of all allocas that
148  // *actually make it to the backend*, which is really what we want.
149  //
150  // Because we don't have this information, we do this simple and useful hack.
151  //
152  SmallPtrSet<AllocaInst*, 16> UsedAllocas;
153 
154  // When processing our SCC, check to see if CS was inlined from some other
155  // call site. For example, if we're processing "A" in this code:
156  // A() { B() }
157  // B() { x = alloca ... C() }
158  // C() { y = alloca ... }
159  // Assume that C was not inlined into B initially, and so we're processing A
160  // and decide to inline B into A. Doing this makes an alloca available for
161  // reuse and makes a callsite (C) available for inlining. When we process
162  // the C call site we don't want to do any alloca merging between X and Y
163  // because their scopes are not disjoint. We could make this smarter by
164  // keeping track of the inline history for each alloca in the
165  // InlinedArrayAllocas but this isn't likely to be a significant win.
166  if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
167  return true;
168 
169  // Loop over all the allocas we have so far and see if they can be merged with
170  // a previously inlined alloca. If not, remember that we had it.
171  for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
172  AllocaNo != e; ++AllocaNo) {
173  AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
174 
175  // Don't bother trying to merge array allocations (they will usually be
176  // canonicalized to be an allocation *of* an array), or allocations whose
177  // type is not itself an array (because we're afraid of pessimizing SRoA).
179  if (ATy == 0 || AI->isArrayAllocation())
180  continue;
181 
182  // Get the list of all available allocas for this array type.
183  std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
184 
185  // Loop over the allocas in AllocasForType to see if we can reuse one. Note
186  // that we have to be careful not to reuse the same "available" alloca for
187  // multiple different allocas that we just inlined, we use the 'UsedAllocas'
188  // set to keep track of which "available" allocas are being used by this
189  // function. Also, AllocasForType can be empty of course!
190  bool MergedAwayAlloca = false;
191  for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
192  AllocaInst *AvailableAlloca = AllocasForType[i];
193 
194  unsigned Align1 = AI->getAlignment(),
195  Align2 = AvailableAlloca->getAlignment();
196  // If we don't have data layout information, and only one alloca is using
197  // the target default, then we can't safely merge them because we can't
198  // pick the greater alignment.
199  if (!TD && (!Align1 || !Align2) && Align1 != Align2)
200  continue;
201 
202  // The available alloca has to be in the right function, not in some other
203  // function in this SCC.
204  if (AvailableAlloca->getParent() != AI->getParent())
205  continue;
206 
207  // If the inlined function already uses this alloca then we can't reuse
208  // it.
209  if (!UsedAllocas.insert(AvailableAlloca))
210  continue;
211 
212  // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
213  // success!
214  DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
215  << *AvailableAlloca << '\n');
216 
217  AI->replaceAllUsesWith(AvailableAlloca);
218 
219  if (Align1 != Align2) {
220  if (!Align1 || !Align2) {
221  assert(TD && "DataLayout required to compare default alignments");
222  unsigned TypeAlign = TD->getABITypeAlignment(AI->getAllocatedType());
223 
224  Align1 = Align1 ? Align1 : TypeAlign;
225  Align2 = Align2 ? Align2 : TypeAlign;
226  }
227 
228  if (Align1 > Align2)
229  AvailableAlloca->setAlignment(AI->getAlignment());
230  }
231 
232  AI->eraseFromParent();
233  MergedAwayAlloca = true;
234  ++NumMergedAllocas;
235  IFI.StaticAllocas[AllocaNo] = 0;
236  break;
237  }
238 
239  // If we already nuked the alloca, we're done with it.
240  if (MergedAwayAlloca)
241  continue;
242 
243  // If we were unable to merge away the alloca either because there are no
244  // allocas of the right type available or because we reused them all
245  // already, remember that this alloca came from an inlined function and mark
246  // it used so we don't reuse it for other allocas from this inline
247  // operation.
248  AllocasForType.push_back(AI);
249  UsedAllocas.insert(AI);
250  }
251 
252  return true;
253 }
254 
256  int thres = InlineThreshold; // -inline-threshold or else selected by
257  // overall opt level
258 
259  // If -inline-threshold is not given, listen to the optsize attribute when it
260  // would decrease the threshold.
261  Function *Caller = CS.getCaller();
262  bool OptSize = Caller && !Caller->isDeclaration() &&
263  Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
265  if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
266  OptSizeThreshold < thres)
267  thres = OptSizeThreshold;
268 
269  // Listen to the inlinehint attribute when it would increase the threshold
270  // and the caller does not need to minimize its size.
271  Function *Callee = CS.getCalledFunction();
272  bool InlineHint = Callee && !Callee->isDeclaration() &&
273  Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
275  if (InlineHint && HintThreshold > thres
276  && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
278  thres = HintThreshold;
279 
280  return thres;
281 }
282 
283 /// shouldInline - Return true if the inliner should attempt to inline
284 /// at the given CallSite.
285 bool Inliner::shouldInline(CallSite CS) {
286  InlineCost IC = getInlineCost(CS);
287 
288  if (IC.isAlways()) {
289  DEBUG(dbgs() << " Inlining: cost=always"
290  << ", Call: " << *CS.getInstruction() << "\n");
291  return true;
292  }
293 
294  if (IC.isNever()) {
295  DEBUG(dbgs() << " NOT Inlining: cost=never"
296  << ", Call: " << *CS.getInstruction() << "\n");
297  return false;
298  }
299 
300  Function *Caller = CS.getCaller();
301  if (!IC) {
302  DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
303  << ", thres=" << (IC.getCostDelta() + IC.getCost())
304  << ", Call: " << *CS.getInstruction() << "\n");
305  return false;
306  }
307 
308  // Try to detect the case where the current inlining candidate caller (call
309  // it B) is a static or linkonce-ODR function and is an inlining candidate
310  // elsewhere, and the current candidate callee (call it C) is large enough
311  // that inlining it into B would make B too big to inline later. In these
312  // circumstances it may be best not to inline C into B, but to inline B into
313  // its callers.
314  //
315  // This only applies to static and linkonce-ODR functions because those are
316  // expected to be available for inlining in the translation units where they
317  // are used. Thus we will always have the opportunity to make local inlining
318  // decisions. Importantly the linkonce-ODR linkage covers inline functions
319  // and templates in C++.
320  //
321  // FIXME: All of this logic should be sunk into getInlineCost. It relies on
322  // the internal implementation of the inline cost metrics rather than
323  // treating them as truly abstract units etc.
324  if (Caller->hasLocalLinkage() ||
326  int TotalSecondaryCost = 0;
327  // The candidate cost to be imposed upon the current function.
328  int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
329  // This bool tracks what happens if we do NOT inline C into B.
330  bool callerWillBeRemoved = Caller->hasLocalLinkage();
331  // This bool tracks what happens if we DO inline C into B.
332  bool inliningPreventsSomeOuterInline = false;
333  for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
334  I != E; ++I) {
335  CallSite CS2(*I);
336 
337  // If this isn't a call to Caller (it could be some other sort
338  // of reference) skip it. Such references will prevent the caller
339  // from being removed.
340  if (!CS2 || CS2.getCalledFunction() != Caller) {
341  callerWillBeRemoved = false;
342  continue;
343  }
344 
345  InlineCost IC2 = getInlineCost(CS2);
346  ++NumCallerCallersAnalyzed;
347  if (!IC2) {
348  callerWillBeRemoved = false;
349  continue;
350  }
351  if (IC2.isAlways())
352  continue;
353 
354  // See if inlining or original callsite would erase the cost delta of
355  // this callsite. We subtract off the penalty for the call instruction,
356  // which we would be deleting.
357  if (IC2.getCostDelta() <= CandidateCost) {
358  inliningPreventsSomeOuterInline = true;
359  TotalSecondaryCost += IC2.getCost();
360  }
361  }
362  // If all outer calls to Caller would get inlined, the cost for the last
363  // one is set very low by getInlineCost, in anticipation that Caller will
364  // be removed entirely. We did not account for this above unless there
365  // is only one caller of Caller.
366  if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
367  TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
368 
369  if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
370  DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
371  " Cost = " << IC.getCost() <<
372  ", outer Cost = " << TotalSecondaryCost << '\n');
373  return false;
374  }
375  }
376 
377  DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
378  << ", thres=" << (IC.getCostDelta() + IC.getCost())
379  << ", Call: " << *CS.getInstruction() << '\n');
380  return true;
381 }
382 
383 /// InlineHistoryIncludes - Return true if the specified inline history ID
384 /// indicates an inline history that includes the specified function.
385 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
386  const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
387  while (InlineHistoryID != -1) {
388  assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
389  "Invalid inline history ID");
390  if (InlineHistory[InlineHistoryID].first == F)
391  return true;
392  InlineHistoryID = InlineHistory[InlineHistoryID].second;
393  }
394  return false;
395 }
396 
398  CallGraph &CG = getAnalysis<CallGraph>();
399  const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
400  const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
401 
402  SmallPtrSet<Function*, 8> SCCFunctions;
403  DEBUG(dbgs() << "Inliner visiting SCC:");
404  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
405  Function *F = (*I)->getFunction();
406  if (F) SCCFunctions.insert(F);
407  DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
408  }
409 
410  // Scan through and identify all call sites ahead of time so that we only
411  // inline call sites in the original functions, not call sites that result
412  // from inlining other functions.
414 
415  // When inlining a callee produces new call sites, we want to keep track of
416  // the fact that they were inlined from the callee. This allows us to avoid
417  // infinite inlining in some obscure cases. To represent this, we use an
418  // index into the InlineHistory vector.
419  SmallVector<std::pair<Function*, int>, 8> InlineHistory;
420 
421  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
422  Function *F = (*I)->getFunction();
423  if (!F) continue;
424 
425  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
426  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
427  CallSite CS(cast<Value>(I));
428  // If this isn't a call, or it is a call to an intrinsic, it can
429  // never be inlined.
430  if (!CS || isa<IntrinsicInst>(I))
431  continue;
432 
433  // If this is a direct call to an external function, we can never inline
434  // it. If it is an indirect call, inlining may resolve it to be a
435  // direct call, so we keep it.
437  continue;
438 
439  CallSites.push_back(std::make_pair(CS, -1));
440  }
441  }
442 
443  DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
444 
445  // If there are no calls in this function, exit early.
446  if (CallSites.empty())
447  return false;
448 
449  // Now that we have all of the call sites, move the ones to functions in the
450  // current SCC to the end of the list.
451  unsigned FirstCallInSCC = CallSites.size();
452  for (unsigned i = 0; i < FirstCallInSCC; ++i)
453  if (Function *F = CallSites[i].first.getCalledFunction())
454  if (SCCFunctions.count(F))
455  std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
456 
457 
458  InlinedArrayAllocasTy InlinedArrayAllocas;
459  InlineFunctionInfo InlineInfo(&CG, TD);
460 
461  // Now that we have all of the call sites, loop over them and inline them if
462  // it looks profitable to do so.
463  bool Changed = false;
464  bool LocalChange;
465  do {
466  LocalChange = false;
467  // Iterate over the outer loop because inlining functions can cause indirect
468  // calls to become direct calls.
469  for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
470  CallSite CS = CallSites[CSi].first;
471 
472  Function *Caller = CS.getCaller();
473  Function *Callee = CS.getCalledFunction();
474 
475  // If this call site is dead and it is to a readonly function, we should
476  // just delete the call instead of trying to inline it, regardless of
477  // size. This happens because IPSCCP propagates the result out of the
478  // call and then we're left with the dead call.
480  DEBUG(dbgs() << " -> Deleting dead call: "
481  << *CS.getInstruction() << "\n");
482  // Update the call graph by deleting the edge from Callee to Caller.
483  CG[Caller]->removeCallEdgeFor(CS);
485  ++NumCallsDeleted;
486  } else {
487  // We can only inline direct calls to non-declarations.
488  if (Callee == 0 || Callee->isDeclaration()) continue;
489 
490  // If this call site was obtained by inlining another function, verify
491  // that the include path for the function did not include the callee
492  // itself. If so, we'd be recursively inlining the same function,
493  // which would provide the same callsites, which would cause us to
494  // infinitely inline.
495  int InlineHistoryID = CallSites[CSi].second;
496  if (InlineHistoryID != -1 &&
497  InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
498  continue;
499 
500 
501  // If the policy determines that we should inline this function,
502  // try to do so.
503  if (!shouldInline(CS))
504  continue;
505 
506  // Attempt to inline the function.
507  if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
508  InlineHistoryID, InsertLifetime, TD))
509  continue;
510  ++NumInlined;
511 
512  // If inlining this function gave us any new call sites, throw them
513  // onto our worklist to process. They are useful inline candidates.
514  if (!InlineInfo.InlinedCalls.empty()) {
515  // Create a new inline history entry for this, so that we remember
516  // that these new callsites came about due to inlining Callee.
517  int NewHistoryID = InlineHistory.size();
518  InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
519 
520  for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
521  i != e; ++i) {
522  Value *Ptr = InlineInfo.InlinedCalls[i];
523  CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
524  }
525  }
526  }
527 
528  // If we inlined or deleted the last possible call site to the function,
529  // delete the function body now.
530  if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
531  // TODO: Can remove if in SCC now.
532  !SCCFunctions.count(Callee) &&
533 
534  // The function may be apparently dead, but if there are indirect
535  // callgraph references to the node, we cannot delete it yet, this
536  // could invalidate the CGSCC iterator.
537  CG[Callee]->getNumReferences() == 0) {
538  DEBUG(dbgs() << " -> Deleting dead function: "
539  << Callee->getName() << "\n");
540  CallGraphNode *CalleeNode = CG[Callee];
541 
542  // Remove any call graph edges from the callee to its callees.
543  CalleeNode->removeAllCalledFunctions();
544 
545  // Removing the node for callee from the call graph and delete it.
546  delete CG.removeFunctionFromModule(CalleeNode);
547  ++NumDeleted;
548  }
549 
550  // Remove this call site from the list. If possible, use
551  // swap/pop_back for efficiency, but do not use it if doing so would
552  // move a call site to a function in this SCC before the
553  // 'FirstCallInSCC' barrier.
554  if (SCC.isSingular()) {
555  CallSites[CSi] = CallSites.back();
556  CallSites.pop_back();
557  } else {
558  CallSites.erase(CallSites.begin()+CSi);
559  }
560  --CSi;
561 
562  Changed = true;
563  LocalChange = true;
564  }
565  } while (LocalChange);
566 
567  return Changed;
568 }
569 
570 // doFinalization - Remove now-dead linkonce functions at the end of
571 // processing to avoid breaking the SCC traversal.
573  return removeDeadFunctions(CG);
574 }
575 
576 /// removeDeadFunctions - Remove dead functions that are not included in
577 /// DNR (Do Not Remove) list.
578 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
579  SmallVector<CallGraphNode*, 16> FunctionsToRemove;
580 
581  // Scan for all of the functions, looking for ones that should now be removed
582  // from the program. Insert the dead ones in the FunctionsToRemove set.
583  for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
584  CallGraphNode *CGN = I->second;
585  Function *F = CGN->getFunction();
586  if (!F || F->isDeclaration())
587  continue;
588 
589  // Handle the case when this function is called and we only want to care
590  // about always-inline functions. This is a bit of a hack to share code
591  // between here and the InlineAlways pass.
592  if (AlwaysInlineOnly &&
593  !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
595  continue;
596 
597  // If the only remaining users of the function are dead constants, remove
598  // them.
600 
601  if (!F->isDefTriviallyDead())
602  continue;
603 
604  // Remove any call graph edges from the function to its callees.
606 
607  // Remove any edges from the external node to the function's call graph
608  // node. These edges might have been made irrelegant due to
609  // optimization of the program.
611 
612  // Removing the node for callee from the call graph and delete it.
613  FunctionsToRemove.push_back(CGN);
614  }
615  if (FunctionsToRemove.empty())
616  return false;
617 
618  // Now that we know which functions to delete, do so. We didn't want to do
619  // this inline, because that would invalidate our CallGraph::iterator
620  // objects. :(
621  //
622  // Note that it doesn't matter that we are iterating over a non-stable order
623  // here to do this, it doesn't matter which order the functions are deleted
624  // in.
625  array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
626  FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
627  FunctionsToRemove.end()),
628  FunctionsToRemove.end());
629  for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
630  E = FunctionsToRemove.end();
631  I != E; ++I) {
632  delete CG.removeFunctionFromModule(*I);
633  ++NumDeleted;
634  }
635  return true;
636 }
bool isDefTriviallyDead() const
Definition: Function.cpp:712
use_iterator use_end()
Definition: Value.h:152
bool isAlways() const
Definition: InlineCost.h:83
LinkageTypes getLinkage() const
Definition: GlobalValue.h:218
virtual bool doFinalization(CallGraph &CG)
Definition: Inliner.cpp:572
unsigned getInlineThreshold() const
Definition: InlinerPass.h:53
LLVMContext & getContext() const
Definition: Function.cpp:167
bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI, bool InsertLifetime=true)
bool isSingular() const
void setAlignment(unsigned Align)
std::vector< CallGraphNode * >::const_iterator iterator
iterator end()
Definition: Function.h:397
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
bool insert(PtrType Ptr)
Definition: SmallPtrSet.h:253
Source said inlining was desirable.
Definition: Attributes.h:75
bool removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly=false)
Definition: Inliner.cpp:578
FunctionMapTy::iterator iterator
Definition: CallGraph.h:107
F(f)
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
Definition: Attributes.cpp:968
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
Definition: Attributes.cpp:818
Represents the cost of inlining a function.
Definition: InlineCost.h:50
virtual void getAnalysisUsage(AnalysisUsage &Info) const
SmallVector< AllocaInst *, 4 > StaticAllocas
Definition: Cloning.h:172
StringRef getName() const
Definition: Value.cpp:167
Function * getFunction() const
Definition: CallGraph.h:212
bool isArrayAllocation() const
FunTy * getCaller() const
Definition: CallSite.h:153
iterator end() const
DenseMap< ArrayType *, std::vector< AllocaInst * > > InlinedArrayAllocasTy
Definition: Inliner.cpp:73
int getCost() const
Get the inline cost estimate. It is an error to call this on an "always" or "never" InlineCost...
Definition: InlineCost.h:89
Function * removeFunctionFromModule(CallGraphNode *CGN)
Definition: CallGraph.cpp:144
Type * getAllocatedType() const
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
void addFnAttr(Attribute::AttrKind N)
Add function attributes to this function.
Definition: Function.h:176
const int OptSizeThreshold
Definition: Inliner.cpp:54
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
const int LastCallToStaticBonus
Definition: InlineCost.h:32
void replaceAllUsesWith(Value *V)
Definition: Value.cpp:303
int getCostDelta() const
Get the cost delta from the threshold for inlining. Only valid if the cost is of the variable kind...
Definition: InlineCost.h:97
void removeAttributes(unsigned i, AttributeSet attr)
removes the attributes from the list of attributes.
Definition: Function.cpp:296
iterator begin()
Definition: Function.h:395
const int CallPenalty
Definition: InlineCost.h:31
Stack protection.
Definition: Attributes.h:102
static cl::opt< int > InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, cl::desc("Control the amount of inlining to perform (default = 225)"))
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:37
#define true
Definition: ConvertUTF.c:65
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:314
void array_pod_sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:289
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Definition: CallGraph.cpp:221
InstrTy * getInstruction() const
Definition: CallSite.h:79
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:266
unsigned getAlignment() const
Definition: Instructions.h:103
SmallVector< WeakVH, 8 > InlinedCalls
Definition: Cloning.h:176
static void AdjustCallerSSPLevel(Function *Caller, Function *Callee)
If the inlined function had a higher stack protection level than the calling function, then bump up the caller's stack protection level.
Definition: Inliner.cpp:77
iterator erase(iterator I)
Definition: SmallVector.h:478
virtual InlineCost getInlineCost(CallSite CS)=0
unsigned getABITypeAlignment(Type *Ty) const
Definition: DataLayout.cpp:582
static cl::opt< int > HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325), cl::desc("Threshold for inlining functions with inline hint"))
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:591
AttributeSet getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:170
iterator begin() const
use_iterator use_begin()
Definition: Value.h:150
void removeAllCalledFunctions()
Definition: CallGraph.h:244
bool isDeclaration() const
Definition: Globals.cpp:66
virtual void getAnalysisUsage(AnalysisUsage &Info) const
Definition: Inliner.cpp:67
#define I(x, y, z)
Definition: MD5.cpp:54
Strong Stack protection.
Definition: Attributes.h:104
iterator end()
Definition: CallGraph.h:115
bool hasLocalLinkage() const
Definition: GlobalValue.h:211
static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI, InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory, bool InsertLifetime, const DataLayout *TD)
Definition: Inliner.cpp:117
static int const Threshold
bool use_empty() const
Definition: Value.h:149
void removeDeadConstantUsers() const
Definition: Constants.cpp:395
LLVM Value Representation.
Definition: Value.h:66
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
virtual bool runOnSCC(CallGraphSCC &SCC)
Definition: Inliner.cpp:397
static bool InlineHistoryIncludes(Function *F, int InlineHistoryID, const SmallVectorImpl< std::pair< Function *, int > > &InlineHistory)
Definition: Inliner.cpp:385
STATISTIC(NumInlined,"Number of functions inlined")
#define DEBUG(X)
Definition: Debug.h:97
Inliner(char &ID)
Definition: Inliner.cpp:56
bool isNever() const
Definition: InlineCost.h:84
CallGraphNode * getExternalCallingNode() const
Definition: CallGraph.h:134
Stack protection required.
Definition: Attributes.h:103
const BasicBlock * getParent() const
Definition: Instruction.h:52
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
iterator begin()
Definition: CallGraph.h:114
FunTy * getCalledFunction() const
Definition: CallSite.h:93
Function must be optimized for size first.
Definition: Attributes.h:77