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