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