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);
1570 return TTI.getInstructionCost(&GEP, Operands,
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 (isColdCallSite(Call, CallerBFI)) {
2155 LLVM_DEBUG(dbgs() << "Cold callsite.\n");
2156 // Do not apply bonuses for a cold callsite including the
2157 // LastCallToStatic bonus. While this bonus might result in code size
2158 // reduction, it can cause the size of a non-cold caller to increase
2159 // preventing it from being inlined.
2160 DisallowAllBonuses();
2161 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
2162 } else if (PSI) {
2163 // Use callee's global profile information only if we have no way of
2164 // determining this via callsite information.
2165 if (PSI->isFunctionEntryHot(&Callee)) {
2166 LLVM_DEBUG(dbgs() << "Hot callee.\n");
2167 // If callsite hotness can not be determined, we may still know
2168 // that the callee is hot and treat it as a weaker hint for threshold
2169 // increase.
2170 Threshold = MaxIfValid(Threshold, HintThreshold);
2171 } else if (PSI->isFunctionEntryCold(&Callee)) {
2172 LLVM_DEBUG(dbgs() << "Cold callee.\n");
2173 // Do not apply bonuses for a cold callee including the
2174 // LastCallToStatic bonus. While this bonus might result in code size
2175 // reduction, it can cause the size of a non-cold caller to increase
2176 // preventing it from being inlined.
2177 DisallowAllBonuses();
2178 Threshold = MinIfValid(Threshold, Params.ColdThreshold);
2179 }
2180 }
2181 }
2182
2183 Threshold += TTI.adjustInliningThreshold(&Call);
2184
2185 // Finally, take the target-specific inlining threshold multiplier into
2186 // account.
2187 Threshold *= TTI.getInliningThresholdMultiplier();
2188
2189 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
2190 VectorBonus = Threshold * VectorBonusPercent / 100;
2191
2192 // If there is only one call of the function, and it has internal linkage,
2193 // the cost of inlining it drops dramatically. It may seem odd to update
2194 // Cost in updateThreshold, but the bonus depends on the logic in this method.
2195 if (isSoleCallToLocalFunction(Call, F)) {
2196 addCost(-LastCallToStaticBonus);
2197 StaticBonusApplied = LastCallToStaticBonus;
2198 }
2199}
2200
2201bool CallAnalyzer::visitCmpInst(CmpInst &I) {
2202 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2203 // First try to handle simplified comparisons.
2205 return true;
2206
2207 // Try to handle comparison that can be simplified using ValueTracking.
2208 if (simplifyCmpInstForRecCall(I))
2209 return true;
2210
2211 if (I.getOpcode() == Instruction::FCmp)
2212 return false;
2213
2214 // Otherwise look for a comparison between constant offset pointers with
2215 // a common base.
2216 Value *LHSBase, *RHSBase;
2217 APInt LHSOffset, RHSOffset;
2218 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2219 if (LHSBase) {
2220 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2221 if (RHSBase && LHSBase == RHSBase) {
2222 // We have common bases, fold the icmp to a constant based on the
2223 // offsets.
2224 SimplifiedValues[&I] = ConstantInt::getBool(
2225 I.getType(),
2226 ICmpInst::compare(LHSOffset, RHSOffset, I.getPredicate()));
2227 ++NumConstantPtrCmps;
2228 return true;
2229 }
2230 }
2231
2232 auto isImplicitNullCheckCmp = [](const CmpInst &I) {
2233 for (auto *User : I.users())
2234 if (auto *Instr = dyn_cast<Instruction>(User))
2235 if (!Instr->getMetadata(LLVMContext::MD_make_implicit))
2236 return false;
2237 return true;
2238 };
2239
2240 // If the comparison is an equality comparison with null, we can simplify it
2241 // if we know the value (argument) can't be null
2242 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1))) {
2243 if (isKnownNonNullInCallee(I.getOperand(0))) {
2244 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
2245 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
2246 : ConstantInt::getFalse(I.getType());
2247 return true;
2248 }
2249 // Implicit null checks act as unconditional branches and their comparisons
2250 // should be treated as simplified and free of cost.
2251 if (isImplicitNullCheckCmp(I))
2252 return true;
2253 }
2254 return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
2255}
2256
2257bool CallAnalyzer::visitSub(BinaryOperator &I) {
2258 // Try to handle a special case: we can fold computing the difference of two
2259 // constant-related pointers.
2260 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2261 Value *LHSBase, *RHSBase;
2262 APInt LHSOffset, RHSOffset;
2263 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
2264 if (LHSBase) {
2265 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
2266 if (RHSBase && LHSBase == RHSBase) {
2267 // We have common bases, fold the subtract to a constant based on the
2268 // offsets.
2269 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
2270 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
2271 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
2272 SimplifiedValues[&I] = C;
2273 ++NumConstantPtrDiffs;
2274 return true;
2275 }
2276 }
2277 }
2278
2279 // Otherwise, fall back to the generic logic for simplifying and handling
2280 // instructions.
2281 return Base::visitSub(I);
2282}
2283
2284bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
2285 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2286 Constant *CLHS = getDirectOrSimplifiedValue<Constant>(LHS);
2287 Constant *CRHS = getDirectOrSimplifiedValue<Constant>(RHS);
2288
2289 Value *SimpleV = nullptr;
2290 if (auto FI = dyn_cast<FPMathOperator>(&I))
2291 SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
2292 FI->getFastMathFlags(), DL);
2293 else
2294 SimpleV =
2295 simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
2296
2297 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2298 SimplifiedValues[&I] = C;
2299
2300 if (SimpleV)
2301 return true;
2302
2303 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
2304 disableSROA(LHS);
2305 disableSROA(RHS);
2306
2307 // If the instruction is floating point, and the target says this operation
2308 // is expensive, this may eventually become a library call. Treat the cost
2309 // as such. Unless it's fneg which can be implemented with an xor.
2310 using namespace llvm::PatternMatch;
2311 if (I.getType()->isFloatingPointTy() &&
2313 !match(&I, m_FNeg(m_Value())))
2314 onCallPenalty();
2315
2316 return false;
2317}
2318
2319bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
2320 Value *Op = I.getOperand(0);
2321 Constant *COp = getDirectOrSimplifiedValue<Constant>(Op);
2322
2323 Value *SimpleV = simplifyFNegInst(
2324 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
2325
2326 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2327 SimplifiedValues[&I] = C;
2328
2329 if (SimpleV)
2330 return true;
2331
2332 // Disable any SROA on arguments to arbitrary, unsimplified fneg.
2333 disableSROA(Op);
2334
2335 return false;
2336}
2337
2338bool CallAnalyzer::visitLoad(LoadInst &I) {
2339 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2340 return true;
2341
2342 // If the data is already loaded from this address and hasn't been clobbered
2343 // by any stores or calls, this load is likely to be redundant and can be
2344 // eliminated.
2345 if (EnableLoadElimination &&
2346 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
2347 onLoadEliminationOpportunity();
2348 return true;
2349 }
2350
2351 onMemAccess();
2352 return false;
2353}
2354
2355bool CallAnalyzer::visitStore(StoreInst &I) {
2356 if (handleSROA(I.getPointerOperand(), I.isSimple()))
2357 return true;
2358
2359 // The store can potentially clobber loads and prevent repeated loads from
2360 // being eliminated.
2361 // FIXME:
2362 // 1. We can probably keep an initial set of eliminatable loads substracted
2363 // from the cost even when we finally see a store. We just need to disable
2364 // *further* accumulation of elimination savings.
2365 // 2. We should probably at some point thread MemorySSA for the callee into
2366 // this and then use that to actually compute *really* precise savings.
2367 disableLoadElimination();
2368
2369 onMemAccess();
2370 return false;
2371}
2372
2373bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
2374 Value *Op = I.getAggregateOperand();
2375
2376 // Special handling, because we want to simplify extractvalue with a
2377 // potential insertvalue from the caller.
2378 if (Value *SimpleOp = getSimplifiedValueUnchecked(Op)) {
2379 SimplifyQuery SQ(DL);
2380 Value *SimpleV = simplifyExtractValueInst(SimpleOp, I.getIndices(), SQ);
2381 if (SimpleV) {
2382 SimplifiedValues[&I] = SimpleV;
2383 return true;
2384 }
2385 }
2386
2387 // SROA can't look through these, but they may be free.
2388 return Base::visitExtractValue(I);
2389}
2390
2391bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
2392 // Constant folding for insert value is trivial.
2394 return true;
2395
2396 // SROA can't look through these, but they may be free.
2397 return Base::visitInsertValue(I);
2398}
2399
2400/// Try to simplify a call site.
2401///
2402/// Takes a concrete function and callsite and tries to actually simplify it by
2403/// analyzing the arguments and call itself with instsimplify. Returns true if
2404/// it has simplified the callsite to some other entity (a constant), making it
2405/// free.
2406bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
2407 // FIXME: Using the instsimplify logic directly for this is inefficient
2408 // because we have to continually rebuild the argument list even when no
2409 // simplifications can be performed. Until that is fixed with remapping
2410 // inside of instsimplify, directly constant fold calls here.
2412 return false;
2413
2414 // Try to re-map the arguments to constants.
2415 SmallVector<Constant *, 4> ConstantArgs;
2416 ConstantArgs.reserve(Call.arg_size());
2417 for (Value *I : Call.args()) {
2418 Constant *C = getDirectOrSimplifiedValue<Constant>(I);
2419 if (!C)
2420 return false; // This argument doesn't map to a constant.
2421
2422 ConstantArgs.push_back(C);
2423 }
2424 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2425 SimplifiedValues[&Call] = C;
2426 return true;
2427 }
2428
2429 return false;
2430}
2431
2432bool CallAnalyzer::isLoweredToCall(Function *F, CallBase &Call) {
2433 const TargetLibraryInfo *TLI = GetTLI ? &GetTLI(*F) : nullptr;
2434 LibFunc LF;
2435 if (!TLI || !TLI->getLibFunc(*F, LF) || !TLI->has(LF))
2436 return TTI.isLoweredToCall(F);
2437
2438 switch (LF) {
2439 case LibFunc_memcpy_chk:
2440 case LibFunc_memmove_chk:
2441 case LibFunc_mempcpy_chk:
2442 case LibFunc_memset_chk: {
2443 // Calls to __memcpy_chk whose length is known to fit within the object
2444 // size will eventually be replaced by inline stores. Therefore, these
2445 // should not incur a call penalty. This is only really relevant on
2446 // platforms whose headers redirect memcpy to __memcpy_chk (e.g. Darwin), as
2447 // other platforms use memcpy intrinsics, which are already exempt from the
2448 // call penalty.
2449 auto *LenOp = getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(2));
2450 auto *ObjSizeOp =
2451 getDirectOrSimplifiedValue<ConstantInt>(Call.getOperand(3));
2452 if (LenOp && ObjSizeOp &&
2453 LenOp->getLimitedValue() <= ObjSizeOp->getLimitedValue()) {
2454 return false;
2455 }
2456 break;
2457 }
2458 default:
2459 break;
2460 }
2461
2462 return TTI.isLoweredToCall(F);
2463}
2464
2465bool CallAnalyzer::visitCallBase(CallBase &Call) {
2466 if (!onCallBaseVisitStart(Call))
2467 return true;
2468
2469 if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
2470 !F.hasFnAttribute(Attribute::ReturnsTwice)) {
2471 // This aborts the entire analysis.
2472 ExposesReturnsTwice = true;
2473 return false;
2474 }
2475 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
2476 ContainsNoDuplicateCall = true;
2477
2478 if (InlineAsm *InlineAsmOp = dyn_cast<InlineAsm>(Call.getCalledOperand()))
2479 onInlineAsm(*InlineAsmOp);
2480
2482 bool IsIndirectCall = !F;
2483 if (IsIndirectCall) {
2484 // Check if this happens to be an indirect function call to a known function
2485 // in this inline context. If not, we've done all we can.
2487 F = getSimplifiedValue<Function>(Callee);
2488 if (!F || F->getFunctionType() != Call.getFunctionType()) {
2489 onCallArgumentSetup(Call);
2490
2491 if (!Call.onlyReadsMemory())
2492 disableLoadElimination();
2493 return Base::visitCallBase(Call);
2494 }
2495 }
2496
2497 assert(F && "Expected a call to a known function");
2498
2499 // When we have a concrete function, first try to simplify it directly.
2500 if (simplifyCallSite(F, Call))
2501 return true;
2502
2503 // Next check if it is an intrinsic we know about.
2504 // FIXME: Lift this into part of the InstVisitor.
2505 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
2506 switch (II->getIntrinsicID()) {
2507 default:
2509 disableLoadElimination();
2510 return Base::visitCallBase(Call);
2511
2512 case Intrinsic::load_relative:
2513 onLoadRelativeIntrinsic();
2514 return false;
2515
2516 case Intrinsic::memset:
2517 case Intrinsic::memcpy:
2518 case Intrinsic::memmove:
2519 disableLoadElimination();
2520 // SROA can usually chew through these intrinsics, but they aren't free.
2521 return false;
2522 case Intrinsic::icall_branch_funnel:
2523 case Intrinsic::localescape:
2524 HasUninlineableIntrinsic = true;
2525 return false;
2526 case Intrinsic::vastart:
2527 InitsVargArgs = true;
2528 return false;
2529 case Intrinsic::launder_invariant_group:
2530 case Intrinsic::strip_invariant_group:
2531 if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2532 SROAArgValues[II] = SROAArg;
2533 return true;
2534 case Intrinsic::is_constant:
2535 return simplifyIntrinsicCallIsConstant(Call);
2536 case Intrinsic::objectsize:
2537 return simplifyIntrinsicCallObjectSize(Call);
2538 }
2539 }
2540
2541 if (F == Call.getFunction()) {
2542 // This flag will fully abort the analysis, so don't bother with anything
2543 // else.
2544 IsRecursiveCall = true;
2545 if (!AllowRecursiveCall)
2546 return false;
2547 }
2548
2549 if (isLoweredToCall(F, Call)) {
2550 onLoweredCall(F, Call, IsIndirectCall);
2551 }
2552
2553 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2554 disableLoadElimination();
2555 return Base::visitCallBase(Call);
2556}
2557
2558bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
2559 // At least one return instruction will be free after inlining.
2560 bool Free = !HasReturn;
2561 HasReturn = true;
2562 return Free;
2563}
2564
2565bool CallAnalyzer::visitUncondBrInst(UncondBrInst &BI) {
2566 // We model unconditional branches as essentially free -- they really
2567 // shouldn't exist at all, but handling them makes the behavior of the
2568 // inliner more regular and predictable.
2569 return true;
2570}
2571
2572bool CallAnalyzer::visitCondBrInst(CondBrInst &BI) {
2573 // Conditional branches which will fold away are free.
2574 return getDirectOrSimplifiedValue<ConstantInt>(BI.getCondition()) ||
2575 BI.getMetadata(LLVMContext::MD_make_implicit);
2576}
2577
2578bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
2579 bool CheckSROA = SI.getType()->isPointerTy();
2580 Value *TrueVal = SI.getTrueValue();
2581 Value *FalseVal = SI.getFalseValue();
2582
2583 Constant *TrueC = getDirectOrSimplifiedValue<Constant>(TrueVal);
2584 Constant *FalseC = getDirectOrSimplifiedValue<Constant>(FalseVal);
2585 Constant *CondC = getSimplifiedValue<Constant>(SI.getCondition());
2586
2587 if (!CondC) {
2588 // Select C, X, X => X
2589 if (TrueC == FalseC && TrueC) {
2590 SimplifiedValues[&SI] = TrueC;
2591 return true;
2592 }
2593
2594 if (!CheckSROA)
2595 return Base::visitSelectInst(SI);
2596
2597 std::pair<Value *, APInt> TrueBaseAndOffset =
2598 ConstantOffsetPtrs.lookup(TrueVal);
2599 std::pair<Value *, APInt> FalseBaseAndOffset =
2600 ConstantOffsetPtrs.lookup(FalseVal);
2601 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
2602 ConstantOffsetPtrs[&SI] = std::move(TrueBaseAndOffset);
2603
2604 if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
2605 SROAArgValues[&SI] = SROAArg;
2606 return true;
2607 }
2608
2609 return Base::visitSelectInst(SI);
2610 }
2611
2612 // Select condition is a constant.
2613 Value *SelectedV = CondC->isAllOnesValue() ? TrueVal
2614 : (CondC->isNullValue()) ? FalseVal
2615 : nullptr;
2616 if (!SelectedV) {
2617 // Condition is a vector constant that is not all 1s or all 0s. If all
2618 // operands are constants, ConstantFoldSelectInstruction() can handle the
2619 // cases such as select vectors.
2620 if (TrueC && FalseC) {
2621 if (auto *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC)) {
2622 SimplifiedValues[&SI] = C;
2623 return true;
2624 }
2625 }
2626 return Base::visitSelectInst(SI);
2627 }
2628
2629 // Condition is either all 1s or all 0s. SI can be simplified.
2630 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
2631 SimplifiedValues[&SI] = SelectedC;
2632 return true;
2633 }
2634
2635 if (!CheckSROA)
2636 return true;
2637
2638 std::pair<Value *, APInt> BaseAndOffset =
2639 ConstantOffsetPtrs.lookup(SelectedV);
2640 if (BaseAndOffset.first) {
2641 ConstantOffsetPtrs[&SI] = std::move(BaseAndOffset);
2642
2643 if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
2644 SROAArgValues[&SI] = SROAArg;
2645 }
2646
2647 return true;
2648}
2649
2650bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
2651 // We model unconditional switches as free, see the comments on handling
2652 // branches.
2653 if (getDirectOrSimplifiedValue<ConstantInt>(SI.getCondition()))
2654 return true;
2655
2656 // Assume the most general case where the switch is lowered into
2657 // either a jump table, bit test, or a balanced binary tree consisting of
2658 // case clusters without merging adjacent clusters with the same
2659 // destination. We do not consider the switches that are lowered with a mix
2660 // of jump table/bit test/binary search tree. The cost of the switch is
2661 // proportional to the size of the tree or the size of jump table range.
2662 //
2663 // NB: We convert large switches which are just used to initialize large phi
2664 // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
2665 // inlining those. It will prevent inlining in cases where the optimization
2666 // does not (yet) fire.
2667
2668 unsigned JumpTableSize = 0;
2669 BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2670 unsigned NumCaseCluster =
2671 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2672
2673 onFinalizeSwitch(JumpTableSize, NumCaseCluster, SI.defaultDestUnreachable());
2674 return false;
2675}
2676
2677bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
2678 // We never want to inline functions that contain an indirectbr. This is
2679 // incorrect because all the blockaddress's (in static global initializers
2680 // for example) would be referring to the original function, and this
2681 // indirect jump would jump from the inlined copy of the function into the
2682 // original function which is extremely undefined behavior.
2683 // FIXME: This logic isn't really right; we can safely inline functions with
2684 // indirectbr's as long as no other function or global references the
2685 // blockaddress of a block within the current function.
2686 HasIndirectBr = true;
2687 return false;
2688}
2689
2690bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
2691 // FIXME: It's not clear that a single instruction is an accurate model for
2692 // the inline cost of a resume instruction.
2693 return false;
2694}
2695
2696bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
2697 // FIXME: It's not clear that a single instruction is an accurate model for
2698 // the inline cost of a cleanupret instruction.
2699 return false;
2700}
2701
2702bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
2703 // FIXME: It's not clear that a single instruction is an accurate model for
2704 // the inline cost of a catchret instruction.
2705 return false;
2706}
2707
2708bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
2709 // FIXME: It might be reasonably to discount the cost of instructions leading
2710 // to unreachable as they have the lowest possible impact on both runtime and
2711 // code size.
2712 return true; // No actual code is needed for unreachable.
2713}
2714
2715bool CallAnalyzer::visitInstruction(Instruction &I) {
2716 // Some instructions are free. All of the free intrinsics can also be
2717 // handled by SROA, etc.
2720 return true;
2721
2722 // We found something we don't understand or can't handle. Mark any SROA-able
2723 // values in the operand list as no longer viable.
2724 for (const Use &Op : I.operands())
2725 disableSROA(Op);
2726
2727 return false;
2728}
2729
2730/// Analyze a basic block for its contribution to the inline cost.
2731///
2732/// This method walks the analyzer over every instruction in the given basic
2733/// block and accounts for their cost during inlining at this callsite. It
2734/// aborts early if the threshold has been exceeded or an impossible to inline
2735/// construct has been detected. It returns false if inlining is no longer
2736/// viable, and true if inlining remains viable.
2737InlineResult
2738CallAnalyzer::analyzeBlock(BasicBlock *BB,
2739 const SmallPtrSetImpl<const Value *> &EphValues) {
2740 for (Instruction &I : *BB) {
2741 // FIXME: Currently, the number of instructions in a function regardless of
2742 // our ability to simplify them during inline to constants or dead code,
2743 // are actually used by the vector bonus heuristic. As long as that's true,
2744 // we have to special case debug intrinsics here to prevent differences in
2745 // inlining due to debug symbols. Eventually, the number of unsimplified
2746 // instructions shouldn't factor into the cost computation, but until then,
2747 // hack around it here.
2748 // Similarly, skip pseudo-probes.
2749 if (I.isDebugOrPseudoInst())
2750 continue;
2751
2752 // Skip ephemeral values.
2753 if (EphValues.count(&I))
2754 continue;
2755
2756 ++NumInstructions;
2757 if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
2758 ++NumVectorInstructions;
2759
2760 // If the instruction simplified to a constant, there is no cost to this
2761 // instruction. Visit the instructions using our InstVisitor to account for
2762 // all of the per-instruction logic. The visit tree returns true if we
2763 // consumed the instruction in any way, and false if the instruction's base
2764 // cost should count against inlining.
2765 onInstructionAnalysisStart(&I);
2766
2767 if (Base::visit(&I))
2768 ++NumInstructionsSimplified;
2769 else
2770 onMissedSimplification();
2771
2772 onInstructionAnalysisFinish(&I);
2773 using namespace ore;
2774 // If the visit this instruction detected an uninlinable pattern, abort.
2775 InlineResult IR = InlineResult::success();
2776 if (IsRecursiveCall && !AllowRecursiveCall)
2777 IR = InlineResult::failure("recursive");
2778 else if (ExposesReturnsTwice)
2779 IR = InlineResult::failure("exposes returns twice");
2780 else if (HasDynamicAlloca)
2781 IR = InlineResult::failure("dynamic alloca");
2782 else if (HasIndirectBr)
2783 IR = InlineResult::failure("indirect branch");
2784 else if (HasUninlineableIntrinsic)
2785 IR = InlineResult::failure("uninlinable intrinsic");
2786 else if (InitsVargArgs)
2787 IR = InlineResult::failure("varargs");
2788 if (!IR.isSuccess()) {
2789 if (ORE)
2790 ORE->emit([&]() {
2791 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2792 &CandidateCall)
2793 << NV("Callee", &F) << " has uninlinable pattern ("
2794 << NV("InlineResult", IR.getFailureReason())
2795 << ") and cost is not fully computed";
2796 });
2797 return IR;
2798 }
2799
2800 // If the caller is a recursive function then we don't want to inline
2801 // functions which allocate a lot of stack space because it would increase
2802 // the caller stack usage dramatically.
2803 if (IsCallerRecursive && AllocatedSize > RecurStackSizeThreshold) {
2804 auto IR =
2805 InlineResult::failure("recursive and allocates too much stack space");
2806 if (ORE)
2807 ORE->emit([&]() {
2808 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2809 &CandidateCall)
2810 << NV("Callee", &F) << " is "
2811 << NV("InlineResult", IR.getFailureReason())
2812 << ". Cost is not fully computed";
2813 });
2814 return IR;
2815 }
2816
2817 if (shouldStop())
2818 return InlineResult::failure(
2819 "Call site analysis is not favorable to inlining.");
2820 }
2821
2822 return InlineResult::success();
2823}
2824
2825/// Compute the base pointer and cumulative constant offsets for V.
2826///
2827/// This strips all constant offsets off of V, leaving it the base pointer, and
2828/// accumulates the total constant offset applied in the returned constant. It
2829/// returns 0 if V is not a pointer, and returns the constant '0' if there are
2830/// no constant offsets applied.
2831ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
2832 if (!V->getType()->isPointerTy())
2833 return nullptr;
2834
2835 unsigned AS = V->getType()->getPointerAddressSpace();
2836 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2837 APInt Offset = APInt::getZero(IntPtrWidth);
2838
2839 // Even though we don't look through PHI nodes, we could be called on an
2840 // instruction in an unreachable block, which may be on a cycle.
2841 SmallPtrSet<Value *, 4> Visited;
2842 Visited.insert(V);
2843 do {
2844 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2845 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
2846 return nullptr;
2847 V = GEP->getPointerOperand();
2848 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2849 if (GA->isInterposable())
2850 break;
2851 V = GA->getAliasee();
2852 } else {
2853 break;
2854 }
2855 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2856 } while (Visited.insert(V).second);
2857
2858 Type *IdxPtrTy = DL.getIndexType(V->getType());
2859 return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
2860}
2861
2862/// Find dead blocks due to deleted CFG edges during inlining.
2863///
2864/// If we know the successor of the current block, \p CurrBB, has to be \p
2865/// NextBB, the other successors of \p CurrBB are dead if these successors have
2866/// no live incoming CFG edges. If one block is found to be dead, we can
2867/// continue growing the dead block list by checking the successors of the dead
2868/// blocks to see if all their incoming edges are dead or not.
2869void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
2870 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
2871 // A CFG edge is dead if the predecessor is dead or the predecessor has a
2872 // known successor which is not the one under exam.
2873 if (DeadBlocks.count(Pred))
2874 return true;
2875 BasicBlock *KnownSucc = KnownSuccessors[Pred];
2876 return KnownSucc && KnownSucc != Succ;
2877 };
2878
2879 auto IsNewlyDead = [&](BasicBlock *BB) {
2880 // If all the edges to a block are dead, the block is also dead.
2881 return (!DeadBlocks.count(BB) &&
2883 [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
2884 };
2885
2886 for (BasicBlock *Succ : successors(CurrBB)) {
2887 if (Succ == NextBB || !IsNewlyDead(Succ))
2888 continue;
2890 NewDead.push_back(Succ);
2891 while (!NewDead.empty()) {
2892 BasicBlock *Dead = NewDead.pop_back_val();
2893 if (DeadBlocks.insert(Dead).second)
2894 // Continue growing the dead block lists.
2895 for (BasicBlock *S : successors(Dead))
2896 if (IsNewlyDead(S))
2897 NewDead.push_back(S);
2898 }
2899 }
2900}
2901
2902/// Analyze a call site for potential inlining.
2903///
2904/// Returns true if inlining this call is viable, and false if it is not
2905/// viable. It computes the cost and adjusts the threshold based on numerous
2906/// factors and heuristics. If this method returns false but the computed cost
2907/// is below the computed threshold, then inlining was forcibly disabled by
2908/// some artifact of the routine.
2909InlineResult CallAnalyzer::analyze() {
2910 ++NumCallsAnalyzed;
2911
2912 auto Result = onAnalysisStart();
2913 if (!Result.isSuccess())
2914 return Result;
2915
2916 if (F.empty())
2917 return InlineResult::success();
2918
2919 Function *Caller = CandidateCall.getFunction();
2920 // Check if the caller function is recursive itself.
2921 for (User *U : Caller->users()) {
2922 CallBase *Call = dyn_cast<CallBase>(U);
2923 if (Call && Call->getFunction() == Caller) {
2924 IsCallerRecursive = true;
2925 break;
2926 }
2927 }
2928
2929 // Populate our simplified values by mapping from function arguments to call
2930 // arguments with known important simplifications.
2931 auto CAI = CandidateCall.arg_begin();
2932 for (Argument &FAI : F.args()) {
2933 assert(CAI != CandidateCall.arg_end());
2934 SimplifiedValues[&FAI] = *CAI;
2935 if (isa<Constant>(*CAI))
2936 ++NumConstantArgs;
2937
2938 Value *PtrArg = *CAI;
2939 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
2940 ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
2941
2942 // We can SROA any pointer arguments derived from alloca instructions.
2943 if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
2944 SROAArgValues[&FAI] = SROAArg;
2945 onInitializeSROAArg(SROAArg);
2946 EnabledSROAAllocas.insert(SROAArg);
2947 }
2948 }
2949 ++CAI;
2950 }
2951 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
2952 NumAllocaArgs = SROAArgValues.size();
2953
2954 // Collecting the ephemeral values of `F` can be expensive, so use the
2955 // ephemeral values cache if available.
2956 SmallPtrSet<const Value *, 32> EphValuesStorage;
2957 const SmallPtrSetImpl<const Value *> *EphValues = &EphValuesStorage;
2958 if (GetEphValuesCache)
2959 EphValues = &GetEphValuesCache(F).ephValues();
2960 else
2961 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F),
2962 EphValuesStorage);
2963
2964 // The worklist of live basic blocks in the callee *after* inlining. We avoid
2965 // adding basic blocks of the callee which can be proven to be dead for this
2966 // particular call site in order to get more accurate cost estimates. This
2967 // requires a somewhat heavyweight iteration pattern: we need to walk the
2968 // basic blocks in a breadth-first order as we insert live successors. To
2969 // accomplish this, prioritizing for small iterations because we exit after
2970 // crossing our threshold, we use a small-size optimized SetVector.
2971 typedef SmallSetVector<BasicBlock *, 16> BBSetVector;
2972 BBSetVector BBWorklist;
2973 BBWorklist.insert(&F.getEntryBlock());
2974
2975 // Note that we *must not* cache the size, this loop grows the worklist.
2976 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
2977 if (shouldStop())
2978 break;
2979
2980 BasicBlock *BB = BBWorklist[Idx];
2981 if (BB->empty())
2982 continue;
2983
2984 onBlockStart(BB);
2985
2986 // Disallow inlining a blockaddress.
2987 // A blockaddress only has defined behavior for an indirect branch in the
2988 // same function, and we do not currently support inlining indirect
2989 // branches. But, the inliner may not see an indirect branch that ends up
2990 // being dead code at a particular call site. If the blockaddress escapes
2991 // the function, e.g., via a global variable, inlining may lead to an
2992 // invalid cross-function reference.
2993 // FIXME: pr/39560: continue relaxing this overt restriction.
2994 if (BB->hasAddressTaken())
2995 return InlineResult::failure("blockaddress used");
2996
2997 // Analyze the cost of this block. If we blow through the threshold, this
2998 // returns false, and we can bail on out.
2999 InlineResult IR = analyzeBlock(BB, *EphValues);
3000 if (!IR.isSuccess())
3001 return IR;
3002
3003 Instruction *TI = BB->getTerminator();
3004
3005 // Add in the live successors by first checking whether we have terminator
3006 // that may be simplified based on the values simplified by this call.
3007 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
3008 Value *Cond = BI->getCondition();
3009 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
3010 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
3011 BBWorklist.insert(NextBB);
3012 KnownSuccessors[BB] = NextBB;
3013 findDeadBlocks(BB, NextBB);
3014 continue;
3015 }
3016 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3017 Value *Cond = SI->getCondition();
3018 if (ConstantInt *SimpleCond = getSimplifiedValue<ConstantInt>(Cond)) {
3019 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
3020 BBWorklist.insert(NextBB);
3021 KnownSuccessors[BB] = NextBB;
3022 findDeadBlocks(BB, NextBB);
3023 continue;
3024 }
3025 }
3026
3027 // If we're unable to select a particular successor, just count all of
3028 // them.
3029 BBWorklist.insert_range(successors(BB));
3030
3031 onBlockAnalyzed(BB);
3032 }
3033
3034 // If this is a noduplicate call, we can still inline as long as
3035 // inlining this would cause the removal of the caller (so the instruction
3036 // is not actually duplicated, just moved).
3037 if (!isSoleCallToLocalFunction(CandidateCall, F) && ContainsNoDuplicateCall)
3038 return InlineResult::failure("noduplicate");
3039
3040 // If the callee's stack size exceeds the user-specified threshold,
3041 // do not let it be inlined.
3042 // The command line option overrides a limit set in the function attributes.
3043 size_t FinalStackSizeThreshold = StackSizeThreshold;
3044 if (!StackSizeThreshold.getNumOccurrences())
3045 if (std::optional<int> AttrMaxStackSize = getStringFnAttrAsInt(
3047 FinalStackSizeThreshold = *AttrMaxStackSize;
3048 if (AllocatedSize > FinalStackSizeThreshold)
3049 return InlineResult::failure("stacksize");
3050
3051 return finalizeAnalysis();
3052}
3053
3054void InlineCostCallAnalyzer::print(raw_ostream &OS) {
3055#define DEBUG_PRINT_STAT(x) OS << " " #x ": " << x << "\n"
3057 F.print(OS, &Writer);
3058 DEBUG_PRINT_STAT(NumConstantArgs);
3059 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
3060 DEBUG_PRINT_STAT(NumAllocaArgs);
3061 DEBUG_PRINT_STAT(NumConstantPtrCmps);
3062 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
3063 DEBUG_PRINT_STAT(NumInstructionsSimplified);
3064 DEBUG_PRINT_STAT(NumInstructions);
3065 DEBUG_PRINT_STAT(NumInlineAsmInstructions);
3066 DEBUG_PRINT_STAT(SROACostSavings);
3067 DEBUG_PRINT_STAT(SROACostSavingsLost);
3068 DEBUG_PRINT_STAT(LoadEliminationCost);
3069 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
3071 DEBUG_PRINT_STAT(Threshold);
3072#undef DEBUG_PRINT_STAT
3073}
3074
3075#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3076/// Dump stats about this call's analysis.
3077LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
3078#endif
3079
3080/// Test that there are no attribute conflicts between Caller and Callee
3081/// that prevent inlining.
3083 Function *Caller, Function *Callee,
3084 function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
3085 // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
3086 // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
3087 // object, and always returns the same object (which is overwritten on each
3088 // GetTLI call). Therefore we copy the first result.
3089 auto CalleeTLI = GetTLI(*Callee);
3090 return GetTLI(*Caller).areInlineCompatible(CalleeTLI,
3092 AttributeFuncs::areInlineCompatible(*Caller, *Callee);
3093}
3094
3096 const DataLayout &DL) {
3097 int64_t Cost = 0;
3098 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
3099 if (Call.isByValArgument(I)) {
3100 // We approximate the number of loads and stores needed by dividing the
3101 // size of the byval type by the target's pointer size.
3102 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
3103 unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
3104 unsigned AS = PTy->getAddressSpace();
3105 unsigned PointerSize = DL.getPointerSizeInBits(AS);
3106 // Ceiling division.
3107 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
3108
3109 // If it generates more than 8 stores it is likely to be expanded as an
3110 // inline memcpy so we take that as an upper bound. Otherwise we assume
3111 // one load and one store per word copied.
3112 // FIXME: The maxStoresPerMemcpy setting from the target should be used
3113 // here instead of a magic number of 8, but it's not available via
3114 // DataLayout.
3115 NumStores = std::min(NumStores, 8U);
3116
3117 Cost += 2 * NumStores * InstrCost;
3118 } else {
3119 // For non-byval arguments subtract off one instruction per call
3120 // argument.
3121 Cost += InstrCost;
3122 }
3123 }
3124 // The call instruction also disappears after inlining.
3125 Cost += InstrCost;
3126 Cost += TTI.getInlineCallPenalty(Call.getCaller(), Call, CallPenalty);
3127
3128 return std::min<int64_t>(Cost, INT_MAX);
3129}
3130
3132 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
3133 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3134 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3137 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3138 return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
3139 GetAssumptionCache, GetTLI, GetBFI, PSI, ORE,
3140 GetEphValuesCache);
3141}
3142
3144 CallBase &Call, TargetTransformInfo &CalleeTTI,
3145 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3147 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3149 const InlineParams Params = {/* DefaultThreshold*/ 0,
3150 /*HintThreshold*/ {},
3151 /*OptSizeHintThreshold*/ {},
3152 /*ColdThreshold*/ {},
3153 /*OptSizeThreshold*/ {},
3154 /*OptMinSizeThreshold*/ {},
3155 /*HotCallSiteThreshold*/ {},
3156 /*LocallyHotCallSiteThreshold*/ {},
3157 /*ColdCallSiteThreshold*/ {},
3158 /*ComputeFullInlineCost*/ true,
3159 /*EnableDeferral*/ true};
3160
3161 InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
3162 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE, true,
3163 /*IgnoreThreshold*/ true);
3164 auto R = CA.analyze();
3165 if (!R.isSuccess())
3166 return std::nullopt;
3167 return CA.getCost();
3168}
3169
3170std::optional<InlineCostFeatures> llvm::getInliningCostFeatures(
3171 CallBase &Call, TargetTransformInfo &CalleeTTI,
3172 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3174 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3176 InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, GetTLI,
3177 PSI, ORE, *Call.getCalledFunction(), Call);
3178 auto R = CFA.analyze();
3179 if (!R.isSuccess())
3180 return std::nullopt;
3181 return CFA.features();
3182}
3183
3185 CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
3186 function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
3187
3188 // Cannot inline indirect calls.
3189 if (!Callee)
3190 return InlineResult::failure("indirect call");
3191
3192 // When callee coroutine function is inlined into caller coroutine function
3193 // before coro-split pass,
3194 // coro-early pass can not handle this quiet well.
3195 // So we won't inline the coroutine function if it have not been unsplited
3196 if (Callee->isPresplitCoroutine())
3197 return InlineResult::failure("unsplited coroutine call");
3198
3199 // Inlining into a function with less target features is unsound, so enforce
3200 // this even if alwaysinline is used.
3201 Function *Caller = Call.getCaller();
3203 !CalleeTTI.areInlineCompatible(Caller, Callee))
3204 return InlineResult::failure("conflicting target features");
3205
3206 // Calls to functions with always-inline attributes should be inlined
3207 // whenever possible.
3208 if (Call.hasFnAttr(Attribute::AlwaysInline)) {
3209 if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
3210 return InlineResult::failure("noinline call site attribute");
3211
3212 if (!AttributeFuncs::isStrictFPInlineCompatible(*Caller, *Callee))
3213 return InlineResult::failure("incompatible strictfp attributes");
3214
3215 auto IsViable = isInlineViable(*Callee);
3216 if (IsViable.isSuccess())
3217 return InlineResult::success();
3218 return InlineResult::failure(IsViable.getFailureReason());
3219 }
3220
3221 // Never inline functions with conflicting attributes (unless callee has
3222 // always-inline attribute).
3223 if (!functionsHaveCompatibleAttributes(Caller, Callee, GetTLI))
3224 return InlineResult::failure("conflicting attributes");
3225
3226 // Flatten: inline all viable calls from flatten functions regardless of cost.
3227 // Checked before optnone so that flatten takes priority.
3228 if (Caller->hasFnAttribute(Attribute::Flatten)) {
3229 auto IsViable = isInlineViable(*Callee);
3230 if (IsViable.isSuccess())
3231 return InlineResult::success();
3232 return InlineResult::failure(IsViable.getFailureReason());
3233 }
3234
3235 // Don't inline this call if the caller has the optnone attribute.
3236 if (Caller->hasOptNone())
3237 return InlineResult::failure("optnone attribute");
3238
3239 // Don't inline functions which can be interposed at link-time.
3240 if (Callee->isInterposable(/*CheckNoIPA=*/false))
3241 return InlineResult::failure("interposable");
3242
3243 // Don't inline functions marked noinline.
3244 if (Callee->hasFnAttribute(Attribute::NoInline))
3245 return InlineResult::failure("noinline function attribute");
3246
3247 // Don't inline call sites marked noinline.
3248 if (Call.isNoInline())
3249 return InlineResult::failure("noinline call site attribute");
3250
3251 // Don't inline functions that are loader replaceable.
3252 if (Callee->hasFnAttribute("loader-replaceable"))
3253 return InlineResult::failure("loader replaceable function attribute");
3254
3255 return std::nullopt;
3256}
3257
3259 CallBase &Call, Function *Callee, const InlineParams &Params,
3260 TargetTransformInfo &CalleeTTI,
3261 function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
3262 function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
3265 function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
3266
3267 auto UserDecision =
3268 llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
3269
3270 if (UserDecision) {
3271 if (UserDecision->isSuccess())
3272 return llvm::InlineCost::getAlways("always inline attribute");
3273 return llvm::InlineCost::getNever(UserDecision->getFailureReason());
3274 }
3275
3278 "Inlining forced by -inline-all-viable-calls");
3279
3280 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
3281 << "... (caller:" << Call.getCaller()->getName()
3282 << ")\n");
3283
3284 InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
3285 GetAssumptionCache, GetBFI, GetTLI, PSI, ORE,
3286 /*BoostIndirect=*/true, /*IgnoreThreshold=*/false,
3287 GetEphValuesCache);
3288 InlineResult ShouldInline = CA.analyze();
3289
3290 LLVM_DEBUG(CA.dump());
3291
3292 // Always make cost benefit based decision explicit.
3293 // We use always/never here since threshold is not meaningful,
3294 // as it's not what drives cost-benefit analysis.
3295 if (CA.wasDecidedByCostBenefit()) {
3296 if (ShouldInline.isSuccess())
3297 return InlineCost::getAlways("benefit over cost",
3298 CA.getCostBenefitPair());
3299 else
3300 return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
3301 }
3302
3303 if (CA.wasDecidedByCostThreshold())
3304 return InlineCost::get(CA.getCost(), CA.getThreshold(),
3305 CA.getStaticBonusApplied());
3306
3307 // No details on how the decision was made, simply return always or never.
3308 return ShouldInline.isSuccess()
3309 ? InlineCost::getAlways("empty function")
3310 : InlineCost::getNever(ShouldInline.getFailureReason());
3311}
3312
3314 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
3315 for (BasicBlock &BB : F) {
3316 // Disallow inlining of functions which contain indirect branches.
3318 return InlineResult::failure("contains indirect branches");
3319
3320 // Disallow inlining of blockaddresses.
3321 if (BB.hasAddressTaken())
3322 return InlineResult::failure("blockaddress used");
3323
3324 for (auto &II : BB) {
3326 if (!Call)
3327 continue;
3328
3329 // Disallow recursive calls.
3330 Function *Callee = Call->getCalledFunction();
3331 if (&F == Callee)
3332 return InlineResult::failure("recursive call");
3333
3334 // Disallow calls which expose returns-twice to a function not previously
3335 // attributed as such.
3336 if (!ReturnsTwice && isa<CallInst>(Call) &&
3337 cast<CallInst>(Call)->canReturnTwice())
3338 return InlineResult::failure("exposes returns-twice attribute");
3339
3340 if (Callee)
3341 switch (Callee->getIntrinsicID()) {
3342 default:
3343 break;
3344 case llvm::Intrinsic::icall_branch_funnel:
3345 // Disallow inlining of @llvm.icall.branch.funnel because current
3346 // backend can't separate call targets from call arguments.
3347 return InlineResult::failure(
3348 "disallowed inlining of @llvm.icall.branch.funnel");
3349 case llvm::Intrinsic::localescape:
3350 // Disallow inlining functions that call @llvm.localescape. Doing this
3351 // correctly would require major changes to the inliner.
3352 return InlineResult::failure(
3353 "disallowed inlining of @llvm.localescape");
3354 case llvm::Intrinsic::vastart:
3355 // Disallow inlining of functions that initialize VarArgs with
3356 // va_start.
3357 return InlineResult::failure(
3358 "contains VarArgs initialized with va_start");
3359 }
3360 }
3361 }
3362
3363 return InlineResult::success();
3364}
3365
3366// APIs to create InlineParams based on command line flags and/or other
3367// parameters.
3368
3370 InlineParams Params;
3371
3372 // This field is the threshold to use for a callee by default. This is
3373 // derived from one or more of:
3374 // * optimization or size-optimization levels,
3375 // * a value passed to createFunctionInliningPass function, or
3376 // * the -inline-threshold flag.
3377 // If the -inline-threshold flag is explicitly specified, that is used
3378 // irrespective of anything else.
3379 if (InlineThreshold.getNumOccurrences() > 0)
3381 else
3382 Params.DefaultThreshold = Threshold;
3383
3384 // Set the HintThreshold knob from the -inlinehint-threshold.
3386 // Use same threshold for optsize by default.
3388
3389 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
3391
3392 // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3393 // populate LocallyHotCallSiteThreshold. Later, we populate
3394 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3395 // we know that optimization level is O3 (in the getInlineParams variant that
3396 // takes the opt and size levels).
3397 // FIXME: Remove this check (and make the assignment unconditional) after
3398 // addressing size regression issues at O2.
3399 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3401
3402 // Set the ColdCallSiteThreshold knob from the
3403 // -inline-cold-callsite-threshold.
3405
3406 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
3407 // -inlinehint-threshold commandline option is not explicitly given. If that
3408 // option is present, then its value applies even for callees with size and
3409 // minsize attributes.
3410 // If the -inline-threshold is not specified, set the ColdThreshold from the
3411 // -inlinecold-threshold even if it is not explicitly passed. If
3412 // -inline-threshold is specified, then -inlinecold-threshold needs to be
3413 // explicitly specified to set the ColdThreshold knob
3414 if (InlineThreshold.getNumOccurrences() == 0) {
3418 } else if (ColdThreshold.getNumOccurrences() > 0) {
3420 }
3421 return Params;
3422}
3423
3427
3429 auto Params =
3432 // At O3, use the value of -locally-hot-callsite-threshold option to populate
3433 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3434 // when it is specified explicitly.
3435 if (OptLevel > 2)
3437 return Params;
3438}
3439
3444 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
3445 [&](Function &F) -> AssumptionCache & {
3446 return FAM.getResult<AssumptionAnalysis>(F);
3447 };
3448
3449 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
3450 ProfileSummaryInfo *PSI =
3451 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3452 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
3453
3454 // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
3455 // In the current implementation, the type of InlineParams doesn't matter as
3456 // the pass serves only for verification of inliner's decisions.
3457 // We can add a flag which determines InlineParams for this run. Right now,
3458 // the default InlineParams are used.
3459 const InlineParams Params = llvm::getInlineParams();
3460 for (BasicBlock &BB : F) {
3461 for (Instruction &I : BB) {
3462 if (auto *CB = dyn_cast<CallBase>(&I)) {
3463 Function *CalledFunction = CB->getCalledFunction();
3464 if (!CalledFunction || CalledFunction->isDeclaration())
3465 continue;
3466 OptimizationRemarkEmitter ORE(CalledFunction);
3467 InlineCostCallAnalyzer ICCA(*CalledFunction, *CB, Params, TTI,
3468 GetAssumptionCache, nullptr, nullptr, PSI,
3469 &ORE);
3470 ICCA.analyze();
3471 OS << " Analyzing call of " << CalledFunction->getName()
3472 << "... (caller:" << CB->getCaller()->getName() << ")\n";
3473 ICCA.print(OS);
3474 OS << "\n";
3475 }
3476 }
3477 }
3478 return PreservedAnalyses::all();
3479}
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
Machine Check Debug Module
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
const SmallVectorImpl< MachineOperand > & Cond
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:1599
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
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:483
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:687
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:786
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
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