blob: 66a6f80f31e4eba09e927d925383b16a551d6758 [file] [log] [blame]
Chris Lattner7d30a6c2004-06-20 04:11:48 +00001//===- Inliner.cpp - Code common to all inliners --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd075cc22003-08-31 19:10:30 +00009//
Chris Lattner6754b822004-05-23 21:22:17 +000010// This file implements the mechanics required to implement inlining without
11// missing any calls and updating the call graph. The decisions of which calls
12// are profitable to inline are implemented elsewhere.
Chris Lattnerd075cc22003-08-31 19:10:30 +000013//
14//===----------------------------------------------------------------------===//
15
Chandler Carruth1d963112016-12-20 03:15:32 +000016#include "llvm/Transforms/IPO/Inliner.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000023#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000025#include "llvm/ADT/StringRef.h"
Hal Finkel0c083022014-09-01 09:01:39 +000026#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000027#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000028#include "llvm/Analysis/BasicAliasAnalysis.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000029#include "llvm/Analysis/BlockFrequencyInfo.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000030#include "llvm/Analysis/CGSCCPassManager.h"
Chris Lattnerd075cc22003-08-31 19:10:30 +000031#include "llvm/Analysis/CallGraph.h"
Dan Gohman4552e3c2009-10-13 18:30:07 +000032#include "llvm/Analysis/InlineCost.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000033#include "llvm/Analysis/LazyCallGraph.h"
Adam Nemet0965da22017-10-09 23:19:02 +000034#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Easwaran Raman71069cf2016-06-09 22:23:21 +000035#include "llvm/Analysis/ProfileSummaryInfo.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000036#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000037#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000038#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000039#include "llvm/IR/Attributes.h"
40#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000041#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/DataLayout.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000043#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/DerivedTypes.h"
Diego Novilloa9298b22014-04-08 16:42:34 +000045#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000046#include "llvm/IR/Function.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000047#include "llvm/IR/InstIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000048#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Instructions.h"
50#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000051#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Module.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000053#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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000059#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000062#include "llvm/Transforms/Utils/ImportedFunctionsInliningStatistics.h"
Chandler Carruth6e9bb7e2016-12-26 23:43:27 +000063#include "llvm/Transforms/Utils/ModuleUtils.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000064#include <algorithm>
65#include <cassert>
66#include <functional>
David Bolvanskyc0aa4b72018-08-05 14:53:08 +000067#include <sstream>
Eugene Zelenkof27d1612017-10-19 21:21:30 +000068#include <tuple>
69#include <utility>
70#include <vector>
71
Chris Lattnera82f1312003-11-21 21:45:31 +000072using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "inline"
75
Chris Lattner1631bcb2006-12-19 22:09:18 +000076STATISTIC(NumInlined, "Number of functions inlined");
Chris Lattnerb49a6222010-05-01 17:19:38 +000077STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
Chris Lattner1631bcb2006-12-19 22:09:18 +000078STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
Chris Lattnerd3374e82009-08-27 06:29:33 +000079STATISTIC(NumMergedAllocas, "Number of allocas merged together");
Chris Lattner1631bcb2006-12-19 22:09:18 +000080
Benjamin Kramerbde91762012-06-02 10:20:22 +000081// This weirdly named statistic tracks the number of times that, when attempting
Chandler Carruth7ae90d42012-04-11 10:15:10 +000082// to inline a function A into B, we analyze the callers of B in order to see
83// if those would be more profitable and blocked inline steps.
84STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
85
Chandler Carruthf702d8e2016-08-17 02:40:23 +000086/// Flag to disable manual alloca merging.
87///
88/// Merging of allocas was originally done as a stack-size saving technique
89/// prior to LLVM's code generator having support for stack coloring based on
90/// lifetime markers. It is now in the process of being removed. To experiment
91/// with disabling it and relying fully on lifetime marker based stack
92/// coloring, you can pass this flag to LLVM.
93static cl::opt<bool>
94 DisableInlinedAllocaMerging("disable-inlined-alloca-merging",
95 cl::init(false), cl::Hidden);
96
Piotr Padlewski84abc742016-07-29 00:27:16 +000097namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000098
Piotr Padlewski84abc742016-07-29 00:27:16 +000099enum class InlinerFunctionImportStatsOpts {
100 No = 0,
101 Basic = 1,
102 Verbose = 2,
103};
104
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000105} // end anonymous namespace
106
107static cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats(
Piotr Padlewski84abc742016-07-29 00:27:16 +0000108 "inliner-function-import-stats",
109 cl::init(InlinerFunctionImportStatsOpts::No),
110 cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic",
111 "basic statistics"),
112 clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000113 "printing of statistics for each inlined function")),
Piotr Padlewski84abc742016-07-29 00:27:16 +0000114 cl::Hidden, cl::desc("Enable inliner stats for imported functions"));
Piotr Padlewski84abc742016-07-29 00:27:16 +0000115
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000116/// Flag to add inline messages as callsite attributes 'inline-remark'.
117static cl::opt<bool>
118 InlineRemarkAttribute("inline-remark-attribute", cl::init(false),
119 cl::Hidden,
120 cl::desc("Enable adding inline-remark attribute to"
121 " callsites processed by inliner but decided"
122 " to be not inlined"));
123
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000124LegacyInlinerBase::LegacyInlinerBase(char &ID) : CallGraphSCCPass(ID) {}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000125
Chandler Carruth1d963112016-12-20 03:15:32 +0000126LegacyInlinerBase::LegacyInlinerBase(char &ID, bool InsertLifetime)
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000127 : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {}
Chris Lattner22ad7ab2008-01-12 06:49:13 +0000128
Sanjay Patelf1b0db12015-03-10 16:42:24 +0000129/// For this class, we declare that we require and preserve the call graph.
130/// If the derived class implements this method, it should
Chris Lattnerf94bed32007-01-30 23:28:39 +0000131/// always explicitly call the implementation here.
Chandler Carruth1d963112016-12-20 03:15:32 +0000132void LegacyInlinerBase::getAnalysisUsage(AnalysisUsage &AU) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000133 AU.addRequired<AssumptionCacheTracker>();
Easwaran Raman71069cf2016-06-09 22:23:21 +0000134 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000135 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth12884f72016-03-02 15:56:53 +0000136 getAAResultsAnalysisUsage(AU);
Chandler Carruthe40e60e2012-12-27 11:17:15 +0000137 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnerf94bed32007-01-30 23:28:39 +0000138}
139
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000140using InlinedArrayAllocasTy = DenseMap<ArrayType *, std::vector<AllocaInst *>>;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000141
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000142/// Look at all of the allocas that we inlined through this call site. If we
143/// have already inlined other allocas through other calls into this function,
144/// then we know that they have disjoint lifetimes and that we can merge them.
Chris Lattnerd3374e82009-08-27 06:29:33 +0000145///
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000146/// There are many heuristics possible for merging these allocas, and the
147/// different options have different tradeoffs. One thing that we *really*
148/// don't want to hurt is SRoA: once inlining happens, often allocas are no
149/// longer address taken and so they can be promoted.
150///
151/// Our "solution" for that is to only merge allocas whose outermost type is an
152/// array type. These are usually not promoted because someone is using a
153/// variable index into them. These are also often the most important ones to
154/// merge.
155///
156/// A better solution would be to have real memory lifetime markers in the IR
157/// and not have the inliner do any merging of allocas at all. This would
158/// allow the backend to do proper stack slot coloring of all allocas that
159/// *actually make it to the backend*, which is really what we want.
160///
161/// Because we don't have this information, we do this simple and useful hack.
162static void mergeInlinedArrayAllocas(
163 Function *Caller, InlineFunctionInfo &IFI,
164 InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory) {
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000165 SmallPtrSet<AllocaInst *, 16> UsedAllocas;
166
Chris Lattnerfb212de2010-12-06 07:52:42 +0000167 // When processing our SCC, check to see if CS was inlined from some other
168 // call site. For example, if we're processing "A" in this code:
169 // A() { B() }
170 // B() { x = alloca ... C() }
171 // C() { y = alloca ... }
172 // Assume that C was not inlined into B initially, and so we're processing A
173 // and decide to inline B into A. Doing this makes an alloca available for
174 // reuse and makes a callsite (C) available for inlining. When we process
175 // the C call site we don't want to do any alloca merging between X and Y
176 // because their scopes are not disjoint. We could make this smarter by
177 // keeping track of the inline history for each alloca in the
178 // InlinedArrayAllocas but this isn't likely to be a significant win.
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000179 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000180 return;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000181
Chris Lattnerd3374e82009-08-27 06:29:33 +0000182 // Loop over all the allocas we have so far and see if they can be merged with
183 // a previously inlined alloca. If not, remember that we had it.
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000184 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size(); AllocaNo != e;
185 ++AllocaNo) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000186 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000187
Chris Lattnerd3374e82009-08-27 06:29:33 +0000188 // Don't bother trying to merge array allocations (they will usually be
189 // canonicalized to be an allocation *of* an array), or allocations whose
190 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattner229907c2011-07-18 04:54:35 +0000191 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Craig Topperf40110f2014-04-25 05:29:35 +0000192 if (!ATy || AI->isArrayAllocation())
Chris Lattnerd3374e82009-08-27 06:29:33 +0000193 continue;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000194
Chris Lattnerd3374e82009-08-27 06:29:33 +0000195 // Get the list of all available allocas for this array type.
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000196 std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy];
197
Chris Lattnerd3374e82009-08-27 06:29:33 +0000198 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
199 // that we have to be careful not to reuse the same "available" alloca for
200 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
201 // set to keep track of which "available" allocas are being used by this
202 // function. Also, AllocasForType can be empty of course!
203 bool MergedAwayAlloca = false;
Yaron Keren62064d62015-06-25 19:28:24 +0000204 for (AllocaInst *AvailableAlloca : AllocasForType) {
Hal Finkel9caa8f72013-07-16 17:10:55 +0000205 unsigned Align1 = AI->getAlignment(),
206 Align2 = AvailableAlloca->getAlignment();
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000207
Chris Lattnerd3374e82009-08-27 06:29:33 +0000208 // The available alloca has to be in the right function, not in some other
209 // function in this SCC.
210 if (AvailableAlloca->getParent() != AI->getParent())
211 continue;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000212
Chris Lattnerd3374e82009-08-27 06:29:33 +0000213 // If the inlined function already uses this alloca then we can't reuse
214 // it.
David Blaikie70573dc2014-11-19 07:49:26 +0000215 if (!UsedAllocas.insert(AvailableAlloca).second)
Chris Lattnerd3374e82009-08-27 06:29:33 +0000216 continue;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000217
Chris Lattnerd3374e82009-08-27 06:29:33 +0000218 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
219 // success!
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000220 LLVM_DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI
221 << "\n\t\tINTO: " << *AvailableAlloca << '\n');
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000222
Evgeniy Stepanovd8b86f72015-09-29 00:30:19 +0000223 // Move affected dbg.declare calls immediately after the new alloca to
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000224 // avoid the situation when a dbg.declare precedes its alloca.
Evgeniy Stepanovd8b86f72015-09-29 00:30:19 +0000225 if (auto *L = LocalAsMetadata::getIfExists(AI))
226 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
227 for (User *U : MDV->users())
228 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
229 DDI->moveBefore(AvailableAlloca->getNextNode());
230
Chris Lattnerd3374e82009-08-27 06:29:33 +0000231 AI->replaceAllUsesWith(AvailableAlloca);
Hal Finkel9caa8f72013-07-16 17:10:55 +0000232
Hal Finkelec7cd262013-07-17 14:32:41 +0000233 if (Align1 != Align2) {
234 if (!Align1 || !Align2) {
Mehdi Amini46a43552015-03-04 18:43:29 +0000235 const DataLayout &DL = Caller->getParent()->getDataLayout();
236 unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType());
Hal Finkelec7cd262013-07-17 14:32:41 +0000237
238 Align1 = Align1 ? Align1 : TypeAlign;
239 Align2 = Align2 ? Align2 : TypeAlign;
240 }
241
242 if (Align1 > Align2)
243 AvailableAlloca->setAlignment(AI->getAlignment());
244 }
Hal Finkel9caa8f72013-07-16 17:10:55 +0000245
Chris Lattnerd3374e82009-08-27 06:29:33 +0000246 AI->eraseFromParent();
247 MergedAwayAlloca = true;
248 ++NumMergedAllocas;
Craig Topperf40110f2014-04-25 05:29:35 +0000249 IFI.StaticAllocas[AllocaNo] = nullptr;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000250 break;
251 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000252
Chris Lattnerd3374e82009-08-27 06:29:33 +0000253 // If we already nuked the alloca, we're done with it.
254 if (MergedAwayAlloca)
255 continue;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000256
Chris Lattnerd3374e82009-08-27 06:29:33 +0000257 // If we were unable to merge away the alloca either because there are no
258 // allocas of the right type available or because we reused them all
259 // already, remember that this alloca came from an inlined function and mark
260 // it used so we don't reuse it for other allocas from this inline
261 // operation.
262 AllocasForType.push_back(AI);
263 UsedAllocas.insert(AI);
Chris Lattner6754b822004-05-23 21:22:17 +0000264 }
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000265}
266
267/// If it is possible to inline the specified call site,
268/// do so and update the CallGraph for this operation.
269///
270/// This function also does some basic book-keeping to update the IR. The
271/// InlinedArrayAllocas map keeps track of any allocas that are already
272/// available from other functions inlined into the caller. If we are able to
273/// inline this call site we attempt to reuse already available allocas or add
274/// any new allocas to the set if not possible.
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000275static InlineResult InlineCallIfPossible(
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000276 CallSite CS, InlineFunctionInfo &IFI,
277 InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory,
278 bool InsertLifetime, function_ref<AAResults &(Function &)> &AARGetter,
279 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
280 Function *Callee = CS.getCalledFunction();
281 Function *Caller = CS.getCaller();
282
283 AAResults &AAR = AARGetter(*Callee);
284
285 // Try to inline the function. Get the list of static allocas that were
286 // inlined.
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000287 InlineResult IR = InlineFunction(CS, IFI, &AAR, InsertLifetime);
288 if (!IR)
289 return IR;
Chandler Carruthf702d8e2016-08-17 02:40:23 +0000290
291 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
292 ImportedFunctionsStats.recordInline(*Caller, *Callee);
293
294 AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee);
295
296 if (!DisableInlinedAllocaMerging)
297 mergeInlinedArrayAllocas(Caller, IFI, InlinedArrayAllocas, InlineHistory);
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000298
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000299 return IR; // success
Chris Lattnerd075cc22003-08-31 19:10:30 +0000300}
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000301
Sean Silvaab6a6832016-07-23 04:22:50 +0000302/// Return true if inlining of CS can block the caller from being
303/// inlined which is proved to be more beneficial. \p IC is the
304/// estimated inline cost associated with callsite \p CS.
Haicheng Wuf8dc2d82017-01-30 16:15:14 +0000305/// \p TotalSecondaryCost will be set to the estimated cost of inlining the
306/// caller if \p CS is suppressed for inlining.
Sean Silvaab6a6832016-07-23 04:22:50 +0000307static bool
308shouldBeDeferred(Function *Caller, CallSite CS, InlineCost IC,
309 int &TotalSecondaryCost,
Benjamin Kramer41e66da2016-08-06 12:33:46 +0000310 function_ref<InlineCost(CallSite CS)> GetInlineCost) {
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000311 // For now we only handle local or inline functions.
312 if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
313 return false;
Easwaran Raman366a8732019-01-05 02:26:29 +0000314 // If the cost of inlining CS is non-positive, it is not going to prevent the
315 // caller from being inlined into its callers and hence we don't need to
316 // defer.
317 if (IC.getCost() <= 0)
318 return false;
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000319 // Try to detect the case where the current inlining candidate caller (call
320 // it B) is a static or linkonce-ODR function and is an inlining candidate
321 // elsewhere, and the current candidate callee (call it C) is large enough
322 // that inlining it into B would make B too big to inline later. In these
323 // circumstances it may be best not to inline C into B, but to inline B into
324 // its callers.
325 //
326 // This only applies to static and linkonce-ODR functions because those are
327 // expected to be available for inlining in the translation units where they
328 // are used. Thus we will always have the opportunity to make local inlining
329 // decisions. Importantly the linkonce-ODR linkage covers inline functions
330 // and templates in C++.
331 //
332 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
333 // the internal implementation of the inline cost metrics rather than
334 // treating them as truly abstract units etc.
335 TotalSecondaryCost = 0;
336 // The candidate cost to be imposed upon the current function.
Evgeny Astigeevich7823c662017-03-22 12:01:57 +0000337 int CandidateCost = IC.getCost() - 1;
Easwaran Raman366a8732019-01-05 02:26:29 +0000338 // If the caller has local linkage and can be inlined to all its callers, we
339 // can apply a huge negative bonus to TotalSecondaryCost.
340 bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000341 // This bool tracks what happens if we DO inline C into B.
342 bool inliningPreventsSomeOuterInline = false;
343 for (User *U : Caller->users()) {
Easwaran Raman366a8732019-01-05 02:26:29 +0000344 // If the caller will not be removed (either because it does not have a
345 // local linkage or because the LastCallToStaticBonus has been already
346 // applied), then we can exit the loop early.
347 if (!ApplyLastCallBonus && TotalSecondaryCost >= IC.getCost())
348 return false;
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000349 CallSite CS2(U);
350
351 // If this isn't a call to Caller (it could be some other sort
352 // of reference) skip it. Such references will prevent the caller
353 // from being removed.
354 if (!CS2 || CS2.getCalledFunction() != Caller) {
Easwaran Raman366a8732019-01-05 02:26:29 +0000355 ApplyLastCallBonus = false;
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000356 continue;
357 }
358
Sean Silvaab6a6832016-07-23 04:22:50 +0000359 InlineCost IC2 = GetInlineCost(CS2);
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000360 ++NumCallerCallersAnalyzed;
361 if (!IC2) {
Easwaran Raman366a8732019-01-05 02:26:29 +0000362 ApplyLastCallBonus = false;
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000363 continue;
364 }
365 if (IC2.isAlways())
366 continue;
367
Xinliang David Lif450b882016-11-04 03:00:52 +0000368 // See if inlining of the original callsite would erase the cost delta of
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000369 // this callsite. We subtract off the penalty for the call instruction,
370 // which we would be deleting.
371 if (IC2.getCostDelta() <= CandidateCost) {
372 inliningPreventsSomeOuterInline = true;
373 TotalSecondaryCost += IC2.getCost();
374 }
375 }
376 // If all outer calls to Caller would get inlined, the cost for the last
377 // one is set very low by getInlineCost, in anticipation that Caller will
378 // be removed entirely. We did not account for this above unless there
379 // is only one caller of Caller.
Easwaran Raman366a8732019-01-05 02:26:29 +0000380 if (ApplyLastCallBonus)
Piotr Padlewskid89875c2016-08-10 21:15:22 +0000381 TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000382
383 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost())
384 return true;
385
386 return false;
387}
388
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000389static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
390 const ore::NV &Arg) {
391 return R << Arg.Val;
392}
393
394template <class RemarkT>
395RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
396 using namespace ore;
397 if (IC.isAlways()) {
398 R << "(cost=always)";
399 } else if (IC.isNever()) {
400 R << "(cost=never)";
401 } else {
402 R << "(cost=" << ore::NV("Cost", IC.getCost())
403 << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
404 }
405 if (const char *Reason = IC.getReason())
406 R << ": " << ore::NV("Reason", Reason);
407 return R;
408}
409
410static std::string inlineCostStr(const InlineCost &IC) {
411 std::stringstream Remark;
412 Remark << IC;
413 return Remark.str();
414}
415
Sam Elliotte604b562017-08-21 16:45:47 +0000416/// Return the cost only if the inliner should attempt to inline at the given
417/// CallSite. If we return the cost, we will emit an optimisation remark later
418/// using that cost, so we won't do so from this function.
419static Optional<InlineCost>
420shouldInline(CallSite CS, function_ref<InlineCost(CallSite CS)> GetInlineCost,
421 OptimizationRemarkEmitter &ORE) {
Adam Nemetc507ac92016-09-27 23:47:03 +0000422 using namespace ore;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000423
Sean Silvaab6a6832016-07-23 04:22:50 +0000424 InlineCost IC = GetInlineCost(CS);
Adam Nemetc507ac92016-09-27 23:47:03 +0000425 Instruction *Call = CS.getInstruction();
426 Function *Callee = CS.getCalledFunction();
Adam Nemete7bdf222017-01-30 16:22:45 +0000427 Function *Caller = CS.getCaller();
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000428
Daniel Dunbar3933e662008-10-30 19:26:59 +0000429 if (IC.isAlways()) {
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000430 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000431 << ", Call: " << *CS.getInstruction() << "\n");
Sam Elliotte604b562017-08-21 16:45:47 +0000432 return IC;
Daniel Dunbar3933e662008-10-30 19:26:59 +0000433 }
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000434
Daniel Dunbar3933e662008-10-30 19:26:59 +0000435 if (IC.isNever()) {
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000436 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000437 << ", Call: " << *CS.getInstruction() << "\n");
Adam Nemet15fccf02017-09-19 23:00:55 +0000438 ORE.emit([&]() {
439 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
Adam Nemete7bdf222017-01-30 16:22:45 +0000440 << NV("Callee", Callee) << " not inlined into "
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000441 << NV("Caller", Caller) << " because it should never be inlined "
442 << IC;
Adam Nemet15fccf02017-09-19 23:00:55 +0000443 });
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000444 return IC;
Daniel Dunbar3933e662008-10-30 19:26:59 +0000445 }
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000446
Chandler Carruth0539c072012-03-31 12:42:41 +0000447 if (!IC) {
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000448 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000449 << ", Call: " << *CS.getInstruction() << "\n");
Adam Nemet15fccf02017-09-19 23:00:55 +0000450 ORE.emit([&]() {
451 return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
Adam Nemete7bdf222017-01-30 16:22:45 +0000452 << NV("Callee", Callee) << " not inlined into "
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000453 << NV("Caller", Caller) << " because too costly to inline " << IC;
Adam Nemet15fccf02017-09-19 23:00:55 +0000454 });
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000455 return IC;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000456 }
Dale Johannesen30599242009-10-09 00:11:32 +0000457
Xinliang David Li4b2fdcc2016-04-29 22:59:36 +0000458 int TotalSecondaryCost = 0;
Sean Silvaab6a6832016-07-23 04:22:50 +0000459 if (shouldBeDeferred(Caller, CS, IC, TotalSecondaryCost, GetInlineCost)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000460 LLVM_DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction()
461 << " Cost = " << IC.getCost()
462 << ", outer Cost = " << TotalSecondaryCost << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +0000463 ORE.emit([&]() {
464 return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
Adam Nemete7bdf222017-01-30 16:22:45 +0000465 Call)
Adam Nemetc507ac92016-09-27 23:47:03 +0000466 << "Not inlining. Cost of inlining " << NV("Callee", Callee)
467 << " increases the cost of inlining " << NV("Caller", Caller)
Vivek Pandya95906582017-10-11 17:12:59 +0000468 << " in other contexts";
469 });
Sam Elliotte604b562017-08-21 16:45:47 +0000470
471 // IC does not bool() to false, so get an InlineCost that will.
472 // This will not be inspected to make an error message.
473 return None;
Dale Johannesen30599242009-10-09 00:11:32 +0000474 }
475
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000476 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000477 << ", Call: " << *CS.getInstruction() << '\n');
Sam Elliotte604b562017-08-21 16:45:47 +0000478 return IC;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000479}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000480
Sanjay Patelf1b0db12015-03-10 16:42:24 +0000481/// Return true if the specified inline history ID
Chris Lattnere8262672010-05-01 01:05:10 +0000482/// indicates an inline history that includes the specified function.
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000483static bool InlineHistoryIncludes(
484 Function *F, int InlineHistoryID,
485 const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) {
Chris Lattnere8262672010-05-01 01:05:10 +0000486 while (InlineHistoryID != -1) {
487 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
488 "Invalid inline history ID");
489 if (InlineHistory[InlineHistoryID].first == F)
490 return true;
491 InlineHistoryID = InlineHistory[InlineHistoryID].second;
492 }
493 return false;
494}
495
Chandler Carruth1d963112016-12-20 03:15:32 +0000496bool LegacyInlinerBase::doInitialization(CallGraph &CG) {
Piotr Padlewski84abc742016-07-29 00:27:16 +0000497 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
498 ImportedFunctionsStats.setModuleInfo(CG.getModule());
499 return false; // No changes to CallGraph.
500}
501
Chandler Carruth1d963112016-12-20 03:15:32 +0000502bool LegacyInlinerBase::runOnSCC(CallGraphSCC &SCC) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000503 if (skipSCC(SCC))
504 return false;
Andrew Kaylor9c81d0f2016-05-23 21:57:54 +0000505 return inlineCalls(SCC);
506}
Andrew Kayloraa641a52016-04-22 22:06:11 +0000507
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000508static void emit_inlined_into(OptimizationRemarkEmitter &ORE, DebugLoc &DLoc,
509 const BasicBlock *Block, const Function &Callee,
510 const Function &Caller, const InlineCost &IC) {
511 ORE.emit([&]() {
512 bool AlwaysInline = IC.isAlways();
513 StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
514 return OptimizationRemark(DEBUG_TYPE, RemarkName, DLoc, Block)
515 << ore::NV("Callee", &Callee) << " inlined into "
516 << ore::NV("Caller", &Caller) << " with " << IC;
517 });
518}
519
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000520static void setInlineRemark(CallSite &CS, StringRef message) {
521 if (!InlineRemarkAttribute)
522 return;
523
524 Attribute attr = Attribute::get(CS->getContext(), "inline-remark", message);
525 CS.addAttribute(AttributeList::FunctionIndex, attr);
526}
527
Sean Silvaab6a6832016-07-23 04:22:50 +0000528static bool
529inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000530 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
Sean Silvaab6a6832016-07-23 04:22:50 +0000531 ProfileSummaryInfo *PSI, TargetLibraryInfo &TLI,
532 bool InsertLifetime,
Benjamin Kramer41e66da2016-08-06 12:33:46 +0000533 function_ref<InlineCost(CallSite CS)> GetInlineCost,
534 function_ref<AAResults &(Function &)> AARGetter,
Piotr Padlewski84abc742016-07-29 00:27:16 +0000535 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000536 SmallPtrSet<Function *, 8> SCCFunctions;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000537 LLVM_DEBUG(dbgs() << "Inliner visiting SCC:");
Yaron Keren4c548f22015-06-20 07:12:33 +0000538 for (CallGraphNode *Node : SCC) {
539 Function *F = Node->getFunction();
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000540 if (F)
541 SCCFunctions.insert(F);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000542 LLVM_DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattnerd075cc22003-08-31 19:10:30 +0000543 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000544
Chris Lattner6754b822004-05-23 21:22:17 +0000545 // Scan through and identify all call sites ahead of time so that we only
546 // inline call sites in the original functions, not call sites that result
547 // from inlining other functions.
Chris Lattnere8262672010-05-01 01:05:10 +0000548 SmallVector<std::pair<CallSite, int>, 16> CallSites;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000549
Chris Lattnere8262672010-05-01 01:05:10 +0000550 // When inlining a callee produces new call sites, we want to keep track of
551 // the fact that they were inlined from the callee. This allows us to avoid
552 // infinite inlining in some obscure cases. To represent this, we use an
553 // index into the InlineHistory vector.
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000554 SmallVector<std::pair<Function *, int>, 8> InlineHistory;
Chris Lattner6754b822004-05-23 21:22:17 +0000555
Yaron Keren4c548f22015-06-20 07:12:33 +0000556 for (CallGraphNode *Node : SCC) {
557 Function *F = Node->getFunction();
Adam Nemetcef33142016-08-26 20:21:05 +0000558 if (!F || F->isDeclaration())
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000559 continue;
560
Adam Nemetcef33142016-08-26 20:21:05 +0000561 OptimizationRemarkEmitter ORE(F);
Yaron Keren4c548f22015-06-20 07:12:33 +0000562 for (BasicBlock &BB : *F)
563 for (Instruction &I : BB) {
564 CallSite CS(cast<Value>(&I));
Dale Johannesen30599242009-10-09 00:11:32 +0000565 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattner9e507472009-08-31 05:34:32 +0000566 // never be inlined.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000567 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000568 continue;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000569
Chris Lattner9e507472009-08-31 05:34:32 +0000570 // If this is a direct call to an external function, we can never inline
571 // it. If it is an indirect call, inlining may resolve it to be a
572 // direct call, so we keep it.
Yaron Kerenc66c06b2015-07-19 15:48:07 +0000573 if (Function *Callee = CS.getCalledFunction())
Adam Nemetcef33142016-08-26 20:21:05 +0000574 if (Callee->isDeclaration()) {
Adam Nemeta62b7e12016-09-27 20:55:07 +0000575 using namespace ore;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000576
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000577 setInlineRemark(CS, "unavailable definition");
Vivek Pandya95906582017-10-11 17:12:59 +0000578 ORE.emit([&]() {
579 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
Adam Nemeta62b7e12016-09-27 20:55:07 +0000580 << NV("Callee", Callee) << " will not be inlined into "
Adam Nemet11421472016-09-27 21:58:17 +0000581 << NV("Caller", CS.getCaller())
582 << " because its definition is unavailable"
Vivek Pandya95906582017-10-11 17:12:59 +0000583 << setIsVerbose();
584 });
Yaron Kerenc66c06b2015-07-19 15:48:07 +0000585 continue;
Adam Nemetcef33142016-08-26 20:21:05 +0000586 }
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000587
Chris Lattnere8262672010-05-01 01:05:10 +0000588 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000589 }
590 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000591
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000592 LLVM_DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000593
Chris Lattnera5cdd5e2010-04-20 00:47:08 +0000594 // If there are no calls in this function, exit early.
595 if (CallSites.empty())
596 return false;
Yaron Keren6967cbb2015-07-02 14:25:09 +0000597
Chris Lattner6754b822004-05-23 21:22:17 +0000598 // Now that we have all of the call sites, move the ones to functions in the
599 // current SCC to the end of the list.
600 unsigned FirstCallInSCC = CallSites.size();
601 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattnere8262672010-05-01 01:05:10 +0000602 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattner6754b822004-05-23 21:22:17 +0000603 if (SCCFunctions.count(F))
604 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000605
Chris Lattnerd3374e82009-08-27 06:29:33 +0000606 InlinedArrayAllocasTy InlinedArrayAllocas;
Easwaran Ramanf5f91602017-05-09 23:21:10 +0000607 InlineFunctionInfo InlineInfo(&CG, &GetAssumptionCache, PSI);
Chandler Carruth66b31302015-01-04 12:03:27 +0000608
Chris Lattner6754b822004-05-23 21:22:17 +0000609 // Now that we have all of the call sites, loop over them and inline them if
610 // it looks profitable to do so.
611 bool Changed = false;
612 bool LocalChange;
613 do {
614 LocalChange = false;
615 // Iterate over the outer loop because inlining functions can cause indirect
616 // calls to become direct calls.
Yaron Keren4c548f22015-06-20 07:12:33 +0000617 // CallSites may be modified inside so ranged for loop can not be used.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000618 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattnere8262672010-05-01 01:05:10 +0000619 CallSite CS = CallSites[CSi].first;
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000620
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000621 Function *Caller = CS.getCaller();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000622 Function *Callee = CS.getCalledFunction();
623
David Blaikiecb9327b2017-06-09 03:29:20 +0000624 // We can only inline direct calls to non-declarations.
625 if (!Callee || Callee->isDeclaration())
626 continue;
627
David Blaikie6d0f3942017-06-13 02:24:09 +0000628 Instruction *Instr = CS.getInstruction();
629
630 bool IsTriviallyDead = isInstructionTriviallyDead(Instr, &TLI);
631
632 int InlineHistoryID;
633 if (!IsTriviallyDead) {
634 // If this call site was obtained by inlining another function, verify
635 // that the include path for the function did not include the callee
636 // itself. If so, we'd be recursively inlining the same function,
637 // which would provide the same callsites, which would cause us to
638 // infinitely inline.
639 InlineHistoryID = CallSites[CSi].second;
640 if (InlineHistoryID != -1 &&
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000641 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory)) {
642 setInlineRemark(CS, "recursive");
David Blaikie6d0f3942017-06-13 02:24:09 +0000643 continue;
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000644 }
David Blaikie6d0f3942017-06-13 02:24:09 +0000645 }
646
David Blaikieae8c4af2017-06-12 23:01:17 +0000647 // FIXME for new PM: because of the old PM we currently generate ORE and
648 // in turn BFI on demand. With the new PM, the ORE dependency should
649 // just become a regular analysis dependency.
650 OptimizationRemarkEmitter ORE(Caller);
651
Sam Elliotte604b562017-08-21 16:45:47 +0000652 Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE);
David Blaikieae8c4af2017-06-12 23:01:17 +0000653 // If the policy determines that we should inline this function,
654 // delete the call instead.
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000655 if (!OIC.hasValue()) {
656 setInlineRemark(CS, "deferred");
657 continue;
658 }
659
660 if (!OIC.getValue()) {
661 // shouldInline() call returned a negative inline cost that explains
662 // why this callsite should not be inlined.
663 setInlineRemark(CS, inlineCostStr(*OIC));
David Blaikieae8c4af2017-06-12 23:01:17 +0000664 continue;
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000665 }
David Blaikieae8c4af2017-06-12 23:01:17 +0000666
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000667 // If this call site is dead and it is to a readonly function, we should
668 // just delete the call instead of trying to inline it, regardless of
669 // size. This happens because IPSCCP propagates the result out of the
670 // call and then we're left with the dead call.
David Blaikie6d0f3942017-06-13 02:24:09 +0000671 if (IsTriviallyDead) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000672 LLVM_DEBUG(dbgs() << " -> Deleting dead call: " << *Instr << "\n");
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000673 // Update the call graph by deleting the edge from Callee to Caller.
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000674 setInlineRemark(CS, "trivially dead");
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000675 CG[Caller]->removeCallEdgeFor(CS);
David Blaikie6d0f3942017-06-13 02:24:09 +0000676 Instr->eraseFromParent();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000677 ++NumCallsDeleted;
678 } else {
NAKAMURA Takumicd1fc4b2014-04-17 12:22:14 +0000679 // Get DebugLoc to report. CS will be invalid after Inliner.
Sam Elliotte604b562017-08-21 16:45:47 +0000680 DebugLoc DLoc = CS->getDebugLoc();
Adam Nemet896c09b2016-08-10 00:44:44 +0000681 BasicBlock *Block = CS.getParent();
Diego Novillo7f8af8b2014-05-22 14:19:46 +0000682
Chris Lattner2eee5d32010-04-22 23:37:35 +0000683 // Attempt to inline the function.
Adam Nemete7bdf222017-01-30 16:22:45 +0000684 using namespace ore;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000685
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000686 InlineResult IR = InlineCallIfPossible(
687 CS, InlineInfo, InlinedArrayAllocas, InlineHistoryID,
688 InsertLifetime, AARGetter, ImportedFunctionsStats);
689 if (!IR) {
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000690 setInlineRemark(CS, std::string(IR) + "; " + inlineCostStr(*OIC));
Vivek Pandya95906582017-10-11 17:12:59 +0000691 ORE.emit([&]() {
692 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc,
693 Block)
694 << NV("Callee", Callee) << " will not be inlined into "
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000695 << NV("Caller", Caller) << ": " << NV("Reason", IR.message);
Vivek Pandya95906582017-10-11 17:12:59 +0000696 });
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000697 continue;
Diego Novillo7f8af8b2014-05-22 14:19:46 +0000698 }
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000699 ++NumInlined;
Diego Novilloa9298b22014-04-08 16:42:34 +0000700
David Bolvanskyc0aa4b72018-08-05 14:53:08 +0000701 emit_inlined_into(ORE, DLoc, Block, *Callee, *Caller, *OIC);
Diego Novilloa9298b22014-04-08 16:42:34 +0000702
Chris Lattnerc2432b92010-05-01 01:26:13 +0000703 // If inlining this function gave us any new call sites, throw them
Chris Lattner2eee5d32010-04-22 23:37:35 +0000704 // onto our worklist to process. They are useful inline candidates.
Chris Lattnerc2432b92010-05-01 01:26:13 +0000705 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattnere8262672010-05-01 01:05:10 +0000706 // Create a new inline history entry for this, so that we remember
707 // that these new callsites came about due to inlining Callee.
708 int NewHistoryID = InlineHistory.size();
709 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
710
Yaron Keren4c548f22015-06-20 07:12:33 +0000711 for (Value *Ptr : InlineInfo.InlinedCalls)
Chandler Carruth21211992012-03-25 04:03:40 +0000712 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
Chris Lattnerc691de32010-04-23 18:37:01 +0000713 }
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000714 }
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000715
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000716 // If we inlined or deleted the last possible call site to the function,
717 // delete the function body now.
718 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattner9e507472009-08-31 05:34:32 +0000719 // TODO: Can remove if in SCC now.
Chris Lattner081375b2009-08-31 03:15:49 +0000720 !SCCFunctions.count(Callee) &&
721 // The function may be apparently dead, but if there are indirect
722 // callgraph references to the node, we cannot delete it yet, this
723 // could invalidate the CGSCC iterator.
724 CG[Callee]->getNumReferences() == 0) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000725 LLVM_DEBUG(dbgs() << " -> Deleting dead function: "
726 << Callee->getName() << "\n");
Chris Lattnerd3374e82009-08-27 06:29:33 +0000727 CallGraphNode *CalleeNode = CG[Callee];
Yaron Keren6967cbb2015-07-02 14:25:09 +0000728
Chris Lattnerd3374e82009-08-27 06:29:33 +0000729 // Remove any call graph edges from the callee to its callees.
730 CalleeNode->removeAllCalledFunctions();
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000731
Chris Lattnerd3374e82009-08-27 06:29:33 +0000732 // Removing the node for callee from the call graph and delete it.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000733 delete CG.removeFunctionFromModule(CalleeNode);
Chris Lattnerd3374e82009-08-27 06:29:33 +0000734 ++NumDeleted;
735 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000736
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000737 // Remove this call site from the list. If possible, use
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000738 // swap/pop_back for efficiency, but do not use it if doing so would
739 // move a call site to a function in this SCC before the
740 // 'FirstCallInSCC' barrier.
Chris Lattner4422d312010-04-16 22:42:17 +0000741 if (SCC.isSingular()) {
Benjamin Kramer5ac57e32010-05-31 12:50:41 +0000742 CallSites[CSi] = CallSites.back();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000743 CallSites.pop_back();
744 } else {
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000745 CallSites.erase(CallSites.begin() + CSi);
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000746 }
747 --CSi;
748
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000749 Changed = true;
750 LocalChange = true;
751 }
Chris Lattner6754b822004-05-23 21:22:17 +0000752 } while (LocalChange);
Chris Lattner4d25c862004-04-08 06:34:31 +0000753
Chris Lattnerd075cc22003-08-31 19:10:30 +0000754 return Changed;
755}
756
Chandler Carruth1d963112016-12-20 03:15:32 +0000757bool LegacyInlinerBase::inlineCalls(CallGraphSCC &SCC) {
Sean Silvaab6a6832016-07-23 04:22:50 +0000758 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000759 ACT = &getAnalysis<AssumptionCacheTracker>();
Vedant Kumare7b789b2018-11-19 05:23:16 +0000760 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Sean Silvaab6a6832016-07-23 04:22:50 +0000761 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000762 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
763 return ACT->getAssumptionCache(F);
764 };
765 return inlineCallsImpl(SCC, CG, GetAssumptionCache, PSI, TLI, InsertLifetime,
Sean Silvaab6a6832016-07-23 04:22:50 +0000766 [this](CallSite CS) { return getInlineCost(CS); },
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000767 LegacyAARGetter(*this), ImportedFunctionsStats);
Sean Silvaab6a6832016-07-23 04:22:50 +0000768}
769
Sanjay Patelf1b0db12015-03-10 16:42:24 +0000770/// Remove now-dead linkonce functions at the end of
771/// processing to avoid breaking the SCC traversal.
Chandler Carruth1d963112016-12-20 03:15:32 +0000772bool LegacyInlinerBase::doFinalization(CallGraph &CG) {
Piotr Padlewski84abc742016-07-29 00:27:16 +0000773 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
774 ImportedFunctionsStats.dump(InlinerFunctionImportStats ==
775 InlinerFunctionImportStatsOpts::Verbose);
Devang Patelf0ef3572008-11-05 01:39:16 +0000776 return removeDeadFunctions(CG);
777}
778
Sanjay Patelf1b0db12015-03-10 16:42:24 +0000779/// Remove dead functions that are not included in DNR (Do Not Remove) list.
Chandler Carruth1d963112016-12-20 03:15:32 +0000780bool LegacyInlinerBase::removeDeadFunctions(CallGraph &CG,
781 bool AlwaysInlineOnly) {
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000782 SmallVector<CallGraphNode *, 16> FunctionsToRemove;
Chandler Carruth6e9bb7e2016-12-26 23:43:27 +0000783 SmallVector<Function *, 16> DeadFunctionsInComdats;
David Majnemerac256cf2015-05-05 20:14:22 +0000784
785 auto RemoveCGN = [&](CallGraphNode *CGN) {
786 // Remove any call graph edges from the function to its callees.
787 CGN->removeAllCalledFunctions();
788
789 // Remove any edges from the external node to the function's call graph
790 // node. These edges might have been made irrelegant due to
791 // optimization of the program.
792 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
793
794 // Removing the node for callee from the call graph and delete it.
795 FunctionsToRemove.push_back(CGN);
796 };
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000797
798 // Scan for all of the functions, looking for ones that should now be removed
799 // from the program. Insert the dead ones in the FunctionsToRemove set.
David Blaikiea5d7de92015-08-05 20:55:50 +0000800 for (const auto &I : CG) {
801 CallGraphNode *CGN = I.second.get();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000802 Function *F = CGN->getFunction();
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000803 if (!F || F->isDeclaration())
804 continue;
805
806 // Handle the case when this function is called and we only want to care
807 // about always-inline functions. This is a bit of a hack to share code
808 // between here and the InlineAlways pass.
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000809 if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline))
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000810 continue;
811
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000812 // If the only remaining users of the function are dead constants, remove
813 // them.
814 F->removeDeadConstantUsers();
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000815
Eli Friedman1923a332011-10-20 05:23:42 +0000816 if (!F->isDefTriviallyDead())
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000817 continue;
David Majnemerac077032014-10-08 19:32:32 +0000818
819 // It is unsafe to drop a function with discardable linkage from a COMDAT
820 // without also dropping the other members of the COMDAT.
821 // The inliner doesn't visit non-function entities which are in COMDAT
822 // groups so it is unsafe to do so *unless* the linkage is local.
David Majnemerac256cf2015-05-05 20:14:22 +0000823 if (!F->hasLocalLinkage()) {
Chandler Carruth6e9bb7e2016-12-26 23:43:27 +0000824 if (F->hasComdat()) {
825 DeadFunctionsInComdats.push_back(F);
David Majnemerac256cf2015-05-05 20:14:22 +0000826 continue;
827 }
828 }
Devang Patelf0ef3572008-11-05 01:39:16 +0000829
David Majnemerac256cf2015-05-05 20:14:22 +0000830 RemoveCGN(CGN);
Chris Lattnerc87784f2004-04-20 22:06:53 +0000831 }
David Majnemerac256cf2015-05-05 20:14:22 +0000832 if (!DeadFunctionsInComdats.empty()) {
Chandler Carruth6e9bb7e2016-12-26 23:43:27 +0000833 // Filter out the functions whose comdats remain alive.
834 filterDeadComdatFunctions(CG.getModule(), DeadFunctionsInComdats);
835 // Remove the rest.
836 for (Function *F : DeadFunctionsInComdats)
837 RemoveCGN(CG[F]);
David Majnemerac256cf2015-05-05 20:14:22 +0000838 }
839
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000840 if (FunctionsToRemove.empty())
841 return false;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000842
843 // Now that we know which functions to delete, do so. We didn't want to do
844 // this inline, because that would invalidate our CallGraph::iterator
845 // objects. :(
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000846 //
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000847 // Note that it doesn't matter that we are iterating over a non-stable order
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000848 // here to do this, it doesn't matter which order the functions are deleted
849 // in.
Chandler Carruth45ae88f2012-04-01 10:41:24 +0000850 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
Chandler Carruth8562d3a2016-08-03 01:02:31 +0000851 FunctionsToRemove.erase(
852 std::unique(FunctionsToRemove.begin(), FunctionsToRemove.end()),
853 FunctionsToRemove.end());
Yaron Keren62064d62015-06-25 19:28:24 +0000854 for (CallGraphNode *CGN : FunctionsToRemove) {
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000855 delete CG.removeFunctionFromModule(CGN);
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000856 ++NumDeleted;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000857 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000858 return true;
Chris Lattnerc87784f2004-04-20 22:06:53 +0000859}
Chandler Carruth1d963112016-12-20 03:15:32 +0000860
Teresa Johnsone87868b2018-06-28 20:07:47 +0000861InlinerPass::~InlinerPass() {
862 if (ImportedFunctionsStats) {
863 assert(InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No);
864 ImportedFunctionsStats->dump(InlinerFunctionImportStats ==
865 InlinerFunctionImportStatsOpts::Verbose);
866 }
867}
868
Chandler Carruth1d963112016-12-20 03:15:32 +0000869PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC,
870 CGSCCAnalysisManager &AM, LazyCallGraph &CG,
871 CGSCCUpdateResult &UR) {
Chandler Carruth1d963112016-12-20 03:15:32 +0000872 const ModuleAnalysisManager &MAM =
873 AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG).getManager();
874 bool Changed = false;
875
876 assert(InitialC.size() > 0 && "Cannot handle an empty SCC!");
877 Module &M = *InitialC.begin()->getFunction().getParent();
878 ProfileSummaryInfo *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(M);
879
Teresa Johnsone87868b2018-06-28 20:07:47 +0000880 if (!ImportedFunctionsStats &&
881 InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) {
882 ImportedFunctionsStats =
883 llvm::make_unique<ImportedFunctionsInliningStatistics>();
884 ImportedFunctionsStats->setModuleInfo(M);
885 }
886
Chandler Carruth20e588e2017-03-09 11:35:40 +0000887 // We use a single common worklist for calls across the entire SCC. We
888 // process these in-order and append new calls introduced during inlining to
889 // the end.
890 //
891 // Note that this particular order of processing is actually critical to
892 // avoid very bad behaviors. Consider *highly connected* call graphs where
893 // each function contains a small amonut of code and a couple of calls to
894 // other functions. Because the LLVM inliner is fundamentally a bottom-up
895 // inliner, it can handle gracefully the fact that these all appear to be
896 // reasonable inlining candidates as it will flatten things until they become
897 // too big to inline, and then move on and flatten another batch.
898 //
899 // However, when processing call edges *within* an SCC we cannot rely on this
900 // bottom-up behavior. As a consequence, with heavily connected *SCCs* of
901 // functions we can end up incrementally inlining N calls into each of
902 // N functions because each incremental inlining decision looks good and we
903 // don't have a topological ordering to prevent explosions.
904 //
905 // To compensate for this, we don't process transitive edges made immediate
906 // by inlining until we've done one pass of inlining across the entire SCC.
907 // Large, highly connected SCCs still lead to some amount of code bloat in
908 // this model, but it is uniformly spread across all the functions in the SCC
909 // and eventually they all become too large to inline, rather than
910 // incrementally maknig a single function grow in a super linear fashion.
911 SmallVector<std::pair<CallSite, int>, 16> Calls;
912
Teresa Johnson59da8902018-05-08 01:45:46 +0000913 FunctionAnalysisManager &FAM =
914 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)
915 .getManager();
916
Chandler Carruth20e588e2017-03-09 11:35:40 +0000917 // Populate the initial list of calls in this SCC.
918 for (auto &N : InitialC) {
Teresa Johnson59da8902018-05-08 01:45:46 +0000919 auto &ORE =
920 FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction());
Chandler Carruth20e588e2017-03-09 11:35:40 +0000921 // We want to generally process call sites top-down in order for
922 // simplifications stemming from replacing the call with the returned value
923 // after inlining to be visible to subsequent inlining decisions.
924 // FIXME: Using instructions sequence is a really bad way to do this.
925 // Instead we should do an actual RPO walk of the function body.
926 for (Instruction &I : instructions(N.getFunction()))
927 if (auto CS = CallSite(&I))
Teresa Johnson59da8902018-05-08 01:45:46 +0000928 if (Function *Callee = CS.getCalledFunction()) {
Chandler Carruth20e588e2017-03-09 11:35:40 +0000929 if (!Callee->isDeclaration())
930 Calls.push_back({CS, -1});
Teresa Johnson59da8902018-05-08 01:45:46 +0000931 else if (!isa<IntrinsicInst>(I)) {
932 using namespace ore;
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000933 setInlineRemark(CS, "unavailable definition");
Teresa Johnson59da8902018-05-08 01:45:46 +0000934 ORE.emit([&]() {
935 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
936 << NV("Callee", Callee) << " will not be inlined into "
937 << NV("Caller", CS.getCaller())
938 << " because its definition is unavailable"
939 << setIsVerbose();
940 });
941 }
942 }
Chandler Carruth20e588e2017-03-09 11:35:40 +0000943 }
944 if (Calls.empty())
945 return PreservedAnalyses::all();
946
947 // Capture updatable variables for the current SCC and RefSCC.
Chandler Carruth1d963112016-12-20 03:15:32 +0000948 auto *C = &InitialC;
949 auto *RC = &C->getOuterRefSCC();
950
Chandler Carruth141bf5d2016-12-27 06:46:20 +0000951 // When inlining a callee produces new call sites, we want to keep track of
952 // the fact that they were inlined from the callee. This allows us to avoid
953 // infinite inlining in some obscure cases. To represent this, we use an
954 // index into the InlineHistory vector.
955 SmallVector<std::pair<Function *, int>, 16> InlineHistory;
Chandler Carruth1d963112016-12-20 03:15:32 +0000956
957 // Track a set vector of inlined callees so that we can augment the caller
958 // with all of their edges in the call graph before pruning out the ones that
959 // got simplified away.
960 SmallSetVector<Function *, 4> InlinedCallees;
961
962 // Track the dead functions to delete once finished with inlining calls. We
963 // defer deleting these to make it easier to handle the call graph updates.
964 SmallVector<Function *, 4> DeadFunctions;
965
Chandler Carruth20e588e2017-03-09 11:35:40 +0000966 // Loop forward over all of the calls. Note that we cannot cache the size as
967 // inlining can introduce new calls that need to be processed.
968 for (int i = 0; i < (int)Calls.size(); ++i) {
969 // We expect the calls to typically be batched with sequences of calls that
970 // have the same caller, so we first set up some shared infrastructure for
971 // this caller. We also do any pruning we can at this layer on the caller
972 // alone.
973 Function &F = *Calls[i].first.getCaller();
974 LazyCallGraph::Node &N = *CG.lookup(F);
Chandler Carruth1d963112016-12-20 03:15:32 +0000975 if (CG.lookupSCC(N) != C)
976 continue;
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000977 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
978 setInlineRemark(Calls[i].first, "optnone attribute");
Chandler Carruth1d963112016-12-20 03:15:32 +0000979 continue;
David Bolvanskyc1b27b52018-08-28 15:27:25 +0000980 }
Chandler Carruth1d963112016-12-20 03:15:32 +0000981
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000982 LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n");
Chandler Carruthd4be9f42017-01-22 10:33:58 +0000983
Chandler Carruthb698d592017-01-22 10:34:01 +0000984 // Get a FunctionAnalysisManager via a proxy for this particular node. We
985 // do this each time we visit a node as the SCC may have changed and as
986 // we're going to mutate this particular function we want to make sure the
987 // proxy is in place to forward any invalidation events. We can use the
988 // manager we get here for looking up results for functions other than this
989 // node however because those functions aren't going to be mutated by this
990 // pass.
991 FunctionAnalysisManager &FAM =
992 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG)
993 .getManager();
Haicheng Wu0812c5b2017-08-21 20:00:09 +0000994
995 // Get the remarks emission analysis for the caller.
996 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
997
Chandler Carruthb698d592017-01-22 10:34:01 +0000998 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
999 [&](Function &F) -> AssumptionCache & {
1000 return FAM.getResult<AssumptionAnalysis>(F);
1001 };
1002 auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
1003 return FAM.getResult<BlockFrequencyAnalysis>(F);
1004 };
1005
1006 auto GetInlineCost = [&](CallSite CS) {
1007 Function &Callee = *CS.getCalledFunction();
1008 auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
1009 return getInlineCost(CS, Params, CalleeTTI, GetAssumptionCache, {GetBFI},
Haicheng Wu0812c5b2017-08-21 20:00:09 +00001010 PSI, &ORE);
Chandler Carruthb698d592017-01-22 10:34:01 +00001011 };
1012
Chandler Carruth20e588e2017-03-09 11:35:40 +00001013 // Now process as many calls as we have within this caller in the sequnece.
1014 // We bail out as soon as the caller has to change so we can update the
1015 // call graph and prepare the context of that new caller.
Chandler Carruth1d963112016-12-20 03:15:32 +00001016 bool DidInline = false;
Chandler Carruth20e588e2017-03-09 11:35:40 +00001017 for (; i < (int)Calls.size() && Calls[i].first.getCaller() == &F; ++i) {
Chandler Carruth141bf5d2016-12-27 06:46:20 +00001018 int InlineHistoryID;
1019 CallSite CS;
Chandler Carruth20e588e2017-03-09 11:35:40 +00001020 std::tie(CS, InlineHistoryID) = Calls[i];
Chandler Carruth1d963112016-12-20 03:15:32 +00001021 Function &Callee = *CS.getCalledFunction();
1022
Chandler Carruth141bf5d2016-12-27 06:46:20 +00001023 if (InlineHistoryID != -1 &&
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001024 InlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) {
1025 setInlineRemark(CS, "recursive");
Chandler Carruth141bf5d2016-12-27 06:46:20 +00001026 continue;
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001027 }
Chandler Carruth141bf5d2016-12-27 06:46:20 +00001028
Chandler Carruth95055d82017-08-02 02:09:22 +00001029 // Check if this inlining may repeat breaking an SCC apart that has
1030 // already been split once before. In that case, inlining here may
1031 // trigger infinite inlining, much like is prevented within the inliner
1032 // itself by the InlineHistory above, but spread across CGSCC iterations
1033 // and thus hidden from the full inline history.
1034 if (CG.lookupSCC(*CG.lookup(Callee)) == C &&
1035 UR.InlinedInternalEdges.count({&N, C})) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001036 LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node "
1037 "previously split out of this SCC by inlining: "
1038 << F.getName() << " -> " << Callee.getName() << "\n");
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001039 setInlineRemark(CS, "recursive SCC split");
Chandler Carruth95055d82017-08-02 02:09:22 +00001040 continue;
1041 }
1042
Sam Elliotte604b562017-08-21 16:45:47 +00001043 Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE);
Chandler Carruth1d963112016-12-20 03:15:32 +00001044 // Check whether we want to inline this callsite.
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001045 if (!OIC.hasValue()) {
1046 setInlineRemark(CS, "deferred");
Chandler Carruth1d963112016-12-20 03:15:32 +00001047 continue;
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001048 }
1049
1050 if (!OIC.getValue()) {
1051 // shouldInline() call returned a negative inline cost that explains
1052 // why this callsite should not be inlined.
1053 setInlineRemark(CS, inlineCostStr(*OIC));
1054 continue;
1055 }
Chandler Carruth1d963112016-12-20 03:15:32 +00001056
Easwaran Raman12585b02017-01-20 22:44:04 +00001057 // Setup the data structure used to plumb customization into the
1058 // `InlineFunction` routine.
1059 InlineFunctionInfo IFI(
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001060 /*cg=*/nullptr, &GetAssumptionCache, PSI,
Easwaran Raman12585b02017-01-20 22:44:04 +00001061 &FAM.getResult<BlockFrequencyAnalysis>(*(CS.getCaller())),
1062 &FAM.getResult<BlockFrequencyAnalysis>(Callee));
1063
Sam Elliotte604b562017-08-21 16:45:47 +00001064 // Get DebugLoc to report. CS will be invalid after Inliner.
1065 DebugLoc DLoc = CS->getDebugLoc();
1066 BasicBlock *Block = CS.getParent();
1067
1068 using namespace ore;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001069
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001070 InlineResult IR = InlineFunction(CS, IFI);
1071 if (!IR) {
David Bolvanskyc1b27b52018-08-28 15:27:25 +00001072 setInlineRemark(CS, std::string(IR) + "; " + inlineCostStr(*OIC));
Vivek Pandya95906582017-10-11 17:12:59 +00001073 ORE.emit([&]() {
1074 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
1075 << NV("Callee", &Callee) << " will not be inlined into "
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001076 << NV("Caller", &F) << ": " << NV("Reason", IR.message);
Vivek Pandya95906582017-10-11 17:12:59 +00001077 });
Chandler Carruth1d963112016-12-20 03:15:32 +00001078 continue;
Sam Elliotte604b562017-08-21 16:45:47 +00001079 }
Chandler Carruth1d963112016-12-20 03:15:32 +00001080 DidInline = true;
1081 InlinedCallees.insert(&Callee);
1082
Fedor Sergeevb55705f2018-08-14 15:19:14 +00001083 ++NumInlined;
1084
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001085 emit_inlined_into(ORE, DLoc, Block, Callee, F, *OIC);
Sam Elliotte604b562017-08-21 16:45:47 +00001086
Chandler Carruth1d963112016-12-20 03:15:32 +00001087 // Add any new callsites to defined functions to the worklist.
Chandler Carruth141bf5d2016-12-27 06:46:20 +00001088 if (!IFI.InlinedCallSites.empty()) {
1089 int NewHistoryID = InlineHistory.size();
1090 InlineHistory.push_back({&Callee, InlineHistoryID});
1091 for (CallSite &CS : reverse(IFI.InlinedCallSites))
1092 if (Function *NewCallee = CS.getCalledFunction())
1093 if (!NewCallee->isDeclaration())
1094 Calls.push_back({CS, NewHistoryID});
1095 }
Chandler Carruth1d963112016-12-20 03:15:32 +00001096
Teresa Johnsone87868b2018-06-28 20:07:47 +00001097 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
1098 ImportedFunctionsStats->recordInline(F, Callee);
1099
Chandler Carruth03130d92016-12-27 03:39:54 +00001100 // Merge the attributes based on the inlining.
1101 AttributeFuncs::mergeAttributesForInlining(F, Callee);
1102
Chandler Carruth1d963112016-12-20 03:15:32 +00001103 // For local functions, check whether this makes the callee trivially
1104 // dead. In that case, we can drop the body of the function eagerly
1105 // which may reduce the number of callers of other functions to one,
1106 // changing inline cost thresholds.
1107 if (Callee.hasLocalLinkage()) {
1108 // To check this we also need to nuke any dead constant uses (perhaps
1109 // made dead by this operation on other functions).
1110 Callee.removeDeadConstantUsers();
Chandler Carruth06a86302017-07-19 04:12:25 +00001111 if (Callee.use_empty() && !CG.isLibFunction(Callee)) {
Chandler Carruth814e0df2017-03-16 10:45:42 +00001112 Calls.erase(
1113 std::remove_if(Calls.begin() + i + 1, Calls.end(),
1114 [&Callee](const std::pair<CallSite, int> &Call) {
1115 return Call.first.getCaller() == &Callee;
1116 }),
1117 Calls.end());
Chandler Carruth6acdca72017-01-24 12:55:57 +00001118 // Clear the body and queue the function itself for deletion when we
1119 // finish inlining and call graph updates.
Chandler Carruth1d963112016-12-20 03:15:32 +00001120 // Note that after this point, it is an error to do anything other
1121 // than use the callee's address or delete it.
1122 Callee.dropAllReferences();
1123 assert(find(DeadFunctions, &Callee) == DeadFunctions.end() &&
1124 "Cannot put cause a function to become dead twice!");
1125 DeadFunctions.push_back(&Callee);
1126 }
1127 }
1128 }
1129
Chandler Carruth20e588e2017-03-09 11:35:40 +00001130 // Back the call index up by one to put us in a good position to go around
1131 // the outer loop.
1132 --i;
1133
Chandler Carruth1d963112016-12-20 03:15:32 +00001134 if (!DidInline)
1135 continue;
1136 Changed = true;
1137
Chandler Carruth9900d182016-12-28 03:13:12 +00001138 // Add all the inlined callees' edges as ref edges to the caller. These are
1139 // by definition trivial edges as we always have *some* transitive ref edge
1140 // chain. While in some cases these edges are direct calls inside the
1141 // callee, they have to be modeled in the inliner as reference edges as
1142 // there may be a reference edge anywhere along the chain from the current
1143 // caller to the callee that causes the whole thing to appear like
1144 // a (transitive) reference edge that will require promotion to a call edge
1145 // below.
Chandler Carruth1d963112016-12-20 03:15:32 +00001146 for (Function *InlinedCallee : InlinedCallees) {
1147 LazyCallGraph::Node &CalleeN = *CG.lookup(*InlinedCallee);
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001148 for (LazyCallGraph::Edge &E : *CalleeN)
1149 RC->insertTrivialRefEdge(N, E.getNode());
Chandler Carruth1d963112016-12-20 03:15:32 +00001150 }
Chandler Carruth1d963112016-12-20 03:15:32 +00001151
1152 // At this point, since we have made changes we have at least removed
1153 // a call instruction. However, in the process we do some incremental
1154 // simplification of the surrounding code. This simplification can
1155 // essentially do all of the same things as a function pass and we can
1156 // re-use the exact same logic for updating the call graph to reflect the
Chandler Carruth95055d82017-08-02 02:09:22 +00001157 // change.
1158 LazyCallGraph::SCC *OldC = C;
Chandler Carruth1d963112016-12-20 03:15:32 +00001159 C = &updateCGAndAnalysisManagerForFunctionPass(CG, *C, N, AM, UR);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001160 LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n");
Chandler Carruth1d963112016-12-20 03:15:32 +00001161 RC = &C->getOuterRefSCC();
Chandler Carruth95055d82017-08-02 02:09:22 +00001162
1163 // If this causes an SCC to split apart into multiple smaller SCCs, there
1164 // is a subtle risk we need to prepare for. Other transformations may
1165 // expose an "infinite inlining" opportunity later, and because of the SCC
1166 // mutation, we will revisit this function and potentially re-inline. If we
1167 // do, and that re-inlining also has the potentially to mutate the SCC
1168 // structure, the infinite inlining problem can manifest through infinite
1169 // SCC splits and merges. To avoid this, we capture the originating caller
1170 // node and the SCC containing the call edge. This is a slight over
1171 // approximation of the possible inlining decisions that must be avoided,
Wei Mi80a0c972018-10-23 23:29:45 +00001172 // but is relatively efficient to store. We use C != OldC to know when
1173 // a new SCC is generated and the original SCC may be generated via merge
1174 // in later iterations.
1175 //
1176 // It is also possible that even if no new SCC is generated
1177 // (i.e., C == OldC), the original SCC could be split and then merged
1178 // into the same one as itself. and the original SCC will be added into
1179 // UR.CWorklist again, we want to catch such cases too.
1180 //
Chandler Carruth95055d82017-08-02 02:09:22 +00001181 // FIXME: This seems like a very heavyweight way of retaining the inline
1182 // history, we should look for a more efficient way of tracking it.
Wei Mi80a0c972018-10-23 23:29:45 +00001183 if ((C != OldC || UR.CWorklist.count(OldC)) &&
1184 llvm::any_of(InlinedCallees, [&](Function *Callee) {
Chandler Carruth95055d82017-08-02 02:09:22 +00001185 return CG.lookupSCC(*CG.lookup(*Callee)) == OldC;
1186 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001187 LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, "
1188 "retaining this to avoid infinite inlining.\n");
Chandler Carruth95055d82017-08-02 02:09:22 +00001189 UR.InlinedInternalEdges.insert({&N, OldC});
1190 }
1191 InlinedCallees.clear();
Chandler Carruth20e588e2017-03-09 11:35:40 +00001192 }
Chandler Carruth1d963112016-12-20 03:15:32 +00001193
1194 // Now that we've finished inlining all of the calls across this SCC, delete
1195 // all of the trivially dead functions, updating the call graph and the CGSCC
1196 // pass manager in the process.
1197 //
1198 // Note that this walks a pointer set which has non-deterministic order but
1199 // that is OK as all we do is delete things and add pointers to unordered
1200 // sets.
1201 for (Function *DeadF : DeadFunctions) {
1202 // Get the necessary information out of the call graph and nuke the
Chandler Carruth6acdca72017-01-24 12:55:57 +00001203 // function there. Also, cclear out any cached analyses.
Chandler Carruth1d963112016-12-20 03:15:32 +00001204 auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));
Chandler Carruth6acdca72017-01-24 12:55:57 +00001205 FunctionAnalysisManager &FAM =
1206 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(DeadC, CG)
1207 .getManager();
Sanjoy Dasdef17292017-09-28 02:45:42 +00001208 FAM.clear(*DeadF, DeadF->getName());
1209 AM.clear(DeadC, DeadC.getName());
Chandler Carruth1d963112016-12-20 03:15:32 +00001210 auto &DeadRC = DeadC.getOuterRefSCC();
1211 CG.removeDeadFunction(*DeadF);
1212
1213 // Mark the relevant parts of the call graph as invalid so we don't visit
1214 // them.
1215 UR.InvalidatedSCCs.insert(&DeadC);
1216 UR.InvalidatedRefSCCs.insert(&DeadRC);
1217
1218 // And delete the actual function from the module.
1219 M.getFunctionList().erase(DeadF);
Fedor Sergeevb55705f2018-08-14 15:19:14 +00001220 ++NumDeleted;
Chandler Carruth1d963112016-12-20 03:15:32 +00001221 }
Chandler Carruthbd9c2902017-07-09 03:59:31 +00001222
1223 if (!Changed)
1224 return PreservedAnalyses::all();
1225
1226 // Even if we change the IR, we update the core CGSCC data structures and so
1227 // can preserve the proxy to the function analysis manager.
1228 PreservedAnalyses PA;
1229 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1230 return PA;
Chandler Carruth1d963112016-12-20 03:15:32 +00001231}