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 #include "llvm/Transforms/IPO/Inliner.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/BasicAliasAnalysis.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Analysis/InlineCost.h"
25 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
26 #include "llvm/Analysis/ProfileSummaryInfo.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/InstIterator.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "inline"
43 
44 STATISTIC(NumInlined, "Number of functions inlined");
45 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
46 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
47 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
48 
49 // This weirdly named statistic tracks the number of times that, when attempting
50 // to inline a function A into B, we analyze the callers of B in order to see
51 // if those would be more profitable and blocked inline steps.
52 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
53 
54 /// Flag to disable manual alloca merging.
55 ///
56 /// Merging of allocas was originally done as a stack-size saving technique
57 /// prior to LLVM's code generator having support for stack coloring based on
58 /// lifetime markers. It is now in the process of being removed. To experiment
59 /// with disabling it and relying fully on lifetime marker based stack
60 /// coloring, you can pass this flag to LLVM.
61 static cl::opt<bool>
62     DisableInlinedAllocaMerging("disable-inlined-alloca-merging",
63                                 cl::init(false), cl::Hidden);
64 
65 namespace {
66 enum class InlinerFunctionImportStatsOpts {
67   No = 0,
68   Basic = 1,
69   Verbose = 2,
70 };
71 
72 cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats(
73     "inliner-function-import-stats",
74     cl::init(InlinerFunctionImportStatsOpts::No),
75     cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic",
76                           "basic statistics"),
77                clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose",
78                           "printing of statistics for each inlined function")),
79     cl::Hidden, cl::desc("Enable inliner stats for imported functions"));
80 } // namespace
81 
82 LegacyInlinerBase::LegacyInlinerBase(char &ID)
83     : CallGraphSCCPass(ID), InsertLifetime(true) {}
84 
85 LegacyInlinerBase::LegacyInlinerBase(char &ID, bool InsertLifetime)
86     : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {}
87 
88 /// For this class, we declare that we require and preserve the call graph.
89 /// If the derived class implements this method, it should
90 /// always explicitly call the implementation here.
91 void LegacyInlinerBase::getAnalysisUsage(AnalysisUsage &AU) const {
92   AU.addRequired<AssumptionCacheTracker>();
93   AU.addRequired<ProfileSummaryInfoWrapperPass>();
94   AU.addRequired<TargetLibraryInfoWrapperPass>();
95   getAAResultsAnalysisUsage(AU);
96   CallGraphSCCPass::getAnalysisUsage(AU);
97 }
98 
99 typedef DenseMap<ArrayType *, std::vector<AllocaInst *>> InlinedArrayAllocasTy;
100 
101 /// Look at all of the allocas that we inlined through this call site.  If we
102 /// have already inlined other allocas through other calls into this function,
103 /// then we know that they have disjoint lifetimes and that we can merge them.
104 ///
105 /// There are many heuristics possible for merging these allocas, and the
106 /// different options have different tradeoffs.  One thing that we *really*
107 /// don't want to hurt is SRoA: once inlining happens, often allocas are no
108 /// longer address taken and so they can be promoted.
109 ///
110 /// Our "solution" for that is to only merge allocas whose outermost type is an
111 /// array type.  These are usually not promoted because someone is using a
112 /// variable index into them.  These are also often the most important ones to
113 /// merge.
114 ///
115 /// A better solution would be to have real memory lifetime markers in the IR
116 /// and not have the inliner do any merging of allocas at all.  This would
117 /// allow the backend to do proper stack slot coloring of all allocas that
118 /// *actually make it to the backend*, which is really what we want.
119 ///
120 /// Because we don't have this information, we do this simple and useful hack.
121 static void mergeInlinedArrayAllocas(
122     Function *Caller, InlineFunctionInfo &IFI,
123     InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory) {
124   SmallPtrSet<AllocaInst *, 16> UsedAllocas;
125 
126   // When processing our SCC, check to see if CS was inlined from some other
127   // call site.  For example, if we're processing "A" in this code:
128   //   A() { B() }
129   //   B() { x = alloca ... C() }
130   //   C() { y = alloca ... }
131   // Assume that C was not inlined into B initially, and so we're processing A
132   // and decide to inline B into A.  Doing this makes an alloca available for
133   // reuse and makes a callsite (C) available for inlining.  When we process
134   // the C call site we don't want to do any alloca merging between X and Y
135   // because their scopes are not disjoint.  We could make this smarter by
136   // keeping track of the inline history for each alloca in the
137   // InlinedArrayAllocas but this isn't likely to be a significant win.
138   if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
139     return;
140 
141   // Loop over all the allocas we have so far and see if they can be merged with
142   // a previously inlined alloca.  If not, remember that we had it.
143   for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size(); AllocaNo != e;
144        ++AllocaNo) {
145     AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
146 
147     // Don't bother trying to merge array allocations (they will usually be
148     // canonicalized to be an allocation *of* an array), or allocations whose
149     // type is not itself an array (because we're afraid of pessimizing SRoA).
150     ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
151     if (!ATy || AI->isArrayAllocation())
152       continue;
153 
154     // Get the list of all available allocas for this array type.
155     std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy];
156 
157     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
158     // that we have to be careful not to reuse the same "available" alloca for
159     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
160     // set to keep track of which "available" allocas are being used by this
161     // function.  Also, AllocasForType can be empty of course!
162     bool MergedAwayAlloca = false;
163     for (AllocaInst *AvailableAlloca : AllocasForType) {
164 
165       unsigned Align1 = AI->getAlignment(),
166                Align2 = AvailableAlloca->getAlignment();
167 
168       // The available alloca has to be in the right function, not in some other
169       // function in this SCC.
170       if (AvailableAlloca->getParent() != AI->getParent())
171         continue;
172 
173       // If the inlined function already uses this alloca then we can't reuse
174       // it.
175       if (!UsedAllocas.insert(AvailableAlloca).second)
176         continue;
177 
178       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
179       // success!
180       DEBUG(dbgs() << "    ***MERGED ALLOCA: " << *AI
181                    << "\n\t\tINTO: " << *AvailableAlloca << '\n');
182 
183       // Move affected dbg.declare calls immediately after the new alloca to
184       // avoid the situation when a dbg.declare precedes its alloca.
185       if (auto *L = LocalAsMetadata::getIfExists(AI))
186         if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
187           for (User *U : MDV->users())
188             if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
189               DDI->moveBefore(AvailableAlloca->getNextNode());
190 
191       AI->replaceAllUsesWith(AvailableAlloca);
192 
193       if (Align1 != Align2) {
194         if (!Align1 || !Align2) {
195           const DataLayout &DL = Caller->getParent()->getDataLayout();
196           unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType());
197 
198           Align1 = Align1 ? Align1 : TypeAlign;
199           Align2 = Align2 ? Align2 : TypeAlign;
200         }
201 
202         if (Align1 > Align2)
203           AvailableAlloca->setAlignment(AI->getAlignment());
204       }
205 
206       AI->eraseFromParent();
207       MergedAwayAlloca = true;
208       ++NumMergedAllocas;
209       IFI.StaticAllocas[AllocaNo] = nullptr;
210       break;
211     }
212 
213     // If we already nuked the alloca, we're done with it.
214     if (MergedAwayAlloca)
215       continue;
216 
217     // If we were unable to merge away the alloca either because there are no
218     // allocas of the right type available or because we reused them all
219     // already, remember that this alloca came from an inlined function and mark
220     // it used so we don't reuse it for other allocas from this inline
221     // operation.
222     AllocasForType.push_back(AI);
223     UsedAllocas.insert(AI);
224   }
225 }
226 
227 /// If it is possible to inline the specified call site,
228 /// do so and update the CallGraph for this operation.
229 ///
230 /// This function also does some basic book-keeping to update the IR.  The
231 /// InlinedArrayAllocas map keeps track of any allocas that are already
232 /// available from other functions inlined into the caller.  If we are able to
233 /// inline this call site we attempt to reuse already available allocas or add
234 /// any new allocas to the set if not possible.
235 static bool InlineCallIfPossible(
236     CallSite CS, InlineFunctionInfo &IFI,
237     InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory,
238     bool InsertLifetime, function_ref<AAResults &(Function &)> &AARGetter,
239     ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
240   Function *Callee = CS.getCalledFunction();
241   Function *Caller = CS.getCaller();
242 
243   AAResults &AAR = AARGetter(*Callee);
244 
245   // Try to inline the function.  Get the list of static allocas that were
246   // inlined.
247   if (!InlineFunction(CS, IFI, &AAR, InsertLifetime))
248     return false;
249 
250   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
251     ImportedFunctionsStats.recordInline(*Caller, *Callee);
252 
253   AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee);
254 
255   if (!DisableInlinedAllocaMerging)
256     mergeInlinedArrayAllocas(Caller, IFI, InlinedArrayAllocas, InlineHistory);
257 
258   return true;
259 }
260 
261 /// Return true if inlining of CS can block the caller from being
262 /// inlined which is proved to be more beneficial. \p IC is the
263 /// estimated inline cost associated with callsite \p CS.
264 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
265 /// caller if \p CS is suppressed for inlining.
266 static bool
267 shouldBeDeferred(Function *Caller, CallSite CS, InlineCost IC,
268                  int &TotalSecondaryCost,
269                  function_ref<InlineCost(CallSite CS)> GetInlineCost) {
270 
271   // For now we only handle local or inline functions.
272   if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
273     return false;
274   // Try to detect the case where the current inlining candidate caller (call
275   // it B) is a static or linkonce-ODR function and is an inlining candidate
276   // elsewhere, and the current candidate callee (call it C) is large enough
277   // that inlining it into B would make B too big to inline later. In these
278   // circumstances it may be best not to inline C into B, but to inline B into
279   // its callers.
280   //
281   // This only applies to static and linkonce-ODR functions because those are
282   // expected to be available for inlining in the translation units where they
283   // are used. Thus we will always have the opportunity to make local inlining
284   // decisions. Importantly the linkonce-ODR linkage covers inline functions
285   // and templates in C++.
286   //
287   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
288   // the internal implementation of the inline cost metrics rather than
289   // treating them as truly abstract units etc.
290   TotalSecondaryCost = 0;
291   // The candidate cost to be imposed upon the current function.
292   int CandidateCost = IC.getCost() - 1;
293   // This bool tracks what happens if we do NOT inline C into B.
294   bool callerWillBeRemoved = Caller->hasLocalLinkage();
295   // This bool tracks what happens if we DO inline C into B.
296   bool inliningPreventsSomeOuterInline = false;
297   for (User *U : Caller->users()) {
298     CallSite CS2(U);
299 
300     // If this isn't a call to Caller (it could be some other sort
301     // of reference) skip it.  Such references will prevent the caller
302     // from being removed.
303     if (!CS2 || CS2.getCalledFunction() != Caller) {
304       callerWillBeRemoved = false;
305       continue;
306     }
307 
308     InlineCost IC2 = GetInlineCost(CS2);
309     ++NumCallerCallersAnalyzed;
310     if (!IC2) {
311       callerWillBeRemoved = false;
312       continue;
313     }
314     if (IC2.isAlways())
315       continue;
316 
317     // See if inlining of the original callsite would erase the cost delta of
318     // this callsite. We subtract off the penalty for the call instruction,
319     // which we would be deleting.
320     if (IC2.getCostDelta() <= CandidateCost) {
321       inliningPreventsSomeOuterInline = true;
322       TotalSecondaryCost += IC2.getCost();
323     }
324   }
325   // If all outer calls to Caller would get inlined, the cost for the last
326   // one is set very low by getInlineCost, in anticipation that Caller will
327   // be removed entirely.  We did not account for this above unless there
328   // is only one caller of Caller.
329   if (callerWillBeRemoved && !Caller->hasOneUse())
330     TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
331 
332   if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost())
333     return true;
334 
335   return false;
336 }
337 
338 /// Return the cost only if the inliner should attempt to inline at the given
339 /// CallSite. If we return the cost, we will emit an optimisation remark later
340 /// using that cost, so we won't do so from this function.
341 static Optional<InlineCost>
342 shouldInline(CallSite CS, function_ref<InlineCost(CallSite CS)> GetInlineCost,
343              OptimizationRemarkEmitter &ORE) {
344   using namespace ore;
345   InlineCost IC = GetInlineCost(CS);
346   Instruction *Call = CS.getInstruction();
347   Function *Callee = CS.getCalledFunction();
348   Function *Caller = CS.getCaller();
349 
350   if (IC.isAlways()) {
351     DEBUG(dbgs() << "    Inlining: cost=always"
352                  << ", Call: " << *CS.getInstruction() << "\n");
353     return IC;
354   }
355 
356   if (IC.isNever()) {
357     DEBUG(dbgs() << "    NOT Inlining: cost=never"
358                  << ", Call: " << *CS.getInstruction() << "\n");
359     ORE.emit([&]() {
360       return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
361              << NV("Callee", Callee) << " not inlined into "
362              << NV("Caller", Caller)
363              << " because it should never be inlined (cost=never)";
364     });
365     return None;
366   }
367 
368   if (!IC) {
369     DEBUG(dbgs() << "    NOT Inlining: cost=" << IC.getCost()
370                  << ", thres=" << IC.getThreshold()
371                  << ", Call: " << *CS.getInstruction() << "\n");
372     ORE.emit([&]() {
373       return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
374              << NV("Callee", Callee) << " not inlined into "
375              << NV("Caller", Caller) << " because too costly to inline (cost="
376              << NV("Cost", IC.getCost())
377              << ", threshold=" << NV("Threshold", IC.getThreshold()) << ")";
378     });
379     return None;
380   }
381 
382   int TotalSecondaryCost = 0;
383   if (shouldBeDeferred(Caller, CS, IC, TotalSecondaryCost, GetInlineCost)) {
384     DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction()
385                  << " Cost = " << IC.getCost()
386                  << ", outer Cost = " << TotalSecondaryCost << '\n');
387     ORE.emit([&]() {
388       return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
389                                       Call)
390              << "Not inlining. Cost of inlining " << NV("Callee", Callee)
391              << " increases the cost of inlining " << NV("Caller", Caller)
392              << " in other contexts";
393     });
394 
395     // IC does not bool() to false, so get an InlineCost that will.
396     // This will not be inspected to make an error message.
397     return None;
398   }
399 
400   DEBUG(dbgs() << "    Inlining: cost=" << IC.getCost()
401                << ", thres=" << IC.getThreshold()
402                << ", Call: " << *CS.getInstruction() << '\n');
403   return IC;
404 }
405 
406 /// Return true if the specified inline history ID
407 /// indicates an inline history that includes the specified function.
408 static bool InlineHistoryIncludes(
409     Function *F, int InlineHistoryID,
410     const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) {
411   while (InlineHistoryID != -1) {
412     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
413            "Invalid inline history ID");
414     if (InlineHistory[InlineHistoryID].first == F)
415       return true;
416     InlineHistoryID = InlineHistory[InlineHistoryID].second;
417   }
418   return false;
419 }
420 
421 bool LegacyInlinerBase::doInitialization(CallGraph &CG) {
422   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
423     ImportedFunctionsStats.setModuleInfo(CG.getModule());
424   return false; // No changes to CallGraph.
425 }
426 
427 bool LegacyInlinerBase::runOnSCC(CallGraphSCC &SCC) {
428   if (skipSCC(SCC))
429     return false;
430   return inlineCalls(SCC);
431 }
432 
433 static bool
434 inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG,
435                 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
436                 ProfileSummaryInfo *PSI, TargetLibraryInfo &TLI,
437                 bool InsertLifetime,
438                 function_ref<InlineCost(CallSite CS)> GetInlineCost,
439                 function_ref<AAResults &(Function &)> AARGetter,
440                 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
441   SmallPtrSet<Function *, 8> SCCFunctions;
442   DEBUG(dbgs() << "Inliner visiting SCC:");
443   for (CallGraphNode *Node : SCC) {
444     Function *F = Node->getFunction();
445     if (F)
446       SCCFunctions.insert(F);
447     DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
448   }
449 
450   // Scan through and identify all call sites ahead of time so that we only
451   // inline call sites in the original functions, not call sites that result
452   // from inlining other functions.
453   SmallVector<std::pair<CallSite, int>, 16> CallSites;
454 
455   // When inlining a callee produces new call sites, we want to keep track of
456   // the fact that they were inlined from the callee.  This allows us to avoid
457   // infinite inlining in some obscure cases.  To represent this, we use an
458   // index into the InlineHistory vector.
459   SmallVector<std::pair<Function *, int>, 8> InlineHistory;
460 
461   for (CallGraphNode *Node : SCC) {
462     Function *F = Node->getFunction();
463     if (!F || F->isDeclaration())
464       continue;
465 
466     OptimizationRemarkEmitter ORE(F);
467     for (BasicBlock &BB : *F)
468       for (Instruction &I : BB) {
469         CallSite CS(cast<Value>(&I));
470         // If this isn't a call, or it is a call to an intrinsic, it can
471         // never be inlined.
472         if (!CS || isa<IntrinsicInst>(I))
473           continue;
474 
475         // If this is a direct call to an external function, we can never inline
476         // it.  If it is an indirect call, inlining may resolve it to be a
477         // direct call, so we keep it.
478         if (Function *Callee = CS.getCalledFunction())
479           if (Callee->isDeclaration()) {
480             using namespace ore;
481             ORE.emit([&]() {
482               return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
483                      << NV("Callee", Callee) << " will not be inlined into "
484                      << NV("Caller", CS.getCaller())
485                      << " because its definition is unavailable"
486                      << setIsVerbose();
487             });
488             continue;
489           }
490 
491         CallSites.push_back(std::make_pair(CS, -1));
492       }
493   }
494 
495   DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
496 
497   // If there are no calls in this function, exit early.
498   if (CallSites.empty())
499     return false;
500 
501   // Now that we have all of the call sites, move the ones to functions in the
502   // current SCC to the end of the list.
503   unsigned FirstCallInSCC = CallSites.size();
504   for (unsigned i = 0; i < FirstCallInSCC; ++i)
505     if (Function *F = CallSites[i].first.getCalledFunction())
506       if (SCCFunctions.count(F))
507         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
508 
509   InlinedArrayAllocasTy InlinedArrayAllocas;
510   InlineFunctionInfo InlineInfo(&CG, &GetAssumptionCache, PSI);
511 
512   // Now that we have all of the call sites, loop over them and inline them if
513   // it looks profitable to do so.
514   bool Changed = false;
515   bool LocalChange;
516   do {
517     LocalChange = false;
518     // Iterate over the outer loop because inlining functions can cause indirect
519     // calls to become direct calls.
520     // CallSites may be modified inside so ranged for loop can not be used.
521     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
522       CallSite CS = CallSites[CSi].first;
523 
524       Function *Caller = CS.getCaller();
525       Function *Callee = CS.getCalledFunction();
526 
527       // We can only inline direct calls to non-declarations.
528       if (!Callee || Callee->isDeclaration())
529         continue;
530 
531       Instruction *Instr = CS.getInstruction();
532 
533       bool IsTriviallyDead = isInstructionTriviallyDead(Instr, &TLI);
534 
535       int InlineHistoryID;
536       if (!IsTriviallyDead) {
537         // If this call site was obtained by inlining another function, verify
538         // that the include path for the function did not include the callee
539         // itself.  If so, we'd be recursively inlining the same function,
540         // which would provide the same callsites, which would cause us to
541         // infinitely inline.
542         InlineHistoryID = CallSites[CSi].second;
543         if (InlineHistoryID != -1 &&
544             InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
545           continue;
546       }
547 
548       // FIXME for new PM: because of the old PM we currently generate ORE and
549       // in turn BFI on demand.  With the new PM, the ORE dependency should
550       // just become a regular analysis dependency.
551       OptimizationRemarkEmitter ORE(Caller);
552 
553       Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE);
554       // If the policy determines that we should inline this function,
555       // delete the call instead.
556       if (!OIC)
557         continue;
558 
559       // If this call site is dead and it is to a readonly function, we should
560       // just delete the call instead of trying to inline it, regardless of
561       // size.  This happens because IPSCCP propagates the result out of the
562       // call and then we're left with the dead call.
563       if (IsTriviallyDead) {
564         DEBUG(dbgs() << "    -> Deleting dead call: " << *Instr << "\n");
565         // Update the call graph by deleting the edge from Callee to Caller.
566         CG[Caller]->removeCallEdgeFor(CS);
567         Instr->eraseFromParent();
568         ++NumCallsDeleted;
569       } else {
570         // Get DebugLoc to report. CS will be invalid after Inliner.
571         DebugLoc DLoc = CS->getDebugLoc();
572         BasicBlock *Block = CS.getParent();
573 
574         // Attempt to inline the function.
575         using namespace ore;
576         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
577                                   InlineHistoryID, InsertLifetime, AARGetter,
578                                   ImportedFunctionsStats)) {
579           ORE.emit([&]() {
580             return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc,
581                                             Block)
582                    << NV("Callee", Callee) << " will not be inlined into "
583                    << NV("Caller", Caller);
584           });
585           continue;
586         }
587         ++NumInlined;
588 
589         ORE.emit([&]() {
590           bool AlwaysInline = OIC->isAlways();
591           StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
592           OptimizationRemark R(DEBUG_TYPE, RemarkName, DLoc, Block);
593           R << NV("Callee", Callee) << " inlined into ";
594           R << NV("Caller", Caller);
595           if (AlwaysInline)
596             R << " with cost=always";
597           else {
598             R << " with cost=" << NV("Cost", OIC->getCost());
599             R << " (threshold=" << NV("Threshold", OIC->getThreshold());
600             R << ")";
601           }
602           return R;
603         });
604 
605         // If inlining this function gave us any new call sites, throw them
606         // onto our worklist to process.  They are useful inline candidates.
607         if (!InlineInfo.InlinedCalls.empty()) {
608           // Create a new inline history entry for this, so that we remember
609           // that these new callsites came about due to inlining Callee.
610           int NewHistoryID = InlineHistory.size();
611           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
612 
613           for (Value *Ptr : InlineInfo.InlinedCalls)
614             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
615         }
616       }
617 
618       // If we inlined or deleted the last possible call site to the function,
619       // delete the function body now.
620       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
621           // TODO: Can remove if in SCC now.
622           !SCCFunctions.count(Callee) &&
623 
624           // The function may be apparently dead, but if there are indirect
625           // callgraph references to the node, we cannot delete it yet, this
626           // could invalidate the CGSCC iterator.
627           CG[Callee]->getNumReferences() == 0) {
628         DEBUG(dbgs() << "    -> Deleting dead function: " << Callee->getName()
629                      << "\n");
630         CallGraphNode *CalleeNode = CG[Callee];
631 
632         // Remove any call graph edges from the callee to its callees.
633         CalleeNode->removeAllCalledFunctions();
634 
635         // Removing the node for callee from the call graph and delete it.
636         delete CG.removeFunctionFromModule(CalleeNode);
637         ++NumDeleted;
638       }
639 
640       // Remove this call site from the list.  If possible, use
641       // swap/pop_back for efficiency, but do not use it if doing so would
642       // move a call site to a function in this SCC before the
643       // 'FirstCallInSCC' barrier.
644       if (SCC.isSingular()) {
645         CallSites[CSi] = CallSites.back();
646         CallSites.pop_back();
647       } else {
648         CallSites.erase(CallSites.begin() + CSi);
649       }
650       --CSi;
651 
652       Changed = true;
653       LocalChange = true;
654     }
655   } while (LocalChange);
656 
657   return Changed;
658 }
659 
660 bool LegacyInlinerBase::inlineCalls(CallGraphSCC &SCC) {
661   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
662   ACT = &getAnalysis<AssumptionCacheTracker>();
663   PSI = getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
664   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
665   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
666     return ACT->getAssumptionCache(F);
667   };
668   return inlineCallsImpl(SCC, CG, GetAssumptionCache, PSI, TLI, InsertLifetime,
669                          [this](CallSite CS) { return getInlineCost(CS); },
670                          LegacyAARGetter(*this), ImportedFunctionsStats);
671 }
672 
673 /// Remove now-dead linkonce functions at the end of
674 /// processing to avoid breaking the SCC traversal.
675 bool LegacyInlinerBase::doFinalization(CallGraph &CG) {
676   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
677     ImportedFunctionsStats.dump(InlinerFunctionImportStats ==
678                                 InlinerFunctionImportStatsOpts::Verbose);
679   return removeDeadFunctions(CG);
680 }
681 
682 /// Remove dead functions that are not included in DNR (Do Not Remove) list.
683 bool LegacyInlinerBase::removeDeadFunctions(CallGraph &CG,
684                                             bool AlwaysInlineOnly) {
685   SmallVector<CallGraphNode *, 16> FunctionsToRemove;
686   SmallVector<Function *, 16> DeadFunctionsInComdats;
687 
688   auto RemoveCGN = [&](CallGraphNode *CGN) {
689     // Remove any call graph edges from the function to its callees.
690     CGN->removeAllCalledFunctions();
691 
692     // Remove any edges from the external node to the function's call graph
693     // node.  These edges might have been made irrelegant due to
694     // optimization of the program.
695     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
696 
697     // Removing the node for callee from the call graph and delete it.
698     FunctionsToRemove.push_back(CGN);
699   };
700 
701   // Scan for all of the functions, looking for ones that should now be removed
702   // from the program.  Insert the dead ones in the FunctionsToRemove set.
703   for (const auto &I : CG) {
704     CallGraphNode *CGN = I.second.get();
705     Function *F = CGN->getFunction();
706     if (!F || F->isDeclaration())
707       continue;
708 
709     // Handle the case when this function is called and we only want to care
710     // about always-inline functions. This is a bit of a hack to share code
711     // between here and the InlineAlways pass.
712     if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline))
713       continue;
714 
715     // If the only remaining users of the function are dead constants, remove
716     // them.
717     F->removeDeadConstantUsers();
718 
719     if (!F->isDefTriviallyDead())
720       continue;
721 
722     // It is unsafe to drop a function with discardable linkage from a COMDAT
723     // without also dropping the other members of the COMDAT.
724     // The inliner doesn't visit non-function entities which are in COMDAT
725     // groups so it is unsafe to do so *unless* the linkage is local.
726     if (!F->hasLocalLinkage()) {
727       if (F->hasComdat()) {
728         DeadFunctionsInComdats.push_back(F);
729         continue;
730       }
731     }
732 
733     RemoveCGN(CGN);
734   }
735   if (!DeadFunctionsInComdats.empty()) {
736     // Filter out the functions whose comdats remain alive.
737     filterDeadComdatFunctions(CG.getModule(), DeadFunctionsInComdats);
738     // Remove the rest.
739     for (Function *F : DeadFunctionsInComdats)
740       RemoveCGN(CG[F]);
741   }
742 
743   if (FunctionsToRemove.empty())
744     return false;
745 
746   // Now that we know which functions to delete, do so.  We didn't want to do
747   // this inline, because that would invalidate our CallGraph::iterator
748   // objects. :(
749   //
750   // Note that it doesn't matter that we are iterating over a non-stable order
751   // here to do this, it doesn't matter which order the functions are deleted
752   // in.
753   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
754   FunctionsToRemove.erase(
755       std::unique(FunctionsToRemove.begin(), FunctionsToRemove.end()),
756       FunctionsToRemove.end());
757   for (CallGraphNode *CGN : FunctionsToRemove) {
758     delete CG.removeFunctionFromModule(CGN);
759     ++NumDeleted;
760   }
761   return true;
762 }
763 
764 PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC,
765                                    CGSCCAnalysisManager &AM, LazyCallGraph &CG,
766                                    CGSCCUpdateResult &UR) {
767   const ModuleAnalysisManager &MAM =
768       AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG).getManager();
769   bool Changed = false;
770 
771   assert(InitialC.size() > 0 && "Cannot handle an empty SCC!");
772   Module &M = *InitialC.begin()->getFunction().getParent();
773   ProfileSummaryInfo *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(M);
774 
775   // We use a single common worklist for calls across the entire SCC. We
776   // process these in-order and append new calls introduced during inlining to
777   // the end.
778   //
779   // Note that this particular order of processing is actually critical to
780   // avoid very bad behaviors. Consider *highly connected* call graphs where
781   // each function contains a small amonut of code and a couple of calls to
782   // other functions. Because the LLVM inliner is fundamentally a bottom-up
783   // inliner, it can handle gracefully the fact that these all appear to be
784   // reasonable inlining candidates as it will flatten things until they become
785   // too big to inline, and then move on and flatten another batch.
786   //
787   // However, when processing call edges *within* an SCC we cannot rely on this
788   // bottom-up behavior. As a consequence, with heavily connected *SCCs* of
789   // functions we can end up incrementally inlining N calls into each of
790   // N functions because each incremental inlining decision looks good and we
791   // don't have a topological ordering to prevent explosions.
792   //
793   // To compensate for this, we don't process transitive edges made immediate
794   // by inlining until we've done one pass of inlining across the entire SCC.
795   // Large, highly connected SCCs still lead to some amount of code bloat in
796   // this model, but it is uniformly spread across all the functions in the SCC
797   // and eventually they all become too large to inline, rather than
798   // incrementally maknig a single function grow in a super linear fashion.
799   SmallVector<std::pair<CallSite, int>, 16> Calls;
800 
801   // Populate the initial list of calls in this SCC.
802   for (auto &N : InitialC) {
803     // We want to generally process call sites top-down in order for
804     // simplifications stemming from replacing the call with the returned value
805     // after inlining to be visible to subsequent inlining decisions.
806     // FIXME: Using instructions sequence is a really bad way to do this.
807     // Instead we should do an actual RPO walk of the function body.
808     for (Instruction &I : instructions(N.getFunction()))
809       if (auto CS = CallSite(&I))
810         if (Function *Callee = CS.getCalledFunction())
811           if (!Callee->isDeclaration())
812             Calls.push_back({CS, -1});
813   }
814   if (Calls.empty())
815     return PreservedAnalyses::all();
816 
817   // Capture updatable variables for the current SCC and RefSCC.
818   auto *C = &InitialC;
819   auto *RC = &C->getOuterRefSCC();
820 
821   // When inlining a callee produces new call sites, we want to keep track of
822   // the fact that they were inlined from the callee.  This allows us to avoid
823   // infinite inlining in some obscure cases.  To represent this, we use an
824   // index into the InlineHistory vector.
825   SmallVector<std::pair<Function *, int>, 16> InlineHistory;
826 
827   // Track a set vector of inlined callees so that we can augment the caller
828   // with all of their edges in the call graph before pruning out the ones that
829   // got simplified away.
830   SmallSetVector<Function *, 4> InlinedCallees;
831 
832   // Track the dead functions to delete once finished with inlining calls. We
833   // defer deleting these to make it easier to handle the call graph updates.
834   SmallVector<Function *, 4> DeadFunctions;
835 
836   // Loop forward over all of the calls. Note that we cannot cache the size as
837   // inlining can introduce new calls that need to be processed.
838   for (int i = 0; i < (int)Calls.size(); ++i) {
839     // We expect the calls to typically be batched with sequences of calls that
840     // have the same caller, so we first set up some shared infrastructure for
841     // this caller. We also do any pruning we can at this layer on the caller
842     // alone.
843     Function &F = *Calls[i].first.getCaller();
844     LazyCallGraph::Node &N = *CG.lookup(F);
845     if (CG.lookupSCC(N) != C)
846       continue;
847     if (F.hasFnAttribute(Attribute::OptimizeNone))
848       continue;
849 
850     DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n");
851 
852     // Get a FunctionAnalysisManager via a proxy for this particular node. We
853     // do this each time we visit a node as the SCC may have changed and as
854     // we're going to mutate this particular function we want to make sure the
855     // proxy is in place to forward any invalidation events. We can use the
856     // manager we get here for looking up results for functions other than this
857     // node however because those functions aren't going to be mutated by this
858     // pass.
859     FunctionAnalysisManager &FAM =
860         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG)
861             .getManager();
862 
863     // Get the remarks emission analysis for the caller.
864     auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
865 
866     std::function<AssumptionCache &(Function &)> GetAssumptionCache =
867         [&](Function &F) -> AssumptionCache & {
868       return FAM.getResult<AssumptionAnalysis>(F);
869     };
870     auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
871       return FAM.getResult<BlockFrequencyAnalysis>(F);
872     };
873 
874     auto GetInlineCost = [&](CallSite CS) {
875       Function &Callee = *CS.getCalledFunction();
876       auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
877       return getInlineCost(CS, Params, CalleeTTI, GetAssumptionCache, {GetBFI},
878                            PSI, &ORE);
879     };
880 
881     // Now process as many calls as we have within this caller in the sequnece.
882     // We bail out as soon as the caller has to change so we can update the
883     // call graph and prepare the context of that new caller.
884     bool DidInline = false;
885     for (; i < (int)Calls.size() && Calls[i].first.getCaller() == &F; ++i) {
886       int InlineHistoryID;
887       CallSite CS;
888       std::tie(CS, InlineHistoryID) = Calls[i];
889       Function &Callee = *CS.getCalledFunction();
890 
891       if (InlineHistoryID != -1 &&
892           InlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory))
893         continue;
894 
895       // Check if this inlining may repeat breaking an SCC apart that has
896       // already been split once before. In that case, inlining here may
897       // trigger infinite inlining, much like is prevented within the inliner
898       // itself by the InlineHistory above, but spread across CGSCC iterations
899       // and thus hidden from the full inline history.
900       if (CG.lookupSCC(*CG.lookup(Callee)) == C &&
901           UR.InlinedInternalEdges.count({&N, C})) {
902         DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node "
903                         "previously split out of this SCC by inlining: "
904                      << F.getName() << " -> " << Callee.getName() << "\n");
905         continue;
906       }
907 
908       Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE);
909       // Check whether we want to inline this callsite.
910       if (!OIC)
911         continue;
912 
913       // Setup the data structure used to plumb customization into the
914       // `InlineFunction` routine.
915       InlineFunctionInfo IFI(
916           /*cg=*/nullptr, &GetAssumptionCache, PSI,
917           &FAM.getResult<BlockFrequencyAnalysis>(*(CS.getCaller())),
918           &FAM.getResult<BlockFrequencyAnalysis>(Callee));
919 
920       // Get DebugLoc to report. CS will be invalid after Inliner.
921       DebugLoc DLoc = CS->getDebugLoc();
922       BasicBlock *Block = CS.getParent();
923 
924       using namespace ore;
925       if (!InlineFunction(CS, IFI)) {
926         ORE.emit([&]() {
927           return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
928                  << NV("Callee", &Callee) << " will not be inlined into "
929                  << NV("Caller", &F);
930         });
931         continue;
932       }
933       DidInline = true;
934       InlinedCallees.insert(&Callee);
935 
936       ORE.emit([&]() {
937         bool AlwaysInline = OIC->isAlways();
938         StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
939         OptimizationRemark R(DEBUG_TYPE, RemarkName, DLoc, Block);
940         R << NV("Callee", &Callee) << " inlined into ";
941         R << NV("Caller", &F);
942         if (AlwaysInline)
943           R << " with cost=always";
944         else {
945           R << " with cost=" << NV("Cost", OIC->getCost());
946           R << " (threshold=" << NV("Threshold", OIC->getThreshold());
947           R << ")";
948         }
949         return R;
950       });
951 
952       // Add any new callsites to defined functions to the worklist.
953       if (!IFI.InlinedCallSites.empty()) {
954         int NewHistoryID = InlineHistory.size();
955         InlineHistory.push_back({&Callee, InlineHistoryID});
956         for (CallSite &CS : reverse(IFI.InlinedCallSites))
957           if (Function *NewCallee = CS.getCalledFunction())
958             if (!NewCallee->isDeclaration())
959               Calls.push_back({CS, NewHistoryID});
960       }
961 
962       // Merge the attributes based on the inlining.
963       AttributeFuncs::mergeAttributesForInlining(F, Callee);
964 
965       // For local functions, check whether this makes the callee trivially
966       // dead. In that case, we can drop the body of the function eagerly
967       // which may reduce the number of callers of other functions to one,
968       // changing inline cost thresholds.
969       if (Callee.hasLocalLinkage()) {
970         // To check this we also need to nuke any dead constant uses (perhaps
971         // made dead by this operation on other functions).
972         Callee.removeDeadConstantUsers();
973         if (Callee.use_empty() && !CG.isLibFunction(Callee)) {
974           Calls.erase(
975               std::remove_if(Calls.begin() + i + 1, Calls.end(),
976                              [&Callee](const std::pair<CallSite, int> &Call) {
977                                return Call.first.getCaller() == &Callee;
978                              }),
979               Calls.end());
980           // Clear the body and queue the function itself for deletion when we
981           // finish inlining and call graph updates.
982           // Note that after this point, it is an error to do anything other
983           // than use the callee's address or delete it.
984           Callee.dropAllReferences();
985           assert(find(DeadFunctions, &Callee) == DeadFunctions.end() &&
986                  "Cannot put cause a function to become dead twice!");
987           DeadFunctions.push_back(&Callee);
988         }
989       }
990     }
991 
992     // Back the call index up by one to put us in a good position to go around
993     // the outer loop.
994     --i;
995 
996     if (!DidInline)
997       continue;
998     Changed = true;
999 
1000     // Add all the inlined callees' edges as ref edges to the caller. These are
1001     // by definition trivial edges as we always have *some* transitive ref edge
1002     // chain. While in some cases these edges are direct calls inside the
1003     // callee, they have to be modeled in the inliner as reference edges as
1004     // there may be a reference edge anywhere along the chain from the current
1005     // caller to the callee that causes the whole thing to appear like
1006     // a (transitive) reference edge that will require promotion to a call edge
1007     // below.
1008     for (Function *InlinedCallee : InlinedCallees) {
1009       LazyCallGraph::Node &CalleeN = *CG.lookup(*InlinedCallee);
1010       for (LazyCallGraph::Edge &E : *CalleeN)
1011         RC->insertTrivialRefEdge(N, E.getNode());
1012     }
1013 
1014     // At this point, since we have made changes we have at least removed
1015     // a call instruction. However, in the process we do some incremental
1016     // simplification of the surrounding code. This simplification can
1017     // essentially do all of the same things as a function pass and we can
1018     // re-use the exact same logic for updating the call graph to reflect the
1019     // change.
1020     LazyCallGraph::SCC *OldC = C;
1021     C = &updateCGAndAnalysisManagerForFunctionPass(CG, *C, N, AM, UR);
1022     DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n");
1023     RC = &C->getOuterRefSCC();
1024 
1025     // If this causes an SCC to split apart into multiple smaller SCCs, there
1026     // is a subtle risk we need to prepare for. Other transformations may
1027     // expose an "infinite inlining" opportunity later, and because of the SCC
1028     // mutation, we will revisit this function and potentially re-inline. If we
1029     // do, and that re-inlining also has the potentially to mutate the SCC
1030     // structure, the infinite inlining problem can manifest through infinite
1031     // SCC splits and merges. To avoid this, we capture the originating caller
1032     // node and the SCC containing the call edge. This is a slight over
1033     // approximation of the possible inlining decisions that must be avoided,
1034     // but is relatively efficient to store.
1035     // FIXME: This seems like a very heavyweight way of retaining the inline
1036     // history, we should look for a more efficient way of tracking it.
1037     if (C != OldC && llvm::any_of(InlinedCallees, [&](Function *Callee) {
1038           return CG.lookupSCC(*CG.lookup(*Callee)) == OldC;
1039         })) {
1040       DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, "
1041                       "retaining this to avoid infinite inlining.\n");
1042       UR.InlinedInternalEdges.insert({&N, OldC});
1043     }
1044     InlinedCallees.clear();
1045   }
1046 
1047   // Now that we've finished inlining all of the calls across this SCC, delete
1048   // all of the trivially dead functions, updating the call graph and the CGSCC
1049   // pass manager in the process.
1050   //
1051   // Note that this walks a pointer set which has non-deterministic order but
1052   // that is OK as all we do is delete things and add pointers to unordered
1053   // sets.
1054   for (Function *DeadF : DeadFunctions) {
1055     // Get the necessary information out of the call graph and nuke the
1056     // function there. Also, cclear out any cached analyses.
1057     auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));
1058     FunctionAnalysisManager &FAM =
1059         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(DeadC, CG)
1060             .getManager();
1061     FAM.clear(*DeadF, DeadF->getName());
1062     AM.clear(DeadC, DeadC.getName());
1063     auto &DeadRC = DeadC.getOuterRefSCC();
1064     CG.removeDeadFunction(*DeadF);
1065 
1066     // Mark the relevant parts of the call graph as invalid so we don't visit
1067     // them.
1068     UR.InvalidatedSCCs.insert(&DeadC);
1069     UR.InvalidatedRefSCCs.insert(&DeadRC);
1070 
1071     // And delete the actual function from the module.
1072     M.getFunctionList().erase(DeadF);
1073   }
1074 
1075   if (!Changed)
1076     return PreservedAnalyses::all();
1077 
1078   // Even if we change the IR, we update the core CGSCC data structures and so
1079   // can preserve the proxy to the function analysis manager.
1080   PreservedAnalyses PA;
1081   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1082   return PA;
1083 }
1084