LLVM 24.0.0git
InlineCost.cpp
Go to the documentation of this file.
1//===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
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 inline cost analysis.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
33#include "llvm/Config/llvm-config.h"
35#include "llvm/IR/CallingConv.h"
36#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/GlobalAlias.h"
39#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/InstVisitor.h"
42#include "llvm/IR/Operator.h"
45#include "llvm/Support/Debug.h"
48#include <climits>
49#include <limits>
50#include <optional>
51
52using namespace llvm;
53
54#define DEBUG_TYPE "inline-cost"
55
56STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
57
58static cl::opt<int>
59 DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
60 cl::desc("Default amount of inlining to perform"));
61
62// We introduce this option since there is a minor compile-time win by avoiding
63// addition of TTI attributes (target-features in particular) to inline
64// candidates when they are guaranteed to be the same as top level methods in
65// some use cases. If we avoid adding the attribute, we need an option to avoid
66// checking these attributes.
68 "ignore-tti-inline-compatible", cl::Hidden, cl::init(false),
69 cl::desc("Ignore TTI attributes compatibility check between callee/caller "
70 "during inline cost calculation"));
71
73 "print-instruction-comments", cl::Hidden, cl::init(false),
74 cl::desc("Prints comments for instruction based on inline cost analysis"));
75
77 "inline-threshold", cl::Hidden, cl::init(225),
78 cl::desc("Control the amount of inlining to perform (default = 225)"));
79
81 "inlinehint-threshold", cl::Hidden, cl::init(325),
82 cl::desc("Threshold for inlining functions with inline hint"));
83
84static cl::opt<int>
85 ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
86 cl::init(45),
87 cl::desc("Threshold for inlining cold callsites"));
88
90 "inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false),
91 cl::desc("Enable the cost-benefit analysis for the inliner"));
92
93// InlineSavingsMultiplier overrides per TTI multipliers iff it is
94// specified explicitly in command line options. This option is exposed
95// for tuning and testing.
97 "inline-savings-multiplier", cl::Hidden, cl::init(8),
98 cl::desc("Multiplier to multiply cycle savings by during inlining"));
99
100// InlineSavingsProfitableMultiplier overrides per TTI multipliers iff it is
101// specified explicitly in command line options. This option is exposed
102// for tuning and testing.
104 "inline-savings-profitable-multiplier", cl::Hidden, cl::init(4),
105 cl::desc("A multiplier on top of cycle savings to decide whether the "
106 "savings won't justify the cost"));
107
108static cl::opt<int>
109 InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100),
110 cl::desc("The maximum size of a callee that get's "
111 "inlined without sufficient cycle savings"));
112
113// We introduce this threshold to help performance of instrumentation based
114// PGO before we actually hook up inliner with analysis passes such as BPI and
115// BFI.
117 "inlinecold-threshold", cl::Hidden, cl::init(45),
118 cl::desc("Threshold for inlining functions with cold attribute"));
119
120static cl::opt<int>
121 HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
122 cl::desc("Threshold for hot callsites "));
123
125 "locally-hot-callsite-threshold", cl::Hidden, cl::init(525),
126 cl::desc("Threshold for locally hot callsites "));
127
129 "cold-callsite-rel-freq", cl::Hidden, cl::init(2),
130 cl::desc("Maximum block frequency, expressed as a percentage of caller's "
131 "entry frequency, for a callsite to be cold in the absence of "
132 "profile information."));
133
135 "hot-callsite-rel-freq", cl::Hidden, cl::init(60),
136 cl::desc("Minimum block frequency, expressed as a multiple of caller's "
137 "entry frequency, for a callsite to be hot in the absence of "
138 "profile information."));
139
140static cl::opt<int>
141 InstrCost("inline-instr-cost", cl::Hidden, cl::init(5),
142 cl::desc("Cost of a single instruction when inlining"));
143
145 "inline-asm-instr-cost", cl::Hidden, cl::init(0),
146 cl::desc("Cost of a single inline asm instruction when inlining"));
147
148static cl::opt<int>
149 MemAccessCost("inline-memaccess-cost", cl::Hidden, cl::init(0),
150 cl::desc("Cost of load/store instruction when inlining"));
151
153 "inline-call-penalty", cl::Hidden, cl::init(25),
154 cl::desc("Call penalty that is applied per callsite when inlining"));
155
156static cl::opt<size_t>
157 StackSizeThreshold("inline-max-stacksize", cl::Hidden,
158 cl::init(std::numeric_limits<size_t>::max()),
159 cl::desc("Do not inline functions with a stack size "
160 "that exceeds the specified limit"));
161
163 "recursive-inline-max-stacksize", cl::Hidden,
165 cl::desc("Do not inline recursive functions with a stack "
166 "size that exceeds the specified limit"));
167
169 "inline-cost-full", cl::Hidden,
170 cl::desc("Compute the full inline cost of a call site even when the cost "
171 "exceeds the threshold."));
172
174 "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
175 cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
176 "attributes."));
177
179 "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
180 cl::desc("Disables evaluation of GetElementPtr with constant operands"));
181
183 "inline-all-viable-calls", cl::Hidden, cl::init(false),
184 cl::desc("Inline all viable calls, even if they exceed the inlining "
185 "threshold"));
186namespace llvm {
187std::optional<int> getStringFnAttrAsInt(const Attribute &Attr) {
188 if (Attr.isValid()) {
189 int AttrValue = 0;
190 if (!Attr.getValueAsString().getAsInteger(10, AttrValue))
191 return AttrValue;
192 }
193 return std::nullopt;
194}
195
196std::optional<int> getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind) {
197 return getStringFnAttrAsInt(CB.getFnAttr(AttrKind));
198}
199
200std::optional<int> getStringFnAttrAsInt(Function *F, StringRef AttrKind) {
201 return getStringFnAttrAsInt(F->getFnAttribute(AttrKind));
202}
203
204namespace InlineConstants {
205int getInstrCost() { return InstrCost; }
206
207} // namespace InlineConstants
208
209} // namespace llvm
210
211namespace {
212class InlineCostCallAnalyzer;
213
214// This struct is used to store information about inline cost of a
215// particular instruction
216struct InstructionCostDetail {
217 int CostBefore = 0;
218 int CostAfter = 0;
219 int ThresholdBefore = 0;
220 int ThresholdAfter = 0;
221
222 int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
223
224 int getCostDelta() const { return CostAfter - CostBefore; }
225
226 bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
227};
228
229class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
230private:
231 InlineCostCallAnalyzer *const ICCA;
232
233public:
234 InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
235 void emitInstructionAnnot(const Instruction *I,
236 formatted_raw_ostream &OS) override;
237};
238
239/// Carry out call site analysis, in order to evaluate inlinability.
240/// NOTE: the type is currently used as implementation detail of functions such
241/// as llvm::getInlineCost. Note the function_ref constructor parameters - the
242/// expectation is that they come from the outer scope, from the wrapper
243/// functions. If we want to support constructing CallAnalyzer objects where
244/// lambdas are provided inline at construction, or where the object needs to
245/// otherwise survive past the scope of the provided functions, we need to
246/// revisit the argument types.
247class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
248 typedef InstVisitor<CallAnalyzer, bool> Base;
249 friend class InstVisitor<CallAnalyzer, bool>;
250
251protected:
252 virtual ~CallAnalyzer() = default;
253 /// The TargetTransformInfo available for this compilation.
254 const TargetTransformInfo &TTI;
255
256 /// Getter for the cache of @llvm.assume intrinsics.
257 function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
258
259 /// Getter for BlockFrequencyInfo
260 function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
261
262 /// Getter for TargetLibraryInfo
263 function_ref<const TargetLibraryInfo &(Function &)> GetTLI;
264
265 /// Profile summary information.
266 ProfileSummaryInfo *PSI;
267
268 /// The called function.
269 Function &F;
270
271 // Cache the DataLayout since we use it a lot.
272 const DataLayout &DL;
273
274 /// The OptimizationRemarkEmitter available for this compilation.
275 OptimizationRemarkEmitter *ORE;
276
277 /// The candidate callsite being analyzed. Please do not use this to do
278 /// analysis in the caller function; we want the inline cost query to be
279 /// easily cacheable. Instead, use the cover function paramHasAttr.
280 CallBase &CandidateCall;
281
282 /// Getter for the cache of ephemeral values.
283 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache = nullptr;
284
285 /// Extension points for handling callsite features.
286 // Called before a basic block was analyzed.
287 virtual void onBlockStart(const BasicBlock *BB) {}
288
289 /// Called after a basic block was analyzed.
290 virtual void onBlockAnalyzed(const BasicBlock *BB) {}
291
292 /// Called before an instruction was analyzed
293 virtual void onInstructionAnalysisStart(const Instruction *I) {}
294
295 /// Called after an instruction was analyzed
296 virtual void onInstructionAnalysisFinish(const Instruction *I) {}
297
298 /// Called at the end of the analysis of the callsite. Return the outcome of
299 /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
300 /// the reason it can't.
301 virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
302 /// Called when we're about to start processing a basic block, and every time
303 /// we are done processing an instruction. Return true if there is no point in
304 /// continuing the analysis (e.g. we've determined already the call site is
305 /// too expensive to inline)
306 virtual bool shouldStop() { return false; }
307
308 /// Called before the analysis of the callee body starts (with callsite
309 /// contexts propagated). It checks callsite-specific information. Return a
310 /// reason analysis can't continue if that's the case, or 'true' if it may
311 /// continue.
312 virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
313 /// Called if the analysis engine decides SROA cannot be done for the given
314 /// alloca.
315 virtual void onDisableSROA(AllocaInst *Arg) {}
316
317 /// Called the analysis engine determines load elimination won't happen.
318 virtual void onDisableLoadElimination() {}
319
320 /// Called when we visit a CallBase, before the analysis starts. Return false
321 /// to stop further processing of the instruction.
322 virtual bool onCallBaseVisitStart(CallBase &Call) { return true; }
323
324 /// Called to account for a call.
325 virtual void onCallPenalty() {}
326
327 /// Called to account for a load or store.
328 virtual void onMemAccess(){};
329
330 /// Called to account for the expectation the inlining would result in a load
331 /// elimination.
332 virtual void onLoadEliminationOpportunity() {}
333
334 /// Called to account for the cost of argument setup for the Call in the
335 /// callee's body (not the callsite currently under analysis).
336 virtual void onCallArgumentSetup(const CallBase &Call) {}
337
338 /// Called to account for a load relative intrinsic.
339 virtual void onLoadRelativeIntrinsic() {}
340
341 /// Called to account for a lowered call.
342 virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
343 }
344
345 /// Account for a jump table of given size. Return false to stop further
346 /// processing the switch instruction
347 virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
348
349 /// Account for a case cluster of given size. Return false to stop further
350 /// processing of the instruction.
351 virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
352
353 /// Called at the end of processing a switch instruction, with the given
354 /// number of case clusters.
355 virtual void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
356 bool DefaultDestUnreachable) {}
357
358 /// Called to account for any other instruction not specifically accounted
359 /// for.
360 virtual void onMissedSimplification() {}
361
362 /// Account for inline assembly instructions.
363 virtual void onInlineAsm(const InlineAsm &Arg) {}
364
365 /// Start accounting potential benefits due to SROA for the given alloca.
366 virtual void onInitializeSROAArg(AllocaInst *Arg) {}
367
368 /// Account SROA savings for the AllocaInst value.
369 virtual void onAggregateSROAUse(AllocaInst *V) {}
370
371 bool handleSROA(Value *V, bool DoNotDisable) {
372 // Check for SROA candidates in comparisons.
373 if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
374 if (DoNotDisable) {
375 onAggregateSROAUse(SROAArg);
376 return true;
377 }
378 disableSROAForArg(SROAArg);
379 }
380 return false;
381 }
382
383 bool IsCallerRecursive = false;
384 bool IsRecursiveCall = false;
385 bool ExposesReturnsTwice = false;
386 bool HasDynamicAlloca = false;
387 bool ContainsNoDuplicateCall = false;
388 bool HasReturn = false;
389 bool HasIndirectBr = false;
390 bool HasUninlineableIntrinsic = false;
391 bool InitsVargArgs = false;
392
393 /// Number of bytes allocated statically by the callee.
394 uint64_t AllocatedSize = 0;
395 unsigned NumInstructions = 0;
396 unsigned NumInlineAsmInstructions = 0;
397 unsigned NumVectorInstructions = 0;
398
399 /// While we walk the potentially-inlined instructions, we build up and
400 /// maintain a mapping of simplified values specific to this callsite. The
401 /// idea is to propagate any special information we have about arguments to
402 /// this call through the inlinable section of the function, and account for
403 /// likely simplifications post-inlining. The most important aspect we track
404 /// is CFG altering simplifications -- when we prove a basic block dead, that
405 /// can cause dramatic shifts in the cost of inlining a function.
406 /// Note: The simplified Value may be owned by the caller function.
407 DenseMap<Value *, Value *> SimplifiedValues;
408
409 /// Keep track of the values which map back (through function arguments) to
410 /// allocas on the caller stack which could be simplified through SROA.
411 DenseMap<Value *, AllocaInst *> SROAArgValues;
412
413 /// Keep track of Allocas for which we believe we may get SROA optimization.
414 DenseSet<AllocaInst *> EnabledSROAAllocas;
415
416 /// Keep track of values which map to a pointer base and constant offset.
417 DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
418
419 /// Keep track of dead blocks due to the constant arguments.
420 SmallPtrSet<BasicBlock *, 16> DeadBlocks;
421
422 /// The mapping of the blocks to their known unique successors due to the
423 /// constant arguments.
424 DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
425
426 /// Model the elimination of repeated loads that is expected to happen
427 /// whenever we simplify away the stores that would otherwise cause them to be
428 /// loads.
429 bool EnableLoadElimination = true;
430
431 /// Whether we allow inlining for recursive call.
432 bool AllowRecursiveCall = false;
433
434 SmallPtrSet<Value *, 16> LoadAddrSet;
435
436 AllocaInst *getSROAArgForValueOrNull(Value *V) const {
437 auto It = SROAArgValues.find(V);
438 if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
439 return nullptr;
440 return It->second;
441 }
442
443 /// Use a value in its given form directly if possible, otherwise try looking
444 /// for it in SimplifiedValues.
445 template <typename T> T *getDirectOrSimplifiedValue(Value *V) const {
446 if (auto *Direct = dyn_cast<T>(V))
447 return Direct;
448 return getSimplifiedValue<T>(V);
449 }
450
451 // Custom simplification helper routines.
452 bool isAllocaDerivedArg(Value *V);
453 void disableSROAForArg(AllocaInst *SROAArg);
454 void disableSROA(Value *V);
455 void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
456 void disableLoadElimination();
457 bool isGEPFree(GetElementPtrInst &GEP);
458 bool canFoldInboundsGEP(GetElementPtrInst &I);
459 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
460 bool simplifyCallSite(Function *F, CallBase &Call);
461 bool simplifyCmpInstForRecCall(CmpInst &Cmp);
462 bool simplifyInstruction(Instruction &I);
463 bool simplifyIntrinsicCallIsConstant(CallBase &CB);
464 bool simplifyIntrinsicCallObjectSize(CallBase &CB);
465 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
466 bool isLoweredToCall(Function *F, CallBase &Call);
467
468 /// Return true if the given argument to the function being considered for
469 /// inlining has the given attribute set either at the call site or the
470 /// function declaration. Primarily used to inspect call site specific
471 /// attributes since these can be more precise than the ones on the callee
472 /// itself.
473 bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
474
475 /// Return true if the given value is known non null within the callee if
476 /// inlined through this particular callsite.
477 bool isKnownNonNullInCallee(Value *V);
478
479 /// Return true if size growth is allowed when inlining the callee at \p Call.
480 bool allowSizeGrowth(CallBase &Call);
481
482 // Custom analysis routines.
483 InlineResult analyzeBlock(BasicBlock *BB,
484 const SmallPtrSetImpl<const Value *> &EphValues);
485
486 // Disable several entry points to the visitor so we don't accidentally use
487 // them by declaring but not defining them here.
488 void visit(Module *);
489 void visit(Module &);
490 void visit(Function *);
491 void visit(Function &);
492 void visit(BasicBlock *);
493 void visit(BasicBlock &);
494
495 // Provide base case for our instruction visit.
496 bool visitInstruction(Instruction &I);
497
498 // Our visit overrides.
499 bool visitAlloca(AllocaInst &I);
500 bool visitPHI(PHINode &I);
501 bool visitGetElementPtr(GetElementPtrInst &I);
502 bool visitBitCast(BitCastInst &I);
503 bool visitPtrToInt(PtrToIntInst &I);
504 bool visitIntToPtr(IntToPtrInst &I);
505 bool visitCastInst(CastInst &I);
506 bool visitCmpInst(CmpInst &I);
507 bool visitSub(BinaryOperator &I);
508 bool visitBinaryOperator(BinaryOperator &I);
509 bool visitFNeg(UnaryOperator &I);
510 bool visitLoad(LoadInst &I);
511 bool visitStore(StoreInst &I);
512 bool visitExtractValue(ExtractValueInst &I);
513 bool visitInsertValue(InsertValueInst &I);
514 bool visitCallBase(CallBase &Call);
515 bool visitReturnInst(ReturnInst &RI);
516 bool visitUncondBrInst(UncondBrInst &BI);
517 bool visitCondBrInst(CondBrInst &BI);
518 bool visitSelectInst(SelectInst &SI);
519 bool visitSwitchInst(SwitchInst &SI);
520 bool visitIndirectBrInst(IndirectBrInst &IBI);
521 bool visitResumeInst(ResumeInst &RI);
522 bool visitCleanupReturnInst(CleanupReturnInst &RI);
523 bool visitCatchReturnInst(CatchReturnInst &RI);
524 bool visitUnreachableInst(UnreachableInst &I);
525
526public:
527 CallAnalyzer(
528 Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
529 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
530 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
531 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
532 ProfileSummaryInfo *PSI = nullptr,
533 OptimizationRemarkEmitter *ORE = nullptr,
534 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
535 nullptr)
536 : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
537 GetTLI(GetTLI), PSI(PSI), F(Callee), DL(F.getDataLayout()), ORE(ORE),
538 CandidateCall(Call), GetEphValuesCache(GetEphValuesCache) {}
539
540 InlineResult analyze();
541
542 /// Lookup simplified Value. May return a value owned by the caller.
543 Value *getSimplifiedValueUnchecked(Value *V) const {
544 return SimplifiedValues.lookup(V);
545 }
546
547 /// Lookup simplified Value, but return nullptr if the simplified value is
548 /// owned by the caller.
549 template <typename T> T *getSimplifiedValue(Value *V) const {
550 Value *SimpleV = SimplifiedValues.lookup(V);
551 if (!SimpleV)
552 return nullptr;
553
554 // Skip checks if we know T is a global. This has a small, but measurable
555 // impact on compile-time.
556 if constexpr (std::is_base_of_v<Constant, T>)
557 return dyn_cast<T>(SimpleV);
558
559 // Make sure the simplified Value is owned by this function
560 if (auto *I = dyn_cast<Instruction>(SimpleV)) {
561 if (I->getFunction() != &F)
562 return nullptr;
563 } else if (auto *Arg = dyn_cast<Argument>(SimpleV)) {
564 if (Arg->getParent() != &F)
565 return nullptr;
566 } else if (!isa<Constant>(SimpleV))
567 return nullptr;
568 return dyn_cast<T>(SimpleV);
569 }
570
571 // Keep a bunch of stats about the cost savings found so we can print them
572 // out when debugging.
573 unsigned NumConstantArgs = 0;
574 unsigned NumConstantOffsetPtrArgs = 0;
575 unsigned NumAllocaArgs = 0;
576 unsigned NumConstantPtrCmps = 0;
577 unsigned NumConstantPtrDiffs = 0;
578 unsigned NumInstructionsSimplified = 0;
579
580 void dump();
581};
582
583// Considering forming a binary search, we should find the number of nodes
584// which is same as the number of comparisons when lowered. For a given
585// number of clusters, n, we can define a recursive function, f(n), to find
586// the number of nodes in the tree. The recursion is :
587// f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
588// and f(n) = n, when n <= 3.
589// This will lead a binary tree where the leaf should be either f(2) or f(3)
590// when n > 3. So, the number of comparisons from leaves should be n, while
591// the number of non-leaf should be :
592// 2^(log2(n) - 1) - 1
593// = 2^log2(n) * 2^-1 - 1
594// = n / 2 - 1.
595// Considering comparisons from leaf and non-leaf nodes, we can estimate the
596// number of comparisons in a simple closed form :
597// n + n / 2 - 1 = n * 3 / 2 - 1
598int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
599 return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
600}
601
602/// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
603/// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
604class InlineCostCallAnalyzer final : public CallAnalyzer {
605 const bool ComputeFullInlineCost;
606 int LoadEliminationCost = 0;
607 /// Bonus to be applied when percentage of vector instructions in callee is
608 /// high (see more details in updateThreshold).
609 int VectorBonus = 0;
610 /// Bonus to be applied when the callee has only one reachable basic block.
611 int SingleBBBonus = 0;
612
613 /// Tunable parameters that control the analysis.
614 const InlineParams &Params;
615
616 // This DenseMap stores the delta change in cost and threshold after
617 // accounting for the given instruction. The map is filled only with the
618 // flag PrintInstructionComments on.
619 DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
620
621 /// Upper bound for the inlining cost. Bonuses are being applied to account
622 /// for speculative "expected profit" of the inlining decision.
623 int Threshold = 0;
624
625 /// The amount of StaticBonus applied.
626 int StaticBonusApplied = 0;
627
628 /// Attempt to evaluate indirect calls to boost its inline cost.
629 const bool BoostIndirectCalls;
630
631 /// Ignore the threshold when finalizing analysis.
632 const bool IgnoreThreshold;
633
634 // True if the cost-benefit-analysis-based inliner is enabled.
635 const bool CostBenefitAnalysisEnabled;
636
637 /// Inlining cost measured in abstract units, accounts for all the
638 /// instructions expected to be executed for a given function invocation.
639 /// Instructions that are statically proven to be dead based on call-site
640 /// arguments are not counted here.
641 int Cost = 0;
642
643 // The cumulative cost at the beginning of the basic block being analyzed. At
644 // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
645 // the size of that basic block.
646 int CostAtBBStart = 0;
647
648 // The static size of live but cold basic blocks. This is "static" in the
649 // sense that it's not weighted by profile counts at all.
650 int ColdSize = 0;
651
652 // Whether inlining is decided by cost-threshold analysis.
653 bool DecidedByCostThreshold = false;
654
655 // Whether inlining is decided by cost-benefit analysis.
656 bool DecidedByCostBenefit = false;
657
658 // The cost-benefit pair computed by cost-benefit analysis.
659 std::optional<CostBenefitPair> CostBenefit;
660
661 bool SingleBB = true;
662
663 unsigned SROACostSavings = 0;
664 unsigned SROACostSavingsLost = 0;
665
666 /// The mapping of caller Alloca values to their accumulated cost savings. If
667 /// we have to disable SROA for one of the allocas, this tells us how much
668 /// cost must be added.
669 DenseMap<AllocaInst *, int> SROAArgCosts;
670
671 /// Return true if \p Call is a cold callsite.
672 bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
673
674 /// Update Threshold based on callsite properties such as callee
675 /// attributes and callee hotness for PGO builds. The Callee is explicitly
676 /// passed to support analyzing indirect calls whose target is inferred by
677 /// analysis.
678 void updateThreshold(CallBase &Call, Function &Callee);
679 /// Return a higher threshold if \p Call is a hot callsite.
680 std::optional<int> getHotCallSiteThreshold(CallBase &Call,
681 BlockFrequencyInfo *CallerBFI);
682
683 /// Handle a capped 'int' increment for Cost.
684 void addCost(int64_t Inc) {
685 Inc = std::clamp<int64_t>(Inc, INT_MIN, INT_MAX);
686 Cost = std::clamp<int64_t>(Inc + Cost, INT_MIN, INT_MAX);
687 }
688
689 void onDisableSROA(AllocaInst *Arg) override {
690 auto CostIt = SROAArgCosts.find(Arg);
691 if (CostIt == SROAArgCosts.end())
692 return;
693 addCost(CostIt->second);
694 SROACostSavings -= CostIt->second;
695 SROACostSavingsLost += CostIt->second;
696 SROAArgCosts.erase(CostIt);
697 }
698
699 void onDisableLoadElimination() override {
700 addCost(LoadEliminationCost);
701 LoadEliminationCost = 0;
702 }
703
704 bool onCallBaseVisitStart(CallBase &Call) override {
705 if (std::optional<int> AttrCallThresholdBonus =
706 getStringFnAttrAsInt(Call, "call-threshold-bonus"))
707 Threshold += *AttrCallThresholdBonus;
708
709 if (std::optional<int> AttrCallCost =
710 getStringFnAttrAsInt(Call, "call-inline-cost")) {
711 addCost(*AttrCallCost);
712 // Prevent further processing of the call since we want to override its
713 // inline cost, not just add to it.
714 return false;
715 }
716 return true;
717 }
718
719 void onCallPenalty() override { addCost(CallPenalty); }
720
721 void onMemAccess() override { addCost(MemAccessCost); }
722
723 void onCallArgumentSetup(const CallBase &Call) override {
724 // Pay the price of the argument setup. We account for the average 1
725 // instruction per call argument setup here.
726 addCost(Call.arg_size() * InstrCost);
727 }
728 void onLoadRelativeIntrinsic() override {
729 // This is normally lowered to 4 LLVM instructions.
730 addCost(3 * InstrCost);
731 }
732 void onLoweredCall(Function *F, CallBase &Call,
733 bool IsIndirectCall) override {
734 // We account for the average 1 instruction per call argument setup here.
735 addCost(Call.arg_size() * InstrCost);
736
737 // If we have a constant that we are calling as a function, we can peer
738 // through it and see the function target. This happens not infrequently
739 // during devirtualization and so we want to give it a hefty bonus for
740 // inlining, but cap that bonus in the event that inlining wouldn't pan out.
741 // Pretend to inline the function, with a custom threshold.
742 if (IsIndirectCall && BoostIndirectCalls) {
743 auto IndirectCallParams = Params;
744 IndirectCallParams.DefaultThreshold =
746 /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
747 /// to instantiate the derived class.
748 InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
749 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
750 false);
751 if (CA.analyze().isSuccess()) {
752 // We were able to inline the indirect call! Subtract the cost from the
753 // threshold to get the bonus we want to apply, but don't go below zero.
754 addCost(-std::max(0, CA.getThreshold() - CA.getCost()));
755 }
756 } else
757 // Otherwise simply add the cost for merely making the call.
758 addCost(TTI.getInlineCallPenalty(CandidateCall.getCaller(), Call,
759 CallPenalty));
760 }
761
762 void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
763 bool DefaultDestUnreachable) override {
764 // If suitable for a jump table, consider the cost for the table size and
765 // branch to destination.
766 // Maximum valid cost increased in this function.
767 if (JumpTableSize) {
768 // Suppose a default branch includes one compare and one conditional
769 // branch if it's reachable.
770 if (!DefaultDestUnreachable)
771 addCost(2 * InstrCost);
772 // Suppose a jump table requires one load and one jump instruction.
773 int64_t JTCost =
774 static_cast<int64_t>(JumpTableSize) * InstrCost + 2 * InstrCost;
775 addCost(JTCost);
776 return;
777 }
778
779 if (NumCaseCluster <= 3) {
780 // Suppose a comparison includes one compare and one conditional branch.
781 // We can reduce a set of instructions if the default branch is
782 // undefined.
783 addCost((NumCaseCluster - DefaultDestUnreachable) * 2 * InstrCost);
784 return;
785 }
786
787 int64_t ExpectedNumberOfCompare =
788 getExpectedNumberOfCompare(NumCaseCluster);
789 int64_t SwitchCost = ExpectedNumberOfCompare * 2 * InstrCost;
790
791 addCost(SwitchCost);
792 }
793
794 // Parses the inline assembly argument to account for its cost. Inline
795 // assembly instructions incur higher costs for inlining since they cannot be
796 // analyzed and optimized.
797 void onInlineAsm(const InlineAsm &Arg) override {
799 return;
801 Arg.collectAsmStrs(AsmStrs);
802 int SectionLevel = 0;
803 int InlineAsmInstrCount = 0;
804 for (StringRef AsmStr : AsmStrs) {
805 // Trim whitespaces and comments.
806 StringRef Trimmed = AsmStr.trim();
807 size_t hashPos = Trimmed.find('#');
808 if (hashPos != StringRef::npos)
809 Trimmed = Trimmed.substr(0, hashPos);
810 // Ignore comments.
811 if (Trimmed.empty())
812 continue;
813 // Filter out the outlined assembly instructions from the cost by keeping
814 // track of the section level and only accounting for instrutions at
815 // section level of zero. Note there will be duplication in outlined
816 // sections too, but is not accounted in the inlining cost model.
817 if (Trimmed.starts_with(".pushsection")) {
818 ++SectionLevel;
819 continue;
820 }
821 if (Trimmed.starts_with(".popsection")) {
822 --SectionLevel;
823 continue;
824 }
825 // Ignore directives and labels.
826 if (Trimmed.starts_with(".") || Trimmed.contains(":"))
827 continue;
828 if (SectionLevel == 0)
829 ++InlineAsmInstrCount;
830 }
831 NumInlineAsmInstructions += InlineAsmInstrCount;
832 addCost(InlineAsmInstrCount * InlineAsmInstrCost);
833 }
834
835 void onMissedSimplification() override { addCost(InstrCost); }
836
837 void onInitializeSROAArg(AllocaInst *Arg) override {
838 assert(Arg != nullptr &&
839 "Should not initialize SROA costs for null value.");
840 auto SROAArgCost = TTI.getCallerAllocaCost(&CandidateCall, Arg);
841 SROACostSavings += SROAArgCost;
842 SROAArgCosts[Arg] = SROAArgCost;
843 }
844
845 void onAggregateSROAUse(AllocaInst *SROAArg) override {
846 auto CostIt = SROAArgCosts.find(SROAArg);
847 assert(CostIt != SROAArgCosts.end() &&
848 "expected this argument to have a cost");
849 CostIt->second += InstrCost;
850 SROACostSavings += InstrCost;
851 }
852
853 void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
854
855 void onBlockAnalyzed(const BasicBlock *BB) override {
856 if (CostBenefitAnalysisEnabled) {
857 // Keep track of the static size of live but cold basic blocks. For now,
858 // we define a cold basic block to be one that's never executed.
859 assert(GetBFI && "GetBFI must be available");
860 BlockFrequencyInfo *BFI = &(GetBFI(F));
861 assert(BFI && "BFI must be available");
862 auto ProfileCount = BFI->getBlockProfileCount(BB);
863 if (*ProfileCount == 0)
864 ColdSize += Cost - CostAtBBStart;
865 }
866
867 auto *TI = BB->getTerminator();
868 // If we had any successors at this point, than post-inlining is likely to
869 // have them as well. Note that we assume any basic blocks which existed
870 // due to branches or switches which folded above will also fold after
871 // inlining.
872 if (SingleBB && TI->getNumSuccessors() > 1) {
873 // Take off the bonus we applied to the threshold.
874 Threshold -= SingleBBBonus;
875 SingleBB = false;
876 }
877 }
878
879 void onInstructionAnalysisStart(const Instruction *I) override {
880 // This function is called to store the initial cost of inlining before
881 // the given instruction was assessed.
883 return;
884 auto &CostDetail = InstructionCostDetailMap[I];
885 CostDetail.CostBefore = Cost;
886 CostDetail.ThresholdBefore = Threshold;
887 }
888
889 void onInstructionAnalysisFinish(const Instruction *I) override {
890 // This function is called to find new values of cost and threshold after
891 // the instruction has been assessed.
893 return;
894 auto &CostDetail = InstructionCostDetailMap[I];
895 CostDetail.CostAfter = Cost;
896 CostDetail.ThresholdAfter = Threshold;
897 }
898
899 bool isCostBenefitAnalysisEnabled() {
900 if (!PSI || !PSI->hasProfileSummary())
901 return false;
902
903 if (!GetBFI)
904 return false;
905
907 // Honor the explicit request from the user.
909 return false;
910 } else {
911 // Otherwise, require instrumentation profile.
912 if (!PSI->hasInstrumentationProfile())
913 return false;
914 }
915
916 auto *Caller = CandidateCall.getParent()->getParent();
917 if (!Caller->getEntryCount())
918 return false;
919
920 BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
921 if (!CallerBFI)
922 return false;
923
924 // For now, limit to hot call site.
925 if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
926 return false;
927
928 // Make sure we have a nonzero entry count.
929 auto EntryCount = F.getEntryCount();
930 if (!EntryCount || *EntryCount == 0)
931 return false;
932
933 BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
934 if (!CalleeBFI)
935 return false;
936
937 return true;
938 }
939
940 // A helper function to choose between command line override and default.
941 unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const {
942 if (InlineSavingsMultiplier.getNumOccurrences())
945 }
946
947 // A helper function to choose between command line override and default.
948 unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const {
949 if (InlineSavingsProfitableMultiplier.getNumOccurrences())
952 }
953
954 void OverrideCycleSavingsAndSizeForTesting(APInt &CycleSavings, int &Size) {
955 if (std::optional<int> AttrCycleSavings = getStringFnAttrAsInt(
956 CandidateCall, "inline-cycle-savings-for-test")) {
957 CycleSavings = *AttrCycleSavings;
958 }
959
960 if (std::optional<int> AttrRuntimeCost = getStringFnAttrAsInt(
961 CandidateCall, "inline-runtime-cost-for-test")) {
962 Size = *AttrRuntimeCost;
963 }
964 }
965
966 // Determine whether we should inline the given call site, taking into account
967 // both the size cost and the cycle savings. Return std::nullopt if we don't
968 // have sufficient profiling information to determine.
969 std::optional<bool> costBenefitAnalysis() {
970 if (!CostBenefitAnalysisEnabled)
971 return std::nullopt;
972
973 // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
974 // for the prelink phase of the AutoFDO + ThinLTO build. Honor the logic by
975 // falling back to the cost-based metric.
976 // TODO: Improve this hacky condition.
977 if (Threshold == 0)
978 return std::nullopt;
979
980 assert(GetBFI);
981 BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
982 assert(CalleeBFI);
983
984 // The cycle savings expressed as the sum of InstrCost
985 // multiplied by the estimated dynamic count of each instruction we can
986 // avoid. Savings come from the call site cost, such as argument setup and
987 // the call instruction, as well as the instructions that are folded.
988 //
989 // We use 128-bit APInt here to avoid potential overflow. This variable
990 // should stay well below 10^^24 (or 2^^80) in practice. This "worst" case
991 // assumes that we can avoid or fold a billion instructions, each with a
992 // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
993 // period on a 4GHz machine.
994 APInt CycleSavings(128, 0);
995
996 for (auto &BB : F) {
997 APInt CurrentSavings(128, 0);
998 for (auto &I : BB) {
999 if (CondBrInst *BI = dyn_cast<CondBrInst>(&I)) {
1000 // Count a conditional branch as savings if it becomes unconditional.
1001 if (getSimplifiedValue<ConstantInt>(BI->getCondition()))
1002 CurrentSavings += InstrCost;
1003 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) {
1004 if (getSimplifiedValue<ConstantInt>(SI->getCondition()))
1005 CurrentSavings += InstrCost;
1006 } else if (SimplifiedValues.count(&I)) {
1007 // Count an instruction as savings if we can fold it.
1008 CurrentSavings += InstrCost;
1009 }
1010 }
1011
1012 auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
1013 CurrentSavings *= *ProfileCount;
1014 CycleSavings += CurrentSavings;
1015 }
1016
1017 // Compute the cycle savings per call.
1018 auto EntryProfileCount = F.getEntryCount();
1019 assert(EntryProfileCount && *EntryProfileCount);
1020 CycleSavings += *EntryProfileCount / 2;
1021 CycleSavings = CycleSavings.udiv(*EntryProfileCount);
1022
1023 // Compute the total savings for the call site.
1024 auto *CallerBB = CandidateCall.getParent();
1025 BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
1026 CycleSavings += getCallsiteCost(TTI, this->CandidateCall, DL);
1027 CycleSavings *= *CallerBFI->getBlockProfileCount(CallerBB);
1028
1029 // Remove the cost of the cold basic blocks to model the runtime cost more
1030 // accurately. Both machine block placement and function splitting could
1031 // place cold blocks further from hot blocks.
1032 int Size = Cost - ColdSize;
1033
1034 // Allow tiny callees to be inlined regardless of whether they meet the
1035 // savings threshold.
1037
1038 OverrideCycleSavingsAndSizeForTesting(CycleSavings, Size);
1039 CostBenefit.emplace(APInt(128, Size), CycleSavings);
1040
1041 // Let R be the ratio of CycleSavings to Size. We accept the inlining
1042 // opportunity if R is really high and reject if R is really low. If R is
1043 // somewhere in the middle, we fall back to the cost-based analysis.
1044 //
1045 // Specifically, let R = CycleSavings / Size, we accept the inlining
1046 // opportunity if:
1047 //
1048 // PSI->getOrCompHotCountThreshold()
1049 // R > -------------------------------------------------
1050 // getInliningCostBenefitAnalysisSavingsMultiplier()
1051 //
1052 // and reject the inlining opportunity if:
1053 //
1054 // PSI->getOrCompHotCountThreshold()
1055 // R <= ----------------------------------------------------
1056 // getInliningCostBenefitAnalysisProfitableMultiplier()
1057 //
1058 // Otherwise, we fall back to the cost-based analysis.
1059 //
1060 // Implementation-wise, use multiplication (CycleSavings * Multiplier,
1061 // HotCountThreshold * Size) rather than division to avoid precision loss.
1062 APInt Threshold(128, PSI->getOrCompHotCountThreshold());
1063 Threshold *= Size;
1064
1065 APInt UpperBoundCycleSavings = CycleSavings;
1066 UpperBoundCycleSavings *= getInliningCostBenefitAnalysisSavingsMultiplier();
1067 if (UpperBoundCycleSavings.uge(Threshold))
1068 return true;
1069
1070 APInt LowerBoundCycleSavings = CycleSavings;
1071 LowerBoundCycleSavings *=
1072 getInliningCostBenefitAnalysisProfitableMultiplier();
1073 if (LowerBoundCycleSavings.ult(Threshold))
1074 return false;
1075
1076 // Otherwise, fall back to the cost-based analysis.
1077 return std::nullopt;
1078 }
1079
1080 InlineResult finalizeAnalysis() override {
1081 // Loops generally act a lot like calls in that they act like barriers to
1082 // movement, require a certain amount of setup, etc. So when optimising for
1083 // size, we penalise any call sites that perform loops. We do this after all
1084 // other costs here, so will likely only be dealing with relatively small
1085 // functions (and hence LI will hopefully be cheap).
1086 auto *Caller = CandidateCall.getFunction();
1087 if (Caller->hasMinSize()) {
1088 LoopInfo LI;
1089 LI.analyze(&F);
1090 int NumLoops = 0;
1091 for (Loop *L : LI) {
1092 // Ignore loops that will not be executed
1093 if (DeadBlocks.count(L->getHeader()))
1094 continue;
1095 NumLoops++;
1096 }
1097 addCost(NumLoops * InlineConstants::LoopPenalty);
1098 }
1099
1100 // We applied the maximum possible vector bonus at the beginning. Now,
1101 // subtract the excess bonus, if any, from the Threshold before
1102 // comparing against Cost.
1103 if (NumVectorInstructions <= NumInstructions / 10)
1104 Threshold -= VectorBonus;
1105 else if (NumVectorInstructions <= NumInstructions / 2)
1106 Threshold -= VectorBonus / 2;
1107
1108 if (std::optional<int> AttrCost =
1109 getStringFnAttrAsInt(CandidateCall, "function-inline-cost"))
1110 Cost = *AttrCost;
1111
1112 if (std::optional<int> AttrCostMult = getStringFnAttrAsInt(
1113 CandidateCall,
1115 Cost *= *AttrCostMult;
1116
1117 if (std::optional<int> AttrThreshold =
1118 getStringFnAttrAsInt(CandidateCall, "function-inline-threshold"))
1119 Threshold = *AttrThreshold;
1120
1121 if (auto Result = costBenefitAnalysis()) {
1122 DecidedByCostBenefit = true;
1123 if (*Result)
1124 return InlineResult::success();
1125 else
1126 return InlineResult::failure("Cost over threshold.");
1127 }
1128
1129 if (IgnoreThreshold)
1130 return InlineResult::success();
1131
1132 DecidedByCostThreshold = true;
1133 return Cost < std::max(1, Threshold)
1135 : InlineResult::failure("Cost over threshold.");
1136 }
1137
1138 bool shouldStop() override {
1139 if (IgnoreThreshold || ComputeFullInlineCost)
1140 return false;
1141 // Bail out the moment we cross the threshold. This means we'll under-count
1142 // the cost, but only when undercounting doesn't matter.
1143 if (Cost < Threshold)
1144 return false;
1145 DecidedByCostThreshold = true;
1146 return true;
1147 }
1148
1149 void onLoadEliminationOpportunity() override {
1150 LoadEliminationCost += InstrCost;
1151 }
1152
1153 InlineResult onAnalysisStart() override {
1154 // Perform some tweaks to the cost and threshold based on the direct
1155 // callsite information.
1156
1157 // We want to more aggressively inline vector-dense kernels, so up the
1158 // threshold, and we'll lower it if the % of vector instructions gets too
1159 // low. Note that these bonuses are some what arbitrary and evolved over
1160 // time by accident as much as because they are principled bonuses.
1161 //
1162 // FIXME: It would be nice to remove all such bonuses. At least it would be
1163 // nice to base the bonus values on something more scientific.
1164 assert(NumInstructions == 0);
1165 assert(NumVectorInstructions == 0);
1166
1167 // Update the threshold based on callsite properties
1168 updateThreshold(CandidateCall, F);
1169
1170 // While Threshold depends on commandline options that can take negative
1171 // values, we want to enforce the invariant that the computed threshold and
1172 // bonuses are non-negative.
1173 assert(Threshold >= 0);
1174 assert(SingleBBBonus >= 0);
1175 assert(VectorBonus >= 0);
1176
1177 // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1178 // this Threshold any time, and cost cannot decrease, we can stop processing
1179 // the rest of the function body.
1180 Threshold += (SingleBBBonus + VectorBonus);
1181
1182 // Give out bonuses for the callsite, as the instructions setting them up
1183 // will be gone after inlining.
1184 addCost(-getCallsiteCost(TTI, this->CandidateCall, DL));
1185
1186 // If this function uses the coldcc calling convention, prefer not to inline
1187 // it.
1188 if (F.getCallingConv() == CallingConv::Cold)
1190
1191 LLVM_DEBUG(dbgs() << " Initial cost: " << Cost << "\n");
1192
1193 // Check if we're done. This can happen due to bonuses and penalties.
1194 if (Cost >= Threshold && !ComputeFullInlineCost)
1195 return InlineResult::failure("high cost");
1196
1197 return InlineResult::success();
1198 }
1199
1200public:
1201 InlineCostCallAnalyzer(
1202 Function &Callee, CallBase &Call, const InlineParams &Params,
1203 const TargetTransformInfo &TTI,
1204 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
1205 function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
1206 function_ref<const TargetLibraryInfo &(Function &)> GetTLI = nullptr,
1207 ProfileSummaryInfo *PSI = nullptr,
1208 OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
1209 bool IgnoreThreshold = false,
1210 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache =
1211 nullptr)
1212 : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, GetTLI, PSI,
1213 ORE, GetEphValuesCache),
1214 ComputeFullInlineCost(OptComputeFullInlineCost ||
1215 Params.ComputeFullInlineCost || ORE ||
1216 isCostBenefitAnalysisEnabled()),
1217 Params(Params), Threshold(Params.DefaultThreshold),
1218 BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
1219 CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
1220 Writer(this) {
1221 AllowRecursiveCall = *Params.AllowRecursiveCall;
1222 }
1223
1224 /// Annotation Writer for instruction details
1225 InlineCostAnnotationWriter Writer;
1226
1227 void dump();
1228
1229 // Prints the same analysis as dump(), but its definition is not dependent
1230 // on the build.
1231 void print(raw_ostream &OS);
1232
1233 std::optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
1234 auto It = InstructionCostDetailMap.find(I);
1235 if (It != InstructionCostDetailMap.end())
1236 return It->second;
1237 return std::nullopt;
1238 }
1239
1240 ~InlineCostCallAnalyzer() override = default;
1241 int getThreshold() const { return Threshold; }
1242 int getCost() const { return Cost; }
1243 int getStaticBonusApplied() const { return StaticBonusApplied; }
1244 std::optional<CostBenefitPair> getCostBenefitPair() { return CostBenefit; }
1245 bool wasDecidedByCostBenefit() const { return DecidedByCostBenefit; }
1246 bool wasDecidedByCostThreshold() const { return DecidedByCostThreshold; }
1247};
1248
1249// Return true if CB is the sole call to local function Callee.
1250static bool isSoleCallToLocalFunction(const CallBase &CB,
1251 const Function &Callee) {
1252 return Callee.hasLocalLinkage() && Callee.hasOneLiveUse() &&
1253 &Callee == CB.getCalledFunction();
1254}
1255
1256class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
1257private:
1258 InlineCostFeatures Cost = {};
1259
1260 // FIXME: These constants are taken from the heuristic-based cost visitor.
1261 // These should be removed entirely in a later revision to avoid reliance on
1262 // heuristics in the ML inliner.
1263 static constexpr int JTCostMultiplier = 2;
1264 static constexpr int CaseClusterCostMultiplier = 2;
1265 static constexpr int SwitchDefaultDestCostMultiplier = 2;
1266 static constexpr int SwitchCostMultiplier = 2;
1267
1268 // FIXME: These are taken from the heuristic-based cost visitor: we should
1269 // eventually abstract these to the CallAnalyzer to avoid duplication.
1270 unsigned SROACostSavingOpportunities = 0;
1271 int VectorBonus = 0;
1272 int SingleBBBonus = 0;
1273 int Threshold = 5;
1274
1275 DenseMap<AllocaInst *, unsigned> SROACosts;
1276
1277 void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
1278 Cost[static_cast<size_t>(Feature)] += Delta;
1279 }
1280
1281 void set(InlineCostFeatureIndex Feature, int64_t Value) {
1282 Cost[static_cast<size_t>(Feature)] = Value;
1283 }
1284
1285 void onDisableSROA(AllocaInst *Arg) override {
1286 auto CostIt = SROACosts.find(Arg);
1287 if (CostIt == SROACosts.end())
1288 return;
1289
1290 increment(InlineCostFeatureIndex::sroa_losses, CostIt->second);
1291 SROACostSavingOpportunities -= CostIt->second;
1292 SROACosts.erase(CostIt);
1293 }
1294
1295 void onDisableLoadElimination() override {
1296 set(InlineCostFeatureIndex::load_elimination, 1);
1297 }
1298
1299 void onCallPenalty() override {
1300 increment(InlineCostFeatureIndex::call_penalty, CallPenalty);
1301 }
1302
1303 void onCallArgumentSetup(const CallBase &Call) override {
1304 increment(InlineCostFeatureIndex::call_argument_setup,
1305 Call.arg_size() * InstrCost);
1306 }
1307
1308 void onLoadRelativeIntrinsic() override {
1309 increment(InlineCostFeatureIndex::load_relative_intrinsic, 3 * InstrCost);
1310 }
1311
1312 void onLoweredCall(Function *F, CallBase &Call,
1313 bool IsIndirectCall) override {
1314 increment(InlineCostFeatureIndex::lowered_call_arg_setup,
1315 Call.arg_size() * InstrCost);
1316
1317 if (IsIndirectCall) {
1318 InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
1319 /*HintThreshold*/ {},
1320 /*OptSizeHintThreshold*/ {},
1321 /*ColdThreshold*/ {},
1322 /*OptSizeThreshold*/ {},
1323 /*OptMinSizeThreshold*/ {},
1324 /*HotCallSiteThreshold*/ {},
1325 /*LocallyHotCallSiteThreshold*/ {},
1326 /*ColdCallSiteThreshold*/ {},
1327 /*ComputeFullInlineCost*/ true,
1328 /*EnableDeferral*/ true};
1329 IndirectCallParams.DefaultThreshold =
1331
1332 InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
1333 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
1334 false, true);
1335 if (CA.analyze().isSuccess()) {
1336 increment(InlineCostFeatureIndex::nested_inline_cost_estimate,
1337 CA.getCost());
1338 increment(InlineCostFeatureIndex::nested_inlines, 1);
1339 }
1340 } else {
1341 onCallPenalty();
1342 }
1343 }
1344
1345 void onFinalizeSwitch(unsigned JumpTableSize, unsigned NumCaseCluster,
1346 bool DefaultDestUnreachable) override {
1347 if (JumpTableSize) {
1348 if (!DefaultDestUnreachable)
1349 increment(InlineCostFeatureIndex::switch_default_dest_penalty,
1350 SwitchDefaultDestCostMultiplier * InstrCost);
1351 int64_t JTCost = static_cast<int64_t>(JumpTableSize) * InstrCost +
1352 JTCostMultiplier * InstrCost;
1353 increment(InlineCostFeatureIndex::jump_table_penalty, JTCost);
1354 return;
1355 }
1356
1357 if (NumCaseCluster <= 3) {
1358 increment(InlineCostFeatureIndex::case_cluster_penalty,
1359 (NumCaseCluster - DefaultDestUnreachable) *
1360 CaseClusterCostMultiplier * InstrCost);
1361 return;
1362 }
1363
1364 int64_t ExpectedNumberOfCompare =
1365 getExpectedNumberOfCompare(NumCaseCluster);
1366
1367 int64_t SwitchCost =
1368 ExpectedNumberOfCompare * SwitchCostMultiplier * InstrCost;
1369 increment(InlineCostFeatureIndex::switch_penalty, SwitchCost);
1370 }
1371
1372 void onMissedSimplification() override {
1373 increment(InlineCostFeatureIndex::unsimplified_common_instructions,
1374 InstrCost);
1375 }
1376
1377 void onInitializeSROAArg(AllocaInst *Arg) override {
1378 auto SROAArgCost = TTI.getCallerAllocaCost(&CandidateCall, Arg);
1379 SROACosts[Arg] = SROAArgCost;
1380 SROACostSavingOpportunities += SROAArgCost;
1381 }
1382
1383 void onAggregateSROAUse(AllocaInst *Arg) override {
1384 SROACosts.find(Arg)->second += InstrCost;
1385 SROACostSavingOpportunities += InstrCost;
1386 }
1387
1388 void onBlockAnalyzed(const BasicBlock *BB) override {
1389 if (BB->getTerminator()->getNumSuccessors() > 1)
1390 set(InlineCostFeatureIndex::is_multiple_blocks, 1);
1391 Threshold -= SingleBBBonus;
1392 }
1393
1394 InlineResult finalizeAnalysis() override {
1395 auto *Caller = CandidateCall.getFunction();
1396 if (Caller->hasMinSize()) {
1397 LoopInfo LI;
1398 LI.analyze(&F);
1399 for (Loop *L : LI) {
1400 // Ignore loops that will not be executed
1401 if (DeadBlocks.count(L->getHeader()))
1402 continue;
1403 increment(InlineCostFeatureIndex::num_loops,
1405 }
1406 }
1407 set(InlineCostFeatureIndex::dead_blocks, DeadBlocks.size());
1408 set(InlineCostFeatureIndex::simplified_instructions,
1409 NumInstructionsSimplified);
1410 set(InlineCostFeatureIndex::constant_args, NumConstantArgs);
1411 set(InlineCostFeatureIndex::constant_offset_ptr_args,
1412 NumConstantOffsetPtrArgs);
1413 set(InlineCostFeatureIndex::sroa_savings, SROACostSavingOpportunities);
1414
1415 if (NumVectorInstructions <= NumInstructions / 10)
1416 Threshold -= VectorBonus;
1417 else if (NumVectorInstructions <= NumInstructions / 2)
1418 Threshold -= VectorBonus / 2;
1419
1420 set(InlineCostFeatureIndex::threshold, Threshold);
1421
1422 return InlineResult::success();
1423 }
1424
1425 bool shouldStop() override { return false; }
1426
1427 void onLoadEliminationOpportunity() override {
1428 increment(InlineCostFeatureIndex::load_elimination, 1);
1429 }
1430
1431 InlineResult onAnalysisStart() override {
1432 increment(InlineCostFeatureIndex::callsite_cost,
1433 -1 * getCallsiteCost(TTI, this->CandidateCall, DL));
1434
1435 set(InlineCostFeatureIndex::cold_cc_penalty,
1436 (F.getCallingConv() == CallingConv::Cold));
1437
1438 set(InlineCostFeatureIndex::last_call_to_static_bonus,
1439 isSoleCallToLocalFunction(CandidateCall, F));
1440
1441 // FIXME: we shouldn't repeat this logic in both the Features and Cost
1442 // analyzer - instead, we should abstract it to a common method in the
1443 // CallAnalyzer
1444 int SingleBBBonusPercent = 50;
1445 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1446 Threshold += TTI.adjustInliningThreshold(&CandidateCall);
1447 Threshold *= TTI.getInliningThresholdMultiplier();
1448 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1449 VectorBonus = Threshold * VectorBonusPercent / 100;
1450 Threshold += (SingleBBBonus + VectorBonus);
1451
1452 return InlineResult::success();
1453 }
1454
1455public:
1456 InlineCostFeaturesAnalyzer(
1457 const TargetTransformInfo &TTI,
1458 function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
1459 function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
1460 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
1461 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
1462 CallBase &Call)
1463 : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, GetTLI,
1464 PSI) {}
1465
1466 const InlineCostFeatures &features() const { return Cost; }
1467};
1468
1469} // namespace
1470
1471/// Test whether the given value is an Alloca-derived function argument.
1472bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
1473 return SROAArgValues.count(V);
1474}
1475
1476void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
1477 onDisableSROA(SROAArg);
1478 EnabledSROAAllocas.erase(SROAArg);
1479 disableLoadElimination();
1480}
1481
1482void InlineCostAnnotationWriter::emitInstructionAnnot(
1483 const Instruction *I, formatted_raw_ostream &OS) {
1484 // The cost of inlining of the given instruction is printed always.
1485 // The threshold delta is printed only when it is non-zero. It happens
1486 // when we decided to give a bonus at a particular instruction.
1487 std::optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
1488 if (!Record)
1489 OS << "; No analysis for the instruction";
1490 else {
1491 OS << "; cost before = " << Record->CostBefore
1492 << ", cost after = " << Record->CostAfter
1493 << ", threshold before = " << Record->ThresholdBefore
1494 << ", threshold after = " << Record->ThresholdAfter << ", ";
1495 OS << "cost delta = " << Record->getCostDelta();
1496 if (Record->hasThresholdChanged())
1497 OS << ", threshold delta = " << Record->getThresholdDelta();
1498 }
1499 auto *V = ICCA->getSimplifiedValueUnchecked(const_cast<Instruction *>(I));
1500 if (V) {
1501 OS << ", simplified to ";
1502 V->print(OS, true);
1503 if (auto *VI = dyn_cast<Instruction>(V)) {
1504 if (VI->getFunction() != I->getFunction())
1505 OS << " (caller instruction)";
1506 } else if (auto *VArg = dyn_cast<Argument>(V)) {
1507 if (VArg->getParent() != I->getFunction())
1508 OS << " (caller argument)";
1509 }
1510 }
1511 OS << "\n";
1512}
1513
1514/// If 'V' maps to a SROA candidate, disable SROA for it.
1515void CallAnalyzer::disableSROA(Value *V) {
1516 if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
1517 disableSROAForArg(SROAArg);
1518 }
1519}
1520
1521void CallAnalyzer::disableLoadElimination() {
1522 if (EnableLoadElimination) {
1523 onDisableLoadElimination();
1524 EnableLoadElimination = false;
1525 }
1526}
1527
1528/// Accumulate a constant GEP offset into an APInt if possible.
1529///
1530/// Returns false if unable to compute the offset for any reason. Respects any
1531/// simplified values known during the analysis of this callsite.
1532bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1533 unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
1534 assert(IntPtrWidth == Offset.getBitWidth());
1535
1537 GTI != GTE; ++GTI) {
1538 ConstantInt *OpC =
1539 getDirectOrSimplifiedValue<ConstantInt>(GTI.getOperand());
1540 if (!OpC)
1541 return false;
1542 if (OpC->isZero())
1543 continue;
1544
1545 // Handle a struct index, which adds its field offset to the pointer.
1546 if (StructType *STy = GTI.getStructTypeOrNull()) {
1547 unsigned ElementIdx = OpC->getZExtValue();
1548 const StructLayout *SL = DL.getStructLayout(STy);
1549 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
1550 continue;
1551 }
1552
1553 APInt TypeSize(IntPtrWidth, GTI.getSequentialElementStride(DL));
1554 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
1555 }
1556 return true;
1557}
1558
1559/// Use TTI to check whether a GEP is free.
1560///
1561/// Respects any simplified values known during the analysis of this callsite.
1562bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
1563 SmallVector<Value *, 4> Operands;
1564 Operands.push_back(GEP.getOperand(0));
1565 for (const Use &Op : GEP.indices())
1566 if (Constant *SimpleOp = getSimplifiedValue<Constant>(Op))
1567 Operands.push_back(SimpleOp);
1568 else
1569 Operands.push_back(Op);
1573}
1574
1575bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1576 disableSROA(I.getOperand(0));
1577
1578 // Check whether inlining will turn a dynamic alloca into a static
1579 // alloca and handle that case.
1580 if (I.isArrayAllocation()) {
1581 Constant *Size = getSimplifiedValue<Constant>(I.getArraySize());
1582 if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1583 // Sometimes a dynamic alloca could be converted into a static alloca
1584 // after this constant prop, and become a huge static alloca on an
1585 // unconditional CFG path. Avoid inlining if this is going to happen above
1586 // a threshold.
1587 // FIXME: If the threshold is removed or lowered too much, we could end up
1588 // being too pessimistic and prevent inlining non-problematic code. This
1589 // could result in unintended perf regressions. A better overall strategy
1590 // is needed to track stack usage during inlining.
1591 Type *Ty = I.getAllocatedType();
1592 AllocatedSize = SaturatingMultiplyAdd(
1593 AllocSize->getLimitedValue(),
1594 DL.getTypeAllocSize(Ty).getKnownMinValue(), AllocatedSize);
1596 HasDynamicAlloca = true;
1597 return false;
1598 }
1599 }
1600
1601 if (I.isStaticAlloca()) {
1602 // Accumulate the allocated size if constant and executed once.
1603 // Note: if AllocSize is a vscale value, this is an underestimate of the
1604 // allocated size, and it also requires some of the cost of a dynamic
1605 // alloca, but is recorded here as a constant size alloca.
1606 TypeSize AllocSize = I.getAllocationSize(DL).value_or(TypeSize::getZero());
1607 AllocatedSize = SaturatingAdd(AllocSize.getKnownMinValue(), AllocatedSize);
1608 } else {
1609 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
1610 // a variety of reasons, and so we would like to not inline them into
1611 // functions which don't currently have a dynamic alloca. This simply
1612 // disables inlining altogether in the presence of a dynamic alloca.
1613 HasDynamicAlloca = true;
1614 }
1615
1616 return false;
1617}
1618
1619bool CallAnalyzer::visitPHI(PHINode &I) {
1620 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
1621 // though we don't want to propagate it's bonuses. The idea is to disable
1622 // SROA if it *might* be used in an inappropriate manner.
1623
1624 // Phi nodes are always zero-cost.
1625 // FIXME: Pointer sizes may differ between different address spaces, so do we
1626 // need to use correct address space in the call to getPointerSizeInBits here?
1627 // Or could we skip the getPointerSizeInBits call completely? As far as I can
1628 // see the ZeroOffset is used as a dummy value, so we can probably use any
1629 // bit width for the ZeroOffset?
1630 APInt ZeroOffset = APInt::getZero(DL.getPointerSizeInBits(0));
1631 bool CheckSROA = I.getType()->isPointerTy();
1632
1633 // Track the constant or pointer with constant offset we've seen so far.
1634 Constant *FirstC = nullptr;
1635 std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
1636 Value *FirstV = nullptr;
1637
1638 for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
1639 BasicBlock *Pred = I.getIncomingBlock(i);
1640 // If the incoming block is dead, skip the incoming block.
1641 if (DeadBlocks.count(Pred))
1642 continue;
1643 // If the parent block of phi is not the known successor of the incoming
1644 // block, skip the incoming block.
1645 BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
1646 if (KnownSuccessor && KnownSuccessor != I.getParent())
1647 continue;
1648
1649 Value *V = I.getIncomingValue(i);
1650 // If the incoming value is this phi itself, skip the incoming value.
1651 if (&I == V)
1652 continue;
1653
1654 Constant *C = getDirectOrSimplifiedValue<Constant>(V);
1655
1656 std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
1657 if (!C && CheckSROA)
1658 BaseAndOffset = ConstantOffsetPtrs.lookup(V);
1659
1660 if (!C && !BaseAndOffset.first)
1661 // The incoming value is neither a constant nor a pointer with constant
1662 // offset, exit early.
1663 return true;
1664
1665 if (FirstC) {
1666 if (FirstC == C)
1667 // If we've seen a constant incoming value before and it is the same
1668 // constant we see this time, continue checking the next incoming value.
1669 continue;
1670 // Otherwise early exit because we either see a different constant or saw
1671 // a constant before but we have a pointer with constant offset this time.
1672 return true;
1673 }
1674
1675 if (FirstV) {
1676 // The same logic as above, but check pointer with constant offset here.
1677 if (FirstBaseAndOffset == BaseAndOffset)
1678 continue;
1679 return true;
1680 }
1681
1682 if (C) {
1683 // This is the 1st time we've seen a constant, record it.
1684 FirstC = C;
1685 continue;
1686 }
1687
1688 // The remaining case is that this is the 1st time we've seen a pointer with
1689 // constant offset, record it.
1690 FirstV = V;
1691 FirstBaseAndOffset = BaseAndOffset;
1692 }
1693
1694 // Check if we can map phi to a constant.
1695 if (FirstC) {
1696 SimplifiedValues[&I] = FirstC;
1697 return true;
1698 }
1699
1700 // Check if we can map phi to a pointer with constant offset.
1701 if (FirstBaseAndOffset.first) {
1702 ConstantOffsetPtrs[&I] = std::move(FirstBaseAndOffset);
1703
1704 if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
1705 SROAArgValues[&I] = SROAArg;
1706 }
1707
1708 return true;
1709}
1710
1711/// Check we can fold GEPs of constant-offset call site argument pointers.
1712/// This requires target data and inbounds GEPs.
1713///
1714/// \return true if the specified GEP can be folded.
1715bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1716 // Check if we have a base + offset for the pointer.
1717 std::pair<Value *, APInt> BaseAndOffset =
1718 ConstantOffsetPtrs.lookup(I.getPointerOperand());
1719 if (!BaseAndOffset.first)
1720 return false;
1721
1722 // Check if the offset of this GEP is constant, and if so accumulate it
1723 // into Offset.
1724 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1725 return false;
1726
1727 // Add the result as a new mapping to Base + Offset.
1728 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1729
1730 return true;
1731}
1732
1733bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
1734 auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
1735
1736 // Lambda to check whether a GEP's indices are all constant.
1737 auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
1738 for (const Use &Op : GEP.indices())
1739 if (!getDirectOrSimplifiedValue<Constant>(Op))
1740 return false;
1741 return true;
1742 };
1743
1746 return true;
1747
1748 if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
1749 if (SROAArg)
1750 SROAArgValues[&I] = SROAArg;
1751
1752 // Constant GEPs are modeled as free.
1753 return true;
1754 }
1755
1756 // Variable GEPs will require math and will disable SROA.
1757 if (SROAArg)
1758 disableSROAForArg(SROAArg);
1759 return isGEPFree(I);
1760}
1761
1762// Simplify \p Cmp if RHS is const and we can ValueTrack LHS.
1763// This handles the case only when the Cmp instruction is guarding a recursive
1764// call that will cause the Cmp to fail/succeed for the recursive call.
1765bool CallAnalyzer::simplifyCmpInstForRecCall(CmpInst &Cmp) {
1766 // Bail out if LHS is not a function argument or RHS is NOT const:
1767 if (!isa<Argument>(Cmp.getOperand(0)) || !isa<Constant>(Cmp.getOperand(1)))
1768 return false;
1769 auto *CmpOp = Cmp.getOperand(0);
1770 // Make sure that the callsite is recursive:
1771 if (CandidateCall.getCaller() != &F)
1772 return false;
1773 // Only handle the case when the callsite has a single predecessor:
1774 auto *CallBB = CandidateCall.getParent();
1775 auto *Predecessor = CallBB->getSinglePredecessor();
1776 if (!Predecessor)
1777 return false;
1778 // Check if the callsite is guarded by the same Cmp instruction:
1779 auto *Br = dyn_cast<CondBrInst>(Predecessor->getTerminator());
1780 if (!Br || Br->getCondition() != &Cmp)
1781 return false;
1782
1783 // Check if there is any arg of the recursive callsite is affecting the cmp
1784 // instr:
1785 bool ArgFound = false;
1786 Value *FuncArg = nullptr, *CallArg = nullptr;
1787 for (unsigned ArgNum = 0;
1788 ArgNum < F.arg_size() && ArgNum < CandidateCall.arg_size(); ArgNum++) {
1789 FuncArg = F.getArg(ArgNum);
1790 CallArg = CandidateCall.getArgOperand(ArgNum);
1791 if (FuncArg == CmpOp && CallArg != CmpOp) {
1792 ArgFound = true;
1793 break;
1794 }
1795 }
1796 if (!ArgFound)
1797 return false;
1798
1799 // Now we have a recursive call that is guarded by a cmp instruction.
1800 // Check if this cmp can be simplified:
1801 SimplifyQuery SQ(DL, dyn_cast<Instruction>(CallArg));
1802 CondContext CC(&Cmp);
1803 CC.Invert = (CallBB != Br->getSuccessor(0));
1804 SQ.CC = &CC;
1805 CC.AffectedValues.insert(FuncArg);
1806 Value *SimplifiedInstruction = llvm::simplifyInstructionWithOperands(
1807 cast<CmpInst>(&Cmp), {CallArg, Cmp.getOperand(1)}, SQ);
1808 if (auto *ConstVal = dyn_cast_or_null<ConstantInt>(SimplifiedInstruction)) {
1809 // Make sure that the BB of the recursive call is NOT the true successor
1810 // of the icmp. In other words, make sure that the recursion depth is 1.
1811 if ((ConstVal->isOne() && CC.Invert) ||
1812 (ConstVal->isZero() && !CC.Invert)) {
1813 SimplifiedValues[&Cmp] = ConstVal;
1814 return true;
1815 }
1816 }
1817 return false;
1818}
1819
1820/// Simplify \p I if its operands are constants and update SimplifiedValues.
1821bool CallAnalyzer::simplifyInstruction(Instruction &I) {
1823 for (Value *Op : I.operands()) {
1824 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
1825 if (!COp)
1826 return false;
1827 COps.push_back(COp);
1828 }
1829 auto *C = ConstantFoldInstOperands(&I, COps, DL);
1830 if (!C)
1831 return false;
1832 SimplifiedValues[&I] = C;
1833 return true;
1834}
1835
1836/// Try to simplify a call to llvm.is.constant.
1837///
1838/// Duplicate the argument checking from CallAnalyzer::simplifyCallSite since
1839/// we expect calls of this specific intrinsic to be infrequent.
1840///
1841/// FIXME: Given that we know CB's parent (F) caller
1842/// (CandidateCall->getParent()->getParent()), we might be able to determine
1843/// whether inlining F into F's caller would change how the call to
1844/// llvm.is.constant would evaluate.
1845bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
1846 Value *Arg = CB.getArgOperand(0);
1847 auto *C = getDirectOrSimplifiedValue<Constant>(Arg);
1848
1849 Type *RT = CB.getFunctionType()->getReturnType();
1850 SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
1851 return true;
1852}
1853
1854bool CallAnalyzer::simplifyIntrinsicCallObjectSize(CallBase &CB) {
1855 // As per the langref, "The fourth argument to llvm.objectsize determines if
1856 // the value should be evaluated at runtime."
1857 if (cast<ConstantInt>(CB.getArgOperand(3))->isOne())
1858 return false;
1859
1861 /*MustSucceed=*/true);
1863 if (C)
1864 SimplifiedValues[&CB] = C;
1865 return C;
1866}
1867
1868bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1869 // Propagate constants through bitcasts.
1871 return true;
1872
1873 // Track base/offsets through casts
1874 std::pair<Value *, APInt> BaseAndOffset =
1875 ConstantOffsetPtrs.lookup(I.getOperand(0));
1876 // Casts don't change the offset, just wrap it up.
1877 if (BaseAndOffset.first)
1878 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1879
1880 // Also look for SROA candidates here.
1881 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1882 SROAArgValues[&I] = SROAArg;
1883
1884 // Bitcasts are always zero cost.
1885 return true;
1886}
1887
1888bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
1889 // Propagate constants through ptrtoint.
1891 return true;
1892
1893 // Track base/offset pairs when converted to a plain integer provided the
1894 // integer is large enough to represent the pointer.
1895 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
1896 unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1897 if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1898 std::pair<Value *, APInt> BaseAndOffset =
1899 ConstantOffsetPtrs.lookup(I.getOperand(0));
1900 if (BaseAndOffset.first)
1901 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1902 }
1903
1904 // This is really weird. Technically, ptrtoint will disable SROA. However,
1905 // unless that ptrtoint is *used* somewhere in the live basic blocks after
1906 // inlining, it will be nuked, and SROA should proceed. All of the uses which
1907 // would block SROA would also block SROA if applied directly to a pointer,
1908 // and so we can just add the integer in here. The only places where SROA is
1909 // preserved either cannot fire on an integer, or won't in-and-of themselves
1910 // disable SROA (ext) w/o some later use that we would see and disable.
1911 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1912 SROAArgValues[&I] = SROAArg;
1913
1916}
1917
1918bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
1919 // Propagate constants through ptrtoint.
1921 return true;
1922
1923 // Track base/offset pairs when round-tripped through a pointer without
1924 // modifications provided the integer is not too large.
1925 Value *Op = I.getOperand(0);
1926 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
1927 if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
1928 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
1929 if (BaseAndOffset.first)
1930 ConstantOffsetPtrs[&I] = std::move(BaseAndOffset);
1931 }
1932
1933 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
1934 if (auto *SROAArg = getSROAArgForValueOrNull(Op))
1935 SROAArgValues[&I] = SROAArg;
1936
1939}
1940
1941bool CallAnalyzer::visitCastInst(CastInst &I) {
1942 // Propagate constants through casts.
1944 return true;
1945
1946 // Disable SROA in the face of arbitrary casts we don't explicitly list
1947 // elsewhere.
1948 disableSROA(I.getOperand(0));
1949
1950 // If this is a floating-point cast, and the target says this operation
1951 // is expensive, this may eventually become a library call. Treat the cost
1952 // as such.
1953 switch (I.getOpcode()) {
1954 case Instruction::FPTrunc:
1955 case Instruction::FPExt:
1956 case Instruction::UIToFP:
1957 case Instruction::SIToFP:
1958 case Instruction::FPToUI:
1959 case Instruction::FPToSI:
1961 onCallPenalty();
1962 break;
1963 default:
1964 break;
1965 }
1966
1969}
1970
1971bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1972 return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
1973}
1974
1975bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
1976 // Does the *call site* have the NonNull attribute set on an argument? We
1977 // use the attribute on the call site to memoize any analysis done in the
1978 // caller. This will also trip if the callee function has a non-null
1979 // parameter attribute, but that's a less interesting case because hopefully
1980 // the callee would already have been simplified based on that.
1981 if (Argument *A = dyn_cast<Argument>(V))
1982 if (paramHasAttr(A, Attribute::NonNull))
1983 return true;
1984
1985 // Is this an alloca in the caller? This is distinct from the attribute case
1986 // above because attributes aren't updated within the inliner itself and we
1987 // always want to catch the alloca derived case.
1988 if (isAllocaDerivedArg(V))
1989 // We can actually predict the result of comparisons between an
1990 // alloca-derived value and null. Note that this fires regardless of
1991 // SROA firing.
1992 return true;
1993
1994 return false;
1995}
1996
1997bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
1998 // If the normal destination of the invoke or the parent block of the call
1999 // site is unreachable-terminated, there is little point in inlining this
2000 // unless there is literally zero cost.
2001 // FIXME: Note that it is possible that an unreachable-terminated block has a
2002 // hot entry. For example, in below scenario inlining hot_call_X() may be
2003 // beneficial :
2004 // main() {
2005 // hot_call_1();
2006 // ...
2007 // hot_call_N()
2008 // exit(0);
2009 // }
2010 // For now, we are not handling this corner case here as it is rare in real
2011 // code. In future, we should elaborate this based on BPI and BFI in more
2012 // general threshold adjusting heuristics in updateThreshold().
2013 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
2014 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
2015 return false;
2016 } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
2017 return false;
2018
2019 return true;
2020}
2021
2022bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
2023 BlockFrequencyInfo *CallerBFI) {
2024 // If global profile summary is available, then callsite's coldness is
2025 // determined based on that.
2026 if (PSI && PSI->hasProfileSummary())
2027 return PSI->isColdCallSite(Call, CallerBFI);
2028
2029 // Otherwise we need BFI to be available.
2030 if (!CallerBFI)
2031 return false;
2032
2033 // Determine if the callsite is cold relative to caller's entry. We could
2034 // potentially cache the computation of scaled entry frequency, but the added
2035 // complexity is not worth it unless this scaling shows up high in the
2036 // profiles.
2037 const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
2038 auto CallSiteBB = Call.getParent();
2039 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
2040 auto CallerEntryFreq =
2041 CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
2042 return CallSiteFreq < CallerEntryFreq * ColdProb;
2043}
2044
2045std::optional<int>
2046InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
2047 BlockFrequencyInfo *CallerBFI) {
2048
2049 // If global profile summary is available, then callsite's hotness is
2050 // determined based on that.
2051 if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
2052 return Params.HotCallSiteThreshold;
2053
2054 // Otherwise we need BFI to be available and to have a locally hot callsite
2055 // threshold.
2056 if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
2057 return std::nullopt;
2058
2059 // Determine if the callsite is hot relative to caller's entry. We could
2060 // potentially cache the computation of scaled entry frequency, but the added
2061 // complexity is not worth it unless this scaling shows up high in the
2062 // profiles.
2063 const BasicBlock *CallSiteBB = Call.getParent();
2064 BlockFrequency CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
2065 BlockFrequency CallerEntryFreq = CallerBFI->getEntryFreq();
2066 std::optional<BlockFrequency> Limit = CallerEntryFreq.mul(HotCallSiteRelFreq);
2067 if (Limit && CallSiteFreq >= *Limit)
2068 return Params.LocallyHotCallSiteThreshold;
2069
2070 // Otherwise treat it normally.
2071 return std::nullopt;
2072}
2073
2074void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
2075 // If no size growth is allowed for this inlining, set Threshold to 0.
2076 if (!allowSizeGrowth(Call)) {
2077 Threshold = 0;
2078 return;
2079 }
2080
2082
2083 // return min(A, B) if B is valid.
2084 auto MinIfValid = [](int A, std::optional<int> B) {
2085 return B ? std::min(A, *B) : A;
2086 };
2087
2088 // return max(A, B) if B is valid.
2089 auto MaxIfValid = [](int A, std::optional<int> B) {
2090 return B ? std::max(A, *B) : A;
2091 };
2092
2093 // Various bonus percentages. These are multiplied by Threshold to get the
2094 // bonus values.
2095 // SingleBBBonus: This bonus is applied if the callee has a single reachable
2096 // basic block at the given callsite context. This is speculatively applied
2097 // and withdrawn if more than one basic block is seen.
2098 //
2099 // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
2100 // of the last call to a static function as inlining such functions is
2101 // guaranteed to reduce code size.
2102 //
2103 // These bonus percentages may be set to 0 based on properties of the caller
2104 // and the callsite.
2105 int SingleBBBonusPercent = 50;
2106 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
2107 int LastCallToStaticBonus = TTI.getInliningLastCallToStaticBonus();
2108
2109 // Lambda to set all the above bonus and bonus percentages to 0.
2110 auto DisallowAllBonuses = [&]() {
2111 SingleBBBonusPercent = 0;
2112 VectorBonusPercent = 0;
2113 LastCallToStaticBonus = 0;
2114 };
2115
2116 // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
2117 // and reduce the threshold if the caller has the necessary attribute.
2118 if (Caller->hasMinSize()) {
2119 Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
2120 // For minsize, we want to disable the single BB bonus and the vector
2121 // bonuses, but not the last-call-to-static bonus. Inlining the last call to
2122 // a static function will, at the minimum, eliminate the parameter setup and
2123 // call/return instructions.
2124 SingleBBBonusPercent = 0;
2125 VectorBonusPercent = 0;
2126 } else if (Caller->hasOptSize())
2127 Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
2128
2129 // Adjust the threshold based on inlinehint attribute and profile based
2130 // hotness information if the caller does not have MinSize attribute.
2131 if (!Caller->hasMinSize()) {
2132 std::optional<int> HintThreshold = Caller->hasOptSize()
2133 ? Params.OptSizeHintThreshold
2134 : Params.HintThreshold;
2135 if (Callee.hasFnAttribute(Attribute::InlineHint))
2136 Threshold = MaxIfValid(Threshold, HintThreshold);
2137
2138 // FIXME: After switching to the new passmanager, simplify the logic below
2139 // by checking only the callsite hotness/coldness as we will reliably
2140 // have local profile information.
2141 //
2142 // Callsite hotness and coldness can be determined if sample profile is
2143 // used (which adds hotness metadata to calls) or if caller's
2144 // BlockFrequencyInfo is available.
2145 BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
2146 auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
2147 if (!Caller->hasOptSize() && HotCallSiteThreshold) {
2148 LLVM_DEBUG(dbgs() << "Hot callsite.\n");
2149 // FIXME: This should update the threshold only if it exceeds the
2150 // current threshold, but AutoFDO + ThinLTO currently relies on this
2151 // behavior to prevent inlining of hot callsites during ThinLTO
2152 // compile phase.
2153 Threshold = *HotCallSiteThreshold;
2154 } else if (isCallableCC(Caller->getCallingConv()) &&
2155 isColdCallSite(Call, CallerBFI)) {
2156 // In a function that is a hardware entry point rather than something
2157 // callable, e.g. a GPU kernel, register allocation is whole-function and
2158 // occupancy is set by the worst case over it. A call left out of line
2159 // there costs the hot path too, however cold the call itself is, so the
2160 // reduced threshold does not apply.
2161 LLVM_DEBUG(dbgs() << "Cold callsite.\n");
2162 // Do not apply bonuses for a cold callsite including the
2163 // LastCallToStatic bonus. While this bonus might result in code size
2164 // reduction, it can cause the size of a non-cold caller to increase
2165 // preventing it from being inlined.
2166 DisallowAllBonuses();
2167 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
2168 } else if (PSI) {
2169 // Use callee's global profile information only if we have no way of
2170 // determining this via callsite information.
2171 if (PSI->isFunctionEntryHot(&Callee)) {
2172 LLVM_DEBUG(dbgs() << "Hot callee.\n");
2173 // If callsite hotness can not be determined, we may still know
2174 // that the callee is hot and treat it as a weaker hint for threshold
2175 // increase.
2176 Threshold = MaxIfValid(Threshold, HintThreshold);
2177 } else if (PSI->isFunctionEntryCold(&Callee)) {
2178 LLVM_DEBUG(dbgs() << "Cold callee.\n");
2179 // Do not apply bonuses for a cold callee including the
2180 // LastCallToStatic bonus. While this bonus might result in code size
2181 // reduction, it can cause the size of a non-cold caller to increase
2182 // preventing it from being inlined.
2183 DisallowAllBonuses();
2184 Threshold = MinIfValid(Threshold, Params.ColdThreshold);
2185 }
2186 }
2187 }
2188
2189 Threshold += TTI.adjustInliningThreshold(&Call);
2190
2191 // Finally, take the target-specific inlining threshold multiplier into
2192 // account.
2193 Threshold *= TTI.getInliningThresholdMultiplier();
2194
2195 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
2196 VectorBonus = Threshold * VectorBonusPercent / 100;
2197
2198 // If there is only one call of the function, and it has internal linkage,
2199 // the cost of inlining it drops dramatically. It may seem odd to update
2200 // Cost in updateThreshold, but the bonus depends on the logic in this method.
2201 if (isSoleCallToLocalFunction(Call, F)) {
2202 addCost(-LastCallToStaticBonus);
2203 StaticBonusApplied = LastCallToStaticBonus;
2204 }
2205}
2206
2207bool CallAnalyzer::visitCmpInst(CmpInst &I) {
2208 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2209 // First try to handle simplified comparisons.
2211 return true;
2212
2213 // Try to handle comparison that can be simplified using ValueTracking.
2214 if (simplifyCmpInstForRecCall(I))
2215 return true;
2216
2217 if (I.getOpcode() == Instruction::FCmp)
2218 return false;
2219
2220 // Otherwise look for a comparison between constant offset pointers with
2221 // a common base.
2222 Value *LHSBase, *RHSBase;
2223 APInt LHSOffset, RHSOffset;
2224 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2225 if (LHSBase) {
2226 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2227 if (RHSBase && LHSBase == RHSBase) {
2228 // We have common bases, fold the icmp to a constant based on the
2229 // offsets.
2230 SimplifiedValues[&I] = ConstantInt::getBool(
2231 I.getType(),
2232 ICmpInst::compare(LHSOffset, RHSOffset, I.getPredicate()));
2233 ++NumConstantPtrCmps;
2234 return true;
2235 }
2236 }
2237
2238 auto isImplicitNullCheckCmp = [](const CmpInst &I) {
2239 for (auto *User : I.users())
2240 if (auto *Instr = dyn_cast<Instruction>(User))
2241 if (!Instr->getMetadata(LLVMContext::MD_make_implicit))
2242 return false;
2243 return true;
2244 };
2245
2246 // If the comparison is an equality comparison with null, we can simplify it
2247 // if we know the value (argument) can't be null
2248 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1))) {
2249 if (isKnownNonNullInCallee(I.getOperand(0))) {
2250 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
2251 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
2252 : ConstantInt::getFalse(I.getType());
2253 return true;
2254 }
2255 // Implicit null checks act as unconditional branches and their comparisons
2256 // should be treated as simplified and free of cost.
2257 if (isImplicitNullCheckCmp(I))
2258 return true;
2259 }
2260 return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
2261}
2262
2263bool CallAnalyzer::visitSub(BinaryOperator &I) {
2264 // Try to handle a special case: we can fold computing the difference of two
2265 // constant-related pointers.
2266 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2267 Value *LHSBase, *RHSBase;
2268 APInt LHSOffset, RHSOffset;
2269 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2270 if (LHSBase) {
2271 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2272 if (RHSBase && LHSBase == RHSBase) {
2273 // We have common bases, fold the subtract to a constant based on the
2274 // offsets.
2275 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
2276 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
2277 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
2278 SimplifiedValues[&I] = C;
2279 ++NumConstantPtrDiffs;
2280 return true;
2281 }
2282 }
2283 }
2284
2285 // Otherwise, fall back to the generic logic for simplifying and handling
2286 // instructions.
2287 return Base::visitSub(I);
2288}
2289
2290bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
2291 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2292 Constant *CLHS = getDirectOrSimplifiedValue<Constant>(LHS);
2293 Constant *CRHS = getDirectOrSimplifiedValue<Constant>(RHS);
2294
2295 Value *SimpleV = nullptr;
2296 if (auto FI = dyn_cast<FPMathOperator>(&I))
2297 SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
2298 FI->getFastMathFlags(), DL);
2299 else
2300 SimpleV =
2301 simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
2302
2303 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2304 SimplifiedValues[&I] = C;
2305
2306 if (SimpleV)
2307 return true;
2308
2309 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
2310 disableSROA(LHS);
2311 disableSROA(RHS);
2312
2313 // If the instruction is floating point, and the target says this operation
2314 // is expensive, this may eventually become a library call. Treat the cost
2315 // as such. Unless it's fneg which can be implemented with an xor.
2316 using namespace llvm::PatternMatch;
2317 if (I.getType()->isFloatingPointTy() &&
2319 !match(&I, m_FNeg(m_Value())))
2320 onCallPenalty();
2321
2322 return false;
2323}
2324
2325bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
2326 Value *Op = I.getOperand(0);
2327 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
2328
2329 Value *SimpleV = simplifyFNegInst(
2330 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
2331
2332 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2333 SimplifiedValues[&I] = C;
2334
2335 if (SimpleV)
2336 return true;
2337
2338 // Disable any SROA on arguments to arbitrary, unsimplified fneg.
2339 disableSROA(Op);
2340
2341 return false;
2342}
2343
2344bool CallAnalyzer::visitLoad(LoadInst &I) {
2345 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2346 return true;
2347
2348 // If the data is already loaded from this address and hasn't been clobbered
2349 // by any stores or calls, this load is likely to be redundant and can be
2350 // eliminated.
2351 if (EnableLoadElimination &&
2352 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
2353 onLoadEliminationOpportunity();
2354 return true;
2355 }
2356
2357 onMemAccess();
2358 return false;
2359}
2360
2361bool CallAnalyzer::visitStore(StoreInst &I) {
2362 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2363 return true;
2364
2365 // The store can potentially clobber loads and prevent repeated loads from
2366 // being eliminated.
2367 // FIXME:
2368 // 1. We can probably keep an initial set of eliminatable loads substracted
2369 // from the cost even when we finally see a store. We just need to disable
2370 // *further* accumulation of elimination savings.
2371 // 2. We should probably at some point thread MemorySSA for the callee into
2372 // this and then use that to actually compute *really* precise savings.
2373 disableLoadElimination();
2374
2375 onMemAccess();
2376 return false;
2377}
2378
2379bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
2380 Value *Op = I.getAggregateOperand();
2381
2382 // Special handling, because we want to simplify extractvalue with a
2383 // potential insertvalue from the caller.
2384 if (Value *SimpleOp = getSimplifiedValueUnchecked(Op)) {
2385 SimplifyQuery SQ(DL);
2386 Value *SimpleV = simplifyExtractValueInst(SimpleOp, I.getIndices(), SQ);
2387 if (SimpleV) {
2388 SimplifiedValues[&I] = SimpleV;
2389 return true;
2390 }
2391 }
2392
2393 // SROA can't look through these, but they may be free.
2394 return Base::visitExtractValue(I);
2395}
2396
2397bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
2398 // Constant folding for insert value is trivial.
2400 return true;
2401
2402 // SROA can't look through these, but they may be free.
2403 return Base::visitInsertValue(I);
2404}
2405
2406/// Try to simplify a call site.
2407///
2408/// Takes a concrete function and callsite and tries to actually simplify it by
2409/// analyzing the arguments and call itself with instsimplify. Returns true if
2410/// it has simplified the callsite to some other entity (a constant), making it
2411/// free.
2412bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
2413 // FIXME: Using the instsimplify logic directly for this is inefficient
2414 // because we have to continually rebuild the argument list even when no
2415 // simplifications can be performed. Until that is fixed with remapping
2416 // inside of instsimplify, directly constant fold calls here.
2418 return false;
2419
2420 // Try to re-map the arguments to constants.
2421 SmallVector<Constant *, 4> ConstantArgs;
2422 ConstantArgs.reserve(Call.arg_size());
2423 for (Value *I : Call.args()) {
2424 Constant *C = getDirectOrSimplifiedValue<Constant>(I);
2425 if (!C)
2426 return false; // This argument doesn't map to a constant.
2427
2428 ConstantArgs.push_back(C);
2429 }
2430 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2431 SimplifiedValues[&Call] = C;
2432 return true;
2433 }
2434
2435 return false;
2436}
2437
2438bool CallAnalyzer::isLoweredToCall(Function *F, CallBase &Call) {
2439 const TargetLibraryInfo *TLI = GetTLI ? &GetTLI(*F) : nullptr;
2440 LibFunc LF;
2441 if (!TLI || !TLI->getLibFunc(*F, LF) || !TLI->has(LF))
2442 return TTI.isLoweredToCall(F);
2443
2444 switch (LF) {
2445 case LibFunc_memcpy_chk:
2446 case LibFunc_memmove_chk:
2447 case LibFunc_mempcpy_chk:
2448 case LibFunc_memset_chk: {
2449 // Calls to __memcpy_chk whose length is known to fit within the object
2450 // size will eventually be replaced by inline stores. Therefore, these
2451 // should not incur a call penalty. This is only really relevant on
2452 // platforms whose headers redirect memcpy to __memcpy_chk (e.g. Darwin), as
2453 // other platforms use memcpy intrinsics, which are already exempt from the
2454 // call penalty.
2455 auto *LenOp = getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(2));
2456 auto *ObjSizeOp =
2457 getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(3));
2458 if (LenOp && ObjSizeOp &&
2459 LenOp->getLimitedValue() <= ObjSizeOp->getLimitedValue()) {
2460 return false;
2461 }
2462 break;
2463 }
2464 default:
2465 break;
2466 }
2467
2468 return TTI.isLoweredToCall(F);
2469}
2470
2471bool CallAnalyzer::visitCallBase(CallBase &Call) {
2472 if (!onCallBaseVisitStart(Call))
2473 return true;
2474
2475 if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
2476 !F.hasFnAttribute(Attribute::ReturnsTwice)) {
2477 // This aborts the entire analysis.
2478 ExposesReturnsTwice = true;
2479 return false;
2480 }
2481 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
2482 ContainsNoDuplicateCall = true;
2483
2484 if (InlineAsm *InlineAsmOp = dyn_cast<InlineAsm>(Call.getCalledOperand()))
2485 onInlineAsm(*InlineAsmOp);
2486
2488 bool IsIndirectCall = !F;
2489 if (IsIndirectCall) {
2490 // Check if this happens to be an indirect function call to a known function
2491 // in this inline context. If not, we've done all we can.
2493 F = getSimplifiedValue<Function>(Callee);
2494 if (!F || F->getFunctionType() != Call.getFunctionType()) {
2495 onCallArgumentSetup(Call);
2496
2497 if (!Call.onlyReadsMemory())
2498 disableLoadElimination();
2499 return Base::visitCallBase(Call);
2500 }
2501 }
2502
2503 assert(F && "Expected a call to a known function");
2504
2505 // When we have a concrete function, first try to simplify it directly.
2506 if (simplifyCallSite(F, Call))
2507 return true;
2508
2509 // Next check if it is an intrinsic we know about.
2510 // FIXME: Lift this into part of the InstVisitor.
2511 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
2512 switch (II->getIntrinsicID()) {
2513 default:
2515 disableLoadElimination();
2516 return Base::visitCallBase(Call);
2517
2518 case Intrinsic::load_relative:
2519 onLoadRelativeIntrinsic();
2520 return false;
2521
2522 case Intrinsic::memset:
2523 case Intrinsic::memcpy:
2524 case Intrinsic::memmove:
2525 disableLoadElimination();
2526 // SROA can usually chew through these intrinsics, but they aren't free.
2527 return false;
2528 case Intrinsic::icall_branch_funnel:
2529 case Intrinsic::localescape:
2530 HasUninlineableIntrinsic = true;
2531 return false;
2532 case Intrinsic::vastart:
2533 InitsVargArgs = true;
2534 return false;
2535 case Intrinsic::launder_invariant_group:
2536 case Intrinsic::strip_invariant_group:
2537 if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2538 SROAArgValues[II] = SROAArg;
2539 return true;
2540 case Intrinsic::is_constant:
2541 return simplifyIntrinsicCallIsConstant(Call);
2542 case Intrinsic::objectsize:
2543 return simplifyIntrinsicCallObjectSize(Call);
2544 }
2545 }
2546
2547 if (F == Call.getFunction()) {
2548 // This flag will fully abort the analysis, so don't bother with anything
2549 // else.
2550 IsRecursiveCall = true;
2551 if (!AllowRecursiveCall)
2552 return false;
2553 }
2554
2555 if (isLoweredToCall(F, Call)) {
2556 onLoweredCall(F, Call, IsIndirectCall);
2557 }
2558
2559 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2560 disableLoadElimination();
2561 return Base::visitCallBase(Call);
2562}
2563
2564bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
2565 // At least one return instruction will be free after inlining.
2566 bool Free = !HasReturn;
2567 HasReturn = true;
2568 return Free;
2569}
2570
2571bool CallAnalyzer::visitUncondBrInst(UncondBrInst &BI) {
2572 // We model unconditional branches as essentially free -- they really
2573 // shouldn't exist at all, but handling them makes the behavior of the
2574 // inliner more regular and predictable.
2575 return true;
2576}
2577
2578bool CallAnalyzer::visitCondBrInst(CondBrInst &BI) {
2579 // Conditional branches which will fold away are free.
2580 return getDirectOrSimplifiedValue<ConstantInt>(BI.getCondition()) ||
2581 BI.getMetadata(LLVMContext::MD_make_implicit);
2582}
2583
2584bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
2585 bool CheckSROA = SI.getType()->isPointerTy();
2586 Value *TrueVal = SI.getTrueValue();
2587 Value *FalseVal = SI.getFalseValue();
2588
2589 Constant *TrueC = getDirectOrSimplifiedValue<Constant>(TrueVal);
2590 Constant *FalseC = getDirectOrSimplifiedValue<Constant>(FalseVal);
2591 Constant *CondC = getSimplifiedValue<Constant>(SI.getCondition());
2592
2593 if (!CondC) {
2594 // Select C, X, X => X
2595 if (TrueC == FalseC && TrueC) {
2596 SimplifiedValues[&SI] = TrueC;
2597 return true;
2598 }
2599
2600 if (!CheckSROA)
2601 return Base::visitSelectInst(SI);
2602
2603 std::pair<Value *, APInt> TrueBaseAndOffset =
2604 ConstantOffsetPtrs.lookup(TrueVal);
2605 std::pair<Value *, APInt> FalseBaseAndOffset =
2606 ConstantOffsetPtrs.lookup(FalseVal);
2607 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
2608 ConstantOffsetPtrs[&SI] = std::move(TrueBaseAndOffset);
2609
2610 if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
2611 SROAArgValues[&SI] = SROAArg;
2612 return true;
2613 }
2614
2615 return Base::visitSelectInst(SI);
2616 }
2617
2618 // Select condition is a constant.
2619 Value *SelectedV = CondC->isAllOnesValue() ? TrueVal
2620 : (CondC->isNullValue()) ? FalseVal
2621 : nullptr;
2622 if (!SelectedV) {
2623 // Condition is a vector constant that is not all 1s or all 0s. If all
2624 // operands are constants, ConstantFoldSelectInstruction() can handle the
2625 // cases such as select vectors.
2626 if (TrueC && FalseC) {
2627 if (auto *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC)) {
2628 SimplifiedValues[&SI] = C;
2629 return true;
2630 }
2631 }
2632 return Base::visitSelectInst(SI);
2633 }
2634
2635 // Condition is either all 1s or all 0s. SI can be simplified.
2636 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
2637 SimplifiedValues[&SI] = SelectedC;
2638 return true;
2639 }
2640
2641 if (!CheckSROA)
2642 return true;
2643
2644 std::pair<Value *, APInt> BaseAndOffset =
2645 ConstantOffsetPtrs.lookup(SelectedV);
2646 if (BaseAndOffset.first) {
2647 ConstantOffsetPtrs[&SI] = std::move(BaseAndOffset);
2648
2649 if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
2650 SROAArgValues[&SI] = SROAArg;
2651 }
2652
2653 return true;
2654}
2655
2656bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
2657 // We model unconditional switches as free, see the comments on handling
2658 // branches.
2659 if (getDirectOrSimplifiedValue<ConstantInt>(SI.getCondition()))
2660 return true;
2661
2662 // Assume the most general case where the switch is lowered into
2663 // either a jump table, bit test, or a balanced binary tree consisting of
2664 // case clusters without merging adjacent clusters with the same
2665 // destination. We do not consider the switches that are lowered with a mix
2666 // of jump table/bit test/binary search tree. The cost of the switch is
2667 // proportional to the size of the tree or the size of jump table range.
2668 //
2669 // NB: We convert large switches which are just used to initialize large phi
2670 // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
2671 // inlining those. It will prevent inlining in cases where the optimization
2672 // does not (yet) fire.
2673
2674 unsigned JumpTableSize = 0;
2675 BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2676 unsigned NumCaseCluster =
2677 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2678
2679 onFinalizeSwitch(JumpTableSize, NumCaseCluster, SI.defaultDestUnreachable());
2680 return false;
2681}
2682
2683bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
2684 // We never want to inline functions that contain an indirectbr. This is
2685 // incorrect because all the blockaddress's (in static global initializers
2686 // for example) would be referring to the original function, and this
2687 // indirect jump would jump from the inlined copy of the function into the
2688 // original function which is extremely undefined behavior.
2689 // FIXME: This logic isn't really right; we can safely inline functions with
2690 // indirectbr's as long as no other function or global references the
2691 // blockaddress of a block within the current function.
2692 HasIndirectBr = true;
2693 return false;
2694}
2695
2696bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
2697 // FIXME: It's not clear that a single instruction is an accurate model for
2698 // the inline cost of a resume instruction.
2699 return false;
2700}
2701
2702bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
2703 // FIXME: It's not clear that a single instruction is an accurate model for
2704 // the inline cost of a cleanupret instruction.
2705 return false;
2706}
2707
2708bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
2709 // FIXME: It's not clear that a single instruction is an accurate model for
2710 // the inline cost of a catchret instruction.
2711 return false;
2712}
2713
2714bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
2715 // FIXME: It might be reasonably to discount the cost of instructions leading
2716 // to unreachable as they have the lowest possible impact on both runtime and
2717 // code size.
2718 return true; // No actual code is needed for unreachable.
2719}
2720
2721bool CallAnalyzer::visitInstruction(Instruction &I) {
2722 // Some instructions are free. All of the free intrinsics can also be
2723 // handled by SROA, etc.
2726 return true;
2727
2728 // We found something we don't understand or can't handle. Mark any SROA-able
2729 // values in the operand list as no longer viable.
2730 for (const Use &Op : I.operands())
2731 disableSROA(Op);
2732
2733 return false;
2734}
2735
2736/// Analyze a basic block for its contribution to the inline cost.
2737///
2738/// This method walks the analyzer over every instruction in the given basic
2739/// block and accounts for their cost during inlining at this callsite. It
2740/// aborts early if the threshold has been exceeded or an impossible to inline
2741/// construct has been detected. It returns false if inlining is no longer
2742/// viable, and true if inlining remains viable.
2743InlineResult
2744CallAnalyzer::analyzeBlock(BasicBlock *BB,
2745 const SmallPtrSetImpl<const Value *> &EphValues) {
2746 for (Instruction &I : *BB) {
2747 // FIXME: Currently, the number of instructions in a function regardless of
2748 // our ability to simplify them during inline to constants or dead code,
2749 // are actually used by the vector bonus heuristic. As long as that's true,
2750 // we have to special case debug intrinsics here to prevent differences in
2751 // inlining due to debug symbols. Eventually, the number of unsimplified
2752 // instructions shouldn't factor into the cost computation, but until then,
2753 // hack around it here.
2754 // Similarly, skip pseudo-probes.
2755 if (I.isDebugOrPseudoInst())
2756 continue;
2757
2758 // Skip ephemeral values.
2759 if (EphValues.count(&I))
2760 continue;
2761
2762 ++NumInstructions;
2763 if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
2764 ++NumVectorInstructions;
2765
2766 // If the instruction simplified to a constant, there is no cost to this
2767 // instruction. Visit the instructions using our InstVisitor to account for
2768 // all of the per-instruction logic. The visit tree returns true if we
2769 // consumed the instruction in any way, and false if the instruction's base
2770 // cost should count against inlining.
2771 onInstructionAnalysisStart(&I);
2772
2773 if (Base::visit(&I))
2774 ++NumInstructionsSimplified;
2775 else
2776 onMissedSimplification();
2777
2778 onInstructionAnalysisFinish(&I);
2779 using namespace ore;
2780 // If the visit this instruction detected an uninlinable pattern, abort.
2781 InlineResult IR = InlineResult::success();
2782 if (IsRecursiveCall && !AllowRecursiveCall)
2783 IR = InlineResult::failure("recursive");
2784 else if (ExposesReturnsTwice)
2785 IR = InlineResult::failure("exposes returns twice");
2786 else if (HasDynamicAlloca)
2787 IR = InlineResult::failure("dynamic alloca");
2788 else if (HasIndirectBr)
2789 IR = InlineResult::failure("indirect branch");
2790 else if (HasUninlineableIntrinsic)
2791 IR = InlineResult::failure("uninlinable intrinsic");
2792 else if (InitsVargArgs)
2793 IR = InlineResult::failure("varargs");
2794 if (!IR.isSuccess()) {
2795 if (ORE)
2796 ORE->emit([&]() {
2797 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2798 &CandidateCall)
2799 << NV("Callee", &F) << " has uninlinable pattern ("
2800 << NV("InlineResult", IR.getFailureReason())
2801 << ") and cost is not fully computed";
2802 });
2803 return IR;
2804 }
2805
2806 // If the caller is a recursive function then we don't want to inline
2807 // functions which allocate a lot of stack space because it would increase
2808 // the caller stack usage dramatically.
2809 if (IsCallerRecursive && AllocatedSize > RecurStackSizeThreshold) {
2810 auto IR =
2811 InlineResult::failure("recursive and allocates too much stack space");
2812 if (ORE)
2813 ORE->emit([&]() {
2814 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2815 &CandidateCall)
2816 << NV("Callee", &F) << " is "
2817 << NV("InlineResult", IR.getFailureReason())
2818 << ". Cost is not fully computed";
2819 });
2820 return IR;
2821 }
2822
2823 if (shouldStop())
2824 return InlineResult::failure(
2825 "Call site analysis is not favorable to inlining.");
2826 }
2827
2828 return InlineResult::success();
2829}
2830
2831/// Compute the base pointer and cumulative constant offsets for V.
2832///
2833/// This strips all constant offsets off of V, leaving it the base pointer, and
2834/// accumulates the total constant offset applied in the returned constant. It
2835/// returns 0 if V is not a pointer, and returns the constant '0' if there are
2836/// no constant offsets applied.
2837ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
2838 if (!V->getType()->isPointerTy())
2839 return nullptr;
2840
2841 unsigned AS = V->getType()->getPointerAddressSpace();
2842 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2843 APInt Offset = APInt::getZero(IntPtrWidth);
2844
2845 // Even though we don't look through PHI nodes, we could be called on an
2846 // instruction in an unreachable block, which may be on a cycle.
2847 SmallPtrSet<Value *, 4> Visited;
2848 Visited.insert(V);
2849 do {
2850 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2851 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
2852 return nullptr;
2853 V = GEP->getPointerOperand();
2854 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2855 if (GA->isInterposable())
2856 break;
2857 V = GA->getAliasee();
2858 } else {
2859 break;
2860 }
2861 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2862 } while (Visited.insert(V).second);
2863
2864 Type *IdxPtrTy = DL.getIndexType(V->getType());
2865 return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
2866}
2867
2868/// Find dead blocks due to deleted CFG edges during inlining.
2869///
2870/// If we know the successor of the current block, \p CurrBB, has to be \p
2871/// NextBB, the other successors of \p CurrBB are dead if these successors have
2872/// no live incoming CFG edges. If one block is found to be dead, we can
2873/// continue growing the dead block list by checking the successors of the dead
2874/// blocks to see if all their incoming edges are dead or not.
2875void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
2876 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
2877 // A CFG edge is dead if the predecessor is dead or the predecessor has a
2878 // known successor which is not the one under exam.
2879 if (DeadBlocks.count(Pred))
2880 return true;
2881 BasicBlock *KnownSucc = KnownSuccessors[Pred];
2882 return KnownSucc && KnownSucc != Succ;
2883 };
2884
2885 auto IsNewlyDead = [&](BasicBlock *BB) {
2886 // If all the edges to a block are dead, the block is also dead.
2887 return (!DeadBlocks.count(BB) &&
2889 [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
2890 };
2891
2892 for (BasicBlock *Succ : successors(CurrBB)) {
2893 if (Succ == NextBB || !IsNewlyDead(Succ))
2894 continue;
2896 NewDead.push_back(Succ);
2897 while (!NewDead.empty()) {
2898 BasicBlock *Dead = NewDead.pop_back_val();
2899 if (DeadBlocks.insert(Dead).second)
2900 // Continue growing the dead block lists.
2901 for (BasicBlock *S : successors(Dead))
2902 if (IsNewlyDead(S))
2903 NewDead.push_back(S);
2904 }
2905 }
2906}
2907
2908/// Analyze a call site for potential inlining.
2909///
2910/// Returns true if inlining this call is viable, and false if it is not
2911/// viable. It computes the cost and adjusts the threshold based on numerous
2912/// factors and heuristics. If this method returns false but the computed cost
2913/// is below the computed threshold, then inlining was forcibly disabled by
2914/// some artifact of the routine.
2915InlineResult CallAnalyzer::analyze() {
2916 ++NumCallsAnalyzed;
2917
2918 auto Result = onAnalysisStart();
2919 if (!Result.isSuccess())
2920 return Result;
2921
2922 if (F.empty())
2923 return InlineResult::success();
2924
2925 Function *Caller = CandidateCall.getFunction();
2926 // Check if the caller function is recursive itself.
2927 for (User *U : Caller->users()) {
2928 CallBase *Call = dyn_cast<CallBase>(U);
2929 if (Call && Call->getFunction() == Caller) {
2930 IsCallerRecursive = true;
2931 break;
2932 }
2933 }
2934
2935 // Populate our simplified values by mapping from function arguments to call
2936 // arguments with known important simplifications.
2937 auto CAI = CandidateCall.arg_begin();
2938 for (Argument &FAI : F.args()) {
2939 assert(CAI != CandidateCall.arg_end());
2940 SimplifiedValues[&FAI] = *CAI;
2941 if (isa<Constant>(*CAI))
2942 ++NumConstantArgs;
2943
2944 Value *PtrArg = *CAI;
2945 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
2946 ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
2947
2948 // We can SROA any pointer arguments derived from alloca instructions.
2949 if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
2950 SROAArgValues[&FAI] = SROAArg;
2951 onInitializeSROAArg(SROAArg);
2952 EnabledSROAAllocas.insert(SROAArg);
2953 }
2954 }
2955 ++CAI;
2956 }
2957 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
2958 NumAllocaArgs = SROAArgValues.size();
2959
2960 // Collecting the ephemeral values of `F` can be expensive, so use the
2961 // ephemeral values cache if available.
2962 SmallPtrSet<const Value *, 32> EphValuesStorage;
2963 const SmallPtrSetImpl<const Value *> *EphValues = &EphValuesStorage;
2964 if (GetEphValuesCache)
2965 EphValues = &GetEphValuesCache(F).ephValues();
2966 else
2967 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F),
2968 EphValuesStorage);
2969
2970 // The worklist of live basic blocks in the callee *after* inlining. We avoid
2971 // adding basic blocks of the callee which can be proven to be dead for this
2972 // particular call site in order to get more accurate cost estimates. This
2973 // requires a somewhat heavyweight iteration pattern: we need to walk the
2974 // basic blocks in a breadth-first order as we insert live successors. To
2975 // accomplish this, prioritizing for small iterations because we exit after
2976 // crossing our threshold, we use a small-size optimized SetVector.
2977 typedef SmallSetVector<BasicBlock *, 16> BBSetVector;
2978 BBSetVector BBWorklist;
2979 BBWorklist.insert(&F.getEntryBlock());
2980
2981 // Note that we *must not* cache the size, this loop grows the worklist.
2982 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
2983 if (shouldStop())
2984 break;
2985
2986 BasicBlock *BB = BBWorklist[Idx];
2987 if (BB->empty())
2988 continue;
2989
2990 onBlockStart(BB);
2991
2992 // Disallow inlining a blockaddress.
2993 // A blockaddress only has defined behavior for an indirect branch in the
2994 // same function, and we do not currently support inlining indirect
2995 // branches. But, the inliner may not see an indirect branch that ends up
2996 // being dead code at a particular call site. If the blockaddress escapes
2997 // the function, e.g., via a global variable, inlining may lead to an
2998 // invalid cross-function reference.
2999 // FIXME: pr/39560: continue relaxing this overt restriction.
3000 if (BB->hasAddressTaken())
3001 return InlineResult::failure("blockaddress used");
3002
3003 // Analyze the cost of this block. If we blow through the threshold, this
3004 // returns false, and we can bail on out.
3005 InlineResult IR = analyzeBlock(BB, *EphValues);
3006 if (!IR.isSuccess())
3007 return IR;
3008
3009 Instruction *TI = BB->getTerminator();
3010
3011 // Add in the live successors by first checking whether we have terminator
3012 // that may be simplified based on the values simplified by this call.
3013 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
3014 Value *Cond = BI->getCondition();
3015 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
3016 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
3017 BBWorklist.insert(NextBB);
3018 KnownSuccessors[BB] = NextBB;
3019 findDeadBlocks(BB, NextBB);
3020 continue;
3021 }
3022 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3023 Value *Cond = SI->getCondition();
3024 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
3025 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
3026 BBWorklist.insert(NextBB);
3027 KnownSuccessors[BB] = NextBB;
3028 findDeadBlocks(BB, NextBB);
3029 continue;
3030 }
3031 }
3032
3033 // If we're unable to select a particular successor, just count all of
3034 // them.
3035 BBWorklist.insert_range(successors(BB));
3036
3037 onBlockAnalyzed(BB);
3038 }
3039
3040 // If this is a noduplicate call, we can still inline as long as
3041 // inlining this would cause the removal of the caller (so the instruction
3042 // is not actually duplicated, just moved).
3043 if (!isSoleCallToLocalFunction(CandidateCall, F) && ContainsNoDuplicateCall)
3044 return InlineResult::failure("noduplicate");
3045
3046 // If the callee's stack size exceeds the user-specified threshold,
3047 // do not let it be inlined.
3048 // The command line option overrides a limit set in the function attributes.
3049 size_t FinalStackSizeThreshold = StackSizeThreshold;
3050 if (!StackSizeThreshold.getNumOccurrences())
3051 if (std::optional<int> AttrMaxStackSize = getStringFnAttrAsInt(
3053 FinalStackSizeThreshold = *AttrMaxStackSize;
3054 if (AllocatedSize > FinalStackSizeThreshold)
3055 return InlineResult::failure("stacksize");
3056
3057 return finalizeAnalysis();
3058}
3059
3060void InlineCostCallAnalyzer::print(raw_ostream &OS) {
3061#define DEBUG_PRINT_STAT(x) OS << " " #x ": " << x << "\n"
3063 F.print(OS, &Writer);
3064 DEBUG_PRINT_STAT(NumConstantArgs);
3065 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
3066 DEBUG_PRINT_STAT(NumAllocaArgs);
3067 DEBUG_PRINT_STAT(NumConstantPtrCmps);
3068 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
3069 DEBUG_PRINT_STAT(NumInstructionsSimplified);
3070 DEBUG_PRINT_STAT(NumInstructions);
3071 DEBUG_PRINT_STAT(NumInlineAsmInstructions);
3072 DEBUG_PRINT_STAT(SROACostSavings);
3073 DEBUG_PRINT_STAT(SROACostSavingsLost);
3074 DEBUG_PRINT_STAT(LoadEliminationCost);
3075 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
3077 DEBUG_PRINT_STAT(Threshold);
3078#undef DEBUG_PRINT_STAT
3079}
3080
3081#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3082/// Dump stats about this call's analysis.
3083LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
3084#endif
3085
3086/// Test that there are no attribute conflicts between Caller and Callee
3087/// that prevent inlining.
3089 Function *Caller, Function *Callee,
3090 function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
3091 // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
3092 // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
3093 // object, and always returns the same object (which is overwritten on each
3094 // GetTLI call). Therefore we copy the first result.
3095 auto CalleeTLI = GetTLI(*Callee);
3096 return GetTLI(*Caller).areInlineCompatible(CalleeTLI,
3098 AttributeFuncs::areInlineCompatible(*Caller, *Callee);
3099}
3100
3102 const DataLayout &DL) {
3103 int64_t Cost = 0;
3104 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
3105 if (Call.isByValArgument(I)) {
3106 // We approximate the number of loads and stores needed by dividing the
3107 // size of the byval type by the target's pointer size.
3108 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
3109 unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
3110 unsigned AS = PTy->getAddressSpace();
3111 unsigned PointerSize = DL.getPointerSizeInBits(AS);
3112 // Ceiling division.
3113 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
3114
3115 // If it generates more than 8 stores it is likely to be expanded as an
3116 // inline memcpy so we take that as an upper bound. Otherwise we assume
3117 // one load and one store per word copied.
3118 // FIXME: The maxStoresPerMemcpy setting from the target should be used
3119 // here instead of a magic number of 8, but it's not available via
3120 // DataLayout.
3121 NumStores = std::min(NumStores, 8U);
3122
3123 Cost += 2 * NumStores * InstrCost;
3124 } else {
3125 // For non-byval arguments subtract off one instruction per call
3126 // argument.
3127 Cost += InstrCost;
3128 }
3129 }
3130 // The call instruction also disappears after inlining.
3131 Cost += InstrCost;
3132 Cost += TTI.getInlineCallPenalty(Call.getCaller(), Call, CallPenalty);
3133
3134 return std::min<int64_t>(Cost, INT_MAX);
3135}
3136
3138 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
3139 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3140 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3143 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3144 return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
3145 GetAssumptionCache, GetTLI, GetBFI, PSI, ORE,
3146 GetEphValuesCache);
3147}
3148
3150 CallBase &Call, TargetTransformInfo &CalleeTTI,
3151 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3153 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3155 const InlineParams Params = {/* DefaultThreshold*/ 0,
3156 /*HintThreshold*/ {},
3157 /*OptSizeHintThreshold*/ {},
3158 /*ColdThreshold*/ {},
3159 /*OptSizeThreshold*/ {},
3160 /*OptMinSizeThreshold*/ {},
3161 /*HotCallSiteThreshold*/ {},
3162 /*LocallyHotCallSiteThreshold*/ {},
3163 /*ColdCallSiteThreshold*/ {},
3164 /*ComputeFullInlineCost*/ true,
3165 /*EnableDeferral*/ true};
3166
3167 InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
3168 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE, true,
3169 /*IgnoreThreshold*/ true);
3170 auto R = CA.analyze();
3171 if (!R.isSuccess())
3172 return std::nullopt;
3173 return CA.getCost();
3174}
3175
3176std::optional<InlineCostFeatures> llvm::getInliningCostFeatures(
3177 CallBase &Call, TargetTransformInfo &CalleeTTI,
3178 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3180 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3182 InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, GetTLI,
3183 PSI, ORE, *Call.getCalledFunction(), Call);
3184 auto R = CFA.analyze();
3185 if (!R.isSuccess())
3186 return std::nullopt;
3187 return CFA.features();
3188}
3189
3191 CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
3192 function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
3193
3194 // Cannot inline indirect calls.
3195 if (!Callee)
3196 return InlineResult::failure("indirect call");
3197
3198 // When callee coroutine function is inlined into caller coroutine function
3199 // before coro-split pass,
3200 // coro-early pass can not handle this quiet well.
3201 // So we won't inline the coroutine function if it have not been unsplited
3202 if (Callee->isPresplitCoroutine())
3203 return InlineResult::failure("unsplited coroutine call");
3204
3205 // Inlining into a function with less target features is unsound, so enforce
3206 // this even if alwaysinline is used.
3207 Function *Caller = Call.getCaller();
3209 !CalleeTTI.areInlineCompatible(Caller, Callee))
3210 return InlineResult::failure("conflicting target features");
3211
3212 // Calls to functions with always-inline attributes should be inlined
3213 // whenever possible.
3214 if (Call.hasFnAttr(Attribute::AlwaysInline)) {
3215 if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
3216 return InlineResult::failure("noinline call site attribute");
3217
3218 if (!AttributeFuncs::isStrictFPInlineCompatible(*Caller, *Callee))
3219 return InlineResult::failure("incompatible strictfp attributes");
3220
3221 auto IsViable = isInlineViable(*Callee);
3222 if (IsViable.isSuccess())
3223 return InlineResult::success();
3224 return InlineResult::failure(IsViable.getFailureReason());
3225 }
3226
3227 // Never inline functions with conflicting attributes (unless callee has
3228 // always-inline attribute).
3229 if (!functionsHaveCompatibleAttributes(Caller, Callee, GetTLI))
3230 return InlineResult::failure("conflicting attributes");
3231
3232 // Flatten: inline all viable calls from flatten functions regardless of cost.
3233 // Checked before optnone so that flatten takes priority.
3234 if (Caller->hasFnAttribute(Attribute::Flatten)) {
3235 auto IsViable = isInlineViable(*Callee);
3236 if (IsViable.isSuccess())
3237 return InlineResult::success();
3238 return InlineResult::failure(IsViable.getFailureReason());
3239 }
3240
3241 // Don't inline this call if the caller has the optnone attribute.
3242 if (Caller->hasOptNone())
3243 return InlineResult::failure("optnone attribute");
3244
3245 // Don't inline functions which can be interposed at link-time.
3246 if (Callee->isInterposable(/*CheckNoIPA=*/false))
3247 return InlineResult::failure("interposable");
3248
3249 // Don't inline functions marked noinline.
3250 if (Callee->hasFnAttribute(Attribute::NoInline))
3251 return InlineResult::failure("noinline function attribute");
3252
3253 // Don't inline call sites marked noinline.
3254 if (Call.isNoInline())
3255 return InlineResult::failure("noinline call site attribute");
3256
3257 // Don't inline functions that are loader replaceable.
3258 if (Callee->hasFnAttribute("loader-replaceable"))
3259 return InlineResult::failure("loader replaceable function attribute");
3260
3261 return std::nullopt;
3262}
3263
3265 CallBase &Call, Function *Callee, const InlineParams &Params,
3266 TargetTransformInfo &CalleeTTI,
3267 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3268 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3271 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3272
3273 auto UserDecision =
3274 llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
3275
3276 if (UserDecision) {
3277 if (UserDecision->isSuccess())
3278 return llvm::InlineCost::getAlways("always inline attribute");
3279 return llvm::InlineCost::getNever(UserDecision->getFailureReason());
3280 }
3281
3284 "Inlining forced by -inline-all-viable-calls");
3285
3286 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
3287 << "... (caller:" << Call.getCaller()->getName()
3288 << ")\n");
3289
3290 InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
3291 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
3292 /*BoostIndirect=*/true, /*IgnoreThreshold=*/false,
3293 GetEphValuesCache);
3294 InlineResult ShouldInline = CA.analyze();
3295
3296 LLVM_DEBUG(CA.dump());
3297
3298 // Always make cost benefit based decision explicit.
3299 // We use always/never here since threshold is not meaningful,
3300 // as it's not what drives cost-benefit analysis.
3301 if (CA.wasDecidedByCostBenefit()) {
3302 if (ShouldInline.isSuccess())
3303 return InlineCost::getAlways("benefit over cost",
3304 CA.getCostBenefitPair());
3305 else
3306 return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
3307 }
3308
3309 if (CA.wasDecidedByCostThreshold())
3310 return InlineCost::get(CA.getCost(), CA.getThreshold(),
3311 CA.getStaticBonusApplied());
3312
3313 // No details on how the decision was made, simply return always or never.
3314 return ShouldInline.isSuccess()
3315 ? InlineCost::getAlways("empty function")
3316 : InlineCost::getNever(ShouldInline.getFailureReason());
3317}
3318
3320 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
3321 for (BasicBlock &BB : F) {
3322 // Disallow inlining of functions which contain indirect branches.
3324 return InlineResult::failure("contains indirect branches");
3325
3326 // Disallow inlining of blockaddresses.
3327 if (BB.hasAddressTaken())
3328 return InlineResult::failure("blockaddress used");
3329
3330 for (auto &II : BB) {
3332 if (!Call)
3333 continue;
3334
3335 // Disallow recursive calls.
3336 Function *Callee = Call->getCalledFunction();
3337 if (&F == Callee)
3338 return InlineResult::failure("recursive call");
3339
3340 // Disallow calls which expose returns-twice to a function not previously
3341 // attributed as such.
3342 if (!ReturnsTwice && isa<CallInst>(Call) &&
3343 cast<CallInst>(Call)->canReturnTwice())
3344 return InlineResult::failure("exposes returns-twice attribute");
3345
3346 if (Callee)
3347 switch (Callee->getIntrinsicID()) {
3348 default:
3349 break;
3350 case llvm::Intrinsic::icall_branch_funnel:
3351 // Disallow inlining of @llvm.icall.branch.funnel because current
3352 // backend can't separate call targets from call arguments.
3353 return InlineResult::failure(
3354 "disallowed inlining of @llvm.icall.branch.funnel");
3355 case llvm::Intrinsic::localescape:
3356 // Disallow inlining functions that call @llvm.localescape. Doing this
3357 // correctly would require major changes to the inliner.
3358 return InlineResult::failure(
3359 "disallowed inlining of @llvm.localescape");
3360 case llvm::Intrinsic::vastart:
3361 // Disallow inlining of functions that initialize VarArgs with
3362 // va_start.
3363 return InlineResult::failure(
3364 "contains VarArgs initialized with va_start");
3365 }
3366 }
3367 }
3368
3369 return InlineResult::success();
3370}
3371
3372// APIs to create InlineParams based on command line flags and/or other
3373// parameters.
3374
3376 InlineParams Params;
3377
3378 // This field is the threshold to use for a callee by default. This is
3379 // derived from one or more of:
3380 // * optimization or size-optimization levels,
3381 // * a value passed to createFunctionInliningPass function, or
3382 // * the -inline-threshold flag.
3383 // If the -inline-threshold flag is explicitly specified, that is used
3384 // irrespective of anything else.
3385 if (InlineThreshold.getNumOccurrences() > 0)
3387 else
3388 Params.DefaultThreshold = Threshold;
3389
3390 // Set the HintThreshold knob from the -inlinehint-threshold.
3392 // Use same threshold for optsize by default.
3394
3395 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
3397
3398 // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3399 // populate LocallyHotCallSiteThreshold. Later, we populate
3400 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3401 // we know that optimization level is O3 (in the getInlineParams variant that
3402 // takes the opt and size levels).
3403 // FIXME: Remove this check (and make the assignment unconditional) after
3404 // addressing size regression issues at O2.
3405 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3407
3408 // Set the ColdCallSiteThreshold knob from the
3409 // -inline-cold-callsite-threshold.
3411
3412 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
3413 // -inlinehint-threshold commandline option is not explicitly given. If that
3414 // option is present, then its value applies even for callees with size and
3415 // minsize attributes.
3416 // If the -inline-threshold is not specified, set the ColdThreshold from the
3417 // -inlinecold-threshold even if it is not explicitly passed. If
3418 // -inline-threshold is specified, then -inlinecold-threshold needs to be
3419 // explicitly specified to set the ColdThreshold knob
3420 if (InlineThreshold.getNumOccurrences() == 0) {
3424 } else if (ColdThreshold.getNumOccurrences() > 0) {
3426 }
3427 return Params;
3428}
3429
3433
3435 auto Params =
3438 // At O3, use the value of -locally-hot-callsite-threshold option to populate
3439 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3440 // when it is specified explicitly.
3441 if (OptLevel > 2)
3443 return Params;
3444}
3445
3450 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
3451 [&](Function &F) -> AssumptionCache & {
3452 return FAM.getResult<AssumptionAnalysis>(F);
3453 };
3454
3455 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
3456 ProfileSummaryInfo *PSI =
3457 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3458 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
3459
3460 // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
3461 // In the current implementation, the type of InlineParams doesn't matter as
3462 // the pass serves only for verification of inliner's decisions.
3463 // We can add a flag which determines InlineParams for this run. Right now,
3464 // the default InlineParams are used.
3465 const InlineParams Params = llvm::getInlineParams();
3466 for (BasicBlock &BB : F) {
3467 for (Instruction &I : BB) {
3468 if (auto *CB = dyn_cast<CallBase>(&I)) {
3469 Function *CalledFunction = CB->getCalledFunction();
3470 if (!CalledFunction || CalledFunction->isDeclaration())
3471 continue;
3472 OptimizationRemarkEmitter ORE(CalledFunction);
3473 InlineCostCallAnalyzer ICCA(*CalledFunction, *CB, Params, TTI,
3474 GetAssumptionCache, nullptr, nullptr, PSI,
3475 &ORE);
3476 ICCA.analyze();
3477 OS << " Analyzing call of " << CalledFunction->getName()
3478 << "... (caller:" << CB->getCaller()->getName() << ")\n";
3479 ICCA.print(OS);
3480 OS << "\n";
3481 }
3482 }
3483 }
3484 return PreservedAnalyses::all();
3485}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:73
#define DEBUG_TYPE
static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
static cl::opt< int > InlineAsmInstrCost("inline-asm-instr-cost", cl::Hidden, cl::init(0), cl::desc("Cost of a single inline asm instruction when inlining"))
static cl::opt< int > InlineSavingsMultiplier("inline-savings-multiplier", cl::Hidden, cl::init(8), cl::desc("Multiplier to multiply cycle savings by during inlining"))
static cl::opt< int > InlineThreshold("inline-threshold", cl::Hidden, cl::init(225), cl::desc("Control the amount of inlining to perform (default = 225)"))
static cl::opt< int > CallPenalty("inline-call-penalty", cl::Hidden, cl::init(25), cl::desc("Call penalty that is applied per callsite when inlining"))
static cl::opt< int > HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), cl::desc("Threshold for hot callsites "))
static cl::opt< int > ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining functions with cold attribute"))
static cl::opt< size_t > RecurStackSizeThreshold("recursive-inline-max-stacksize", cl::Hidden, cl::init(InlineConstants::TotalAllocaSizeRecursiveCaller), cl::desc("Do not inline recursive functions with a stack " "size that exceeds the specified limit"))
static cl::opt< bool > PrintInstructionComments("print-instruction-comments", cl::Hidden, cl::init(false), cl::desc("Prints comments for instruction based on inline cost analysis"))
static cl::opt< int > LocallyHotCallSiteThreshold("locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::desc("Threshold for locally hot callsites "))
static cl::opt< bool > InlineCallerSupersetNoBuiltin("inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true), cl::desc("Allow inlining when caller has a superset of callee's nobuiltin " "attributes."))
static cl::opt< int > HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325), cl::desc("Threshold for inlining functions with inline hint"))
static cl::opt< size_t > StackSizeThreshold("inline-max-stacksize", cl::Hidden, cl::init(std::numeric_limits< size_t >::max()), cl::desc("Do not inline functions with a stack size " "that exceeds the specified limit"))
static cl::opt< uint64_t > HotCallSiteRelFreq("hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::desc("Minimum block frequency, expressed as a multiple of caller's " "entry frequency, for a callsite to be hot in the absence of " "profile information."))
static cl::opt< int > InlineSavingsProfitableMultiplier("inline-savings-profitable-multiplier", cl::Hidden, cl::init(4), cl::desc("A multiplier on top of cycle savings to decide whether the " "savings won't justify the cost"))
static cl::opt< int > MemAccessCost("inline-memaccess-cost", cl::Hidden, cl::init(0), cl::desc("Cost of load/store instruction when inlining"))
static cl::opt< int > ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining cold callsites"))
static cl::opt< bool > IgnoreTTIInlineCompatible("ignore-tti-inline-compatible", cl::Hidden, cl::init(false), cl::desc("Ignore TTI attributes compatibility check between callee/caller " "during inline cost calculation"))
static cl::opt< bool > OptComputeFullInlineCost("inline-cost-full", cl::Hidden, cl::desc("Compute the full inline cost of a call site even when the cost " "exceeds the threshold."))
#define DEBUG_PRINT_STAT(x)
static cl::opt< bool > InlineEnableCostBenefitAnalysis("inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false), cl::desc("Enable the cost-benefit analysis for the inliner"))
static cl::opt< int > InstrCost("inline-instr-cost", cl::Hidden, cl::init(5), cl::desc("Cost of a single instruction when inlining"))
static cl::opt< bool > InlineAllViableCalls("inline-all-viable-calls", cl::Hidden, cl::init(false), cl::desc("Inline all viable calls, even if they exceed the inlining " "threshold"))
static cl::opt< int > InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100), cl::desc("The maximum size of a callee that get's " "inlined without sufficient cycle savings"))
static cl::opt< int > ColdCallSiteRelFreq("cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::desc("Maximum block frequency, expressed as a percentage of caller's " "entry frequency, for a callsite to be cold in the absence of " "profile information."))
static cl::opt< bool > DisableGEPConstOperand("disable-gep-const-evaluation", cl::Hidden, cl::init(false), cl::desc("Disables evaluation of GetElementPtr with constant operands"))
static bool functionsHaveCompatibleAttributes(Function *Caller, Function *Callee, function_ref< const TargetLibraryInfo &(Function &)> &GetTLI)
Test that there are no attribute conflicts between Caller and Callee that prevent inlining.
static cl::opt< int > DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225), cl::desc("Default amount of inlining to perform"))
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1594
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1079
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
PointerType * getType() const
Overload to return most specific pointer type.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool empty() const
Definition BasicBlock.h:468
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
LLVM_ABI BlockFrequency getEntryFreq() const
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
LLVM_ABI std::optional< BlockFrequency > mul(uint64_t Factor) const
Multiplies frequency with Factor. Returns nullopt in case of overflow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
unsigned size() const
Definition DenseMap.h:172
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
A cache of ephemeral values within a function.
Type * getReturnType() const
const BasicBlock & getEntryBlock() const
Definition Function.h:793
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI void collectAsmStrs(SmallVectorImpl< StringRef > &AsmStrs) const
Definition InlineAsm.cpp:63
Represents the cost of inlining a function.
Definition InlineCost.h:91
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:132
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:127
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
Definition InlineCost.h:121
InlineResult is basically true or false.
Definition InlineCost.h:181
static InlineResult success()
Definition InlineCost.h:186
static InlineResult failure(const char *Reason)
Definition InlineCost.h:187
bool isSuccess() const
Definition InlineCost.h:190
const char * getFailureReason() const
Definition InlineCost.h:191
Base class for instruction visitors.
Definition InstVisitor.h:78
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void analyze(ParentT F)
Create the loop forest for a function.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
size_type size() const
Definition SmallPtrSet.h:99
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void reserve(size_type N)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Analysis pass providing the TargetTransformInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
LLVM_ABI unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const
LLVM_ABI unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI int getInliningLastCallToStaticBonus() const
LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const
LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const
LLVM_ABI int getInlinerVectorBonusPercent() const
LLVM_ABI bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
LLVM_ABI unsigned getInliningThresholdMultiplier() const
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const
LLVM_ABI bool areInlineCompatible(const Function *Caller, const Function *Callee) const
LLVM_ABI InstructionCost getFPOpCost(Type *Ty) const
Return the expected cost of supporting the floating point operation of the specified type.
static constexpr TypeSize getZero()
Definition TypeSize.h:349
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool erase(const ValueT &V)
Definition DenseSet.h:97
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
const int ColdccPenalty
Definition InlineCost.h:52
const char FunctionInlineCostMultiplierAttributeName[]
Definition InlineCost.h:60
const int OptSizeThreshold
Use when optsize (-Os) is specified.
Definition InlineCost.h:40
const int OptMinSizeThreshold
Use when minsize (-Oz) is specified.
Definition InlineCost.h:43
const uint64_t MaxSimplifiedDynamicAllocaToInline
Do not inline dynamic allocas that have been constant propagated to be static allocas above this amou...
Definition InlineCost.h:58
const int IndirectCallThreshold
Definition InlineCost.h:50
const int OptAggressiveThreshold
Use when -O3 is specified.
Definition InlineCost.h:46
const char MaxInlineStackSizeAttributeName[]
Definition InlineCost.h:63
const unsigned TotalAllocaSizeRecursiveCaller
Do not inline functions which allocate this many bytes on the stack when the caller is recursive.
Definition InlineCost.h:55
LLVM_ABI int getInstrCost()
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:578
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
InstructionCost Cost
@ Dead
Unused definition.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::optional< int > getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind)
auto successors(const MachineBasicBlock *BB)
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
LogicalResult failure(bool IsFailure=true)
Utility function to generate a LogicalResult.
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI InlineResult isInlineViable(Function &Callee)
Check if it is mechanically possible to inline the function Callee, based on the contents of the func...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI Value * simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
generic_gep_type_iterator<> gep_type_iterator
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:685
LLVM_ABI std::optional< InlineCostFeatures > getInliningCostFeatures(CallBase &Call, TargetTransformInfo &CalleeTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the expanded cost features.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
TargetTransformInfo TTI
LLVM_ABI std::optional< InlineResult > getAttributeBasedInliningDecision(CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
Returns InlineResult::success() if the call site should be always inlined because of user directives,...
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
LLVM_ABI int getCallsiteCost(const TargetTransformInfo &TTI, const CallBase &Call, const DataLayout &DL)
Return the cost associated with a callsite, including parameter passing and the call/return instructi...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::optional< int > getInliningCostEstimate(CallBase &Call, TargetTransformInfo &CalleeTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the cost estimate ignoring thresholds.
auto predecessors(const MachineBasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:610
constexpr bool isCallableCC(CallingConv::ID CC)
std::array< int, static_cast< size_t >(InlineCostFeatureIndex::NumberOfFeatures)> InlineCostFeatures
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Thresholds to tune inline cost analysis.
Definition InlineCost.h:207
std::optional< int > OptMinSizeThreshold
Threshold to use when the caller is optimized for minsize.
Definition InlineCost.h:225
std::optional< int > OptSizeThreshold
Threshold to use when the caller is optimized for size.
Definition InlineCost.h:222
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:216
std::optional< int > ColdCallSiteThreshold
Threshold to use when the callsite is considered cold.
Definition InlineCost.h:235
std::optional< int > ColdThreshold
Threshold to use for cold callees.
Definition InlineCost.h:219
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:228
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:209
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:212
std::optional< int > LocallyHotCallSiteThreshold
Threshold to use when the callsite is considered hot relative to function entry.
Definition InlineCost.h:232