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