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