29 #include "llvm/Config/llvm-config.h" 45 #define DEBUG_TYPE "inline-cost" 47 STATISTIC(NumCallsAnalyzed,
"Number of call sites analyzed");
51 cl::desc(
"Control the amount of inlining to perform (default = 225)"));
55 cl::desc(
"Threshold for inlining functions with inline hint"));
60 cl::desc(
"Threshold for inlining cold callsites"));
67 cl::desc(
"Threshold for inlining functions with cold attribute"));
72 cl::desc(
"Threshold for hot callsites "));
76 cl::desc(
"Threshold for locally hot callsites "));
80 cl::desc(
"Maximum block frequency, expressed as a percentage of caller's " 81 "entry frequency, for a callsite to be cold in the absence of " 82 "profile information."));
86 cl::desc(
"Minimum block frequency, expressed as a multiple of caller's " 87 "entry frequency, for a callsite to be hot in the absence of " 88 "profile information."));
92 cl::desc(
"Compute the full inline cost of a call site even when the cost " 93 "exceeds the threshold."));
96 class InlineCostCallAnalyzer;
97 class CallAnalyzer :
public InstVisitor<CallAnalyzer, bool> {
102 virtual ~CallAnalyzer() {}
107 std::function<AssumptionCache &(Function &)> &GetAssumptionCache;
131 virtual void onBlockAnalyzed(
const BasicBlock *BB) {}
136 virtual InlineResult finalizeAnalysis() {
return true; }
142 virtual bool shouldStop() {
return false; }
155 virtual void onDisableLoadElimination() {}
158 virtual void onCallPenalty() {}
162 virtual void onLoadEliminationOpportunity() {}
166 virtual void onCallArgumentSetup(
const CallBase &
Call) {}
169 virtual void onLoadRelativeIntrinsic() {}
177 virtual bool onJumpTable(
unsigned JumpTableSize) {
return true; }
181 virtual bool onCaseCluster(
unsigned NumCaseCluster) {
return true; }
185 virtual void onFinalizeSwitch(
unsigned JumpTableSize,
186 unsigned NumCaseCluster) {}
190 virtual void onCommonInstructionSimplification() {}
196 virtual void onAggregateSROAUse(
AllocaInst *V) {}
198 bool handleSROA(
Value *V,
bool DoNotDisable) {
200 if (
auto *SROAArg = getSROAArgForValueOrNull(V)) {
202 onAggregateSROAUse(SROAArg);
205 disableSROAForArg(SROAArg);
210 bool IsCallerRecursive =
false;
211 bool IsRecursiveCall =
false;
212 bool ExposesReturnsTwice =
false;
213 bool HasDynamicAlloca =
false;
214 bool ContainsNoDuplicateCall =
false;
215 bool HasReturn =
false;
216 bool HasIndirectBr =
false;
217 bool HasUninlineableIntrinsic =
false;
218 bool InitsVargArgs =
false;
221 uint64_t AllocatedSize = 0;
222 unsigned NumInstructions = 0;
223 unsigned NumVectorInstructions = 0;
256 bool EnableLoadElimination;
260 auto It = SROAArgValues.
find(V);
261 if (It == SROAArgValues.
end() ||
262 EnabledSROAArgValues.
count(It->second) == 0)
268 bool isAllocaDerivedArg(
Value *V);
270 void disableSROA(
Value *V);
272 void disableLoadElimination();
277 template <
typename Callable>
278 bool simplifyInstruction(
Instruction &
I, Callable Evaluate);
290 bool isKnownNonNullInCallee(
Value *V);
345 : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
346 PSI(PSI), F(Callee), DL(F.
getParent()->getDataLayout()), ORE(ORE),
347 CandidateCall(Call), EnableLoadElimination(
true) {}
353 unsigned NumConstantArgs = 0;
354 unsigned NumConstantOffsetPtrArgs = 0;
355 unsigned NumAllocaArgs = 0;
356 unsigned NumConstantPtrCmps = 0;
357 unsigned NumConstantPtrDiffs = 0;
358 unsigned NumInstructionsSimplified = 0;
365 class InlineCostCallAnalyzer final :
public CallAnalyzer {
367 const bool ComputeFullInlineCost;
368 int LoadEliminationCost = 0;
373 int SingleBBBonus = 0;
383 const bool BoostIndirectCalls;
391 bool SingleBB =
true;
393 unsigned SROACostSavings = 0;
394 unsigned SROACostSavingsLost = 0;
414 void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
415 assert(UpperBound > 0 && UpperBound <= INT_MAX &&
"invalid upper bound");
416 Cost = (int)std::min(UpperBound, Cost + Inc);
420 auto CostIt = SROAArgCosts.
find(Arg);
421 if (CostIt == SROAArgCosts.
end())
423 addCost(CostIt->second);
424 SROACostSavings -= CostIt->second;
425 SROACostSavingsLost += CostIt->second;
426 SROAArgCosts.
erase(CostIt);
429 void onDisableLoadElimination()
override {
430 addCost(LoadEliminationCost);
431 LoadEliminationCost = 0;
434 void onCallArgumentSetup(
const CallBase &Call)
override {
439 void onLoadRelativeIntrinsic()
override {
441 addCost(3 * InlineConstants::InstrCost);
444 bool IsIndirectCall)
override {
453 if (IsIndirectCall && BoostIndirectCalls) {
454 auto IndirectCallParams = Params;
459 InlineCostCallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F,
460 Call, IndirectCallParams,
false);
464 Cost -=
std::max(0, CA.getThreshold() - CA.getCost());
471 void onFinalizeSwitch(
unsigned JumpTableSize,
472 unsigned NumCaseCluster)
override {
477 int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
478 4 * InlineConstants::InstrCost;
480 addCost(JTCost, (int64_t)CostUpperBound);
498 if (NumCaseCluster <= 3) {
500 addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
504 int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
508 addCost(SwitchCost, (int64_t)CostUpperBound);
510 void onCommonInstructionSimplification()
override {
511 addCost(InlineConstants::InstrCost);
514 void onInitializeSROAArg(
AllocaInst *Arg)
override {
516 "Should not initialize SROA costs for null value.");
517 SROAArgCosts[
Arg] = 0;
518 EnabledSROAArgValues.
insert(Arg);
521 void onAggregateSROAUse(
AllocaInst *SROAArg)
override {
522 auto CostIt = SROAArgCosts.
find(SROAArg);
524 "expected this argument to have a cost");
529 void onBlockAnalyzed(
const BasicBlock *BB)
override {
535 if (SingleBB && TI->getNumSuccessors() > 1) {
537 Threshold -= SingleBBBonus;
548 if (Caller->hasMinSize()) {
554 if (DeadBlocks.
count(L->getHeader()))
564 if (NumVectorInstructions <= NumInstructions / 10)
565 Threshold -= VectorBonus;
566 else if (NumVectorInstructions <= NumInstructions / 2)
567 Threshold -= VectorBonus / 2;
569 return Cost <
std::max(1, Threshold);
571 bool shouldStop()
override {
574 return Cost >= Threshold && !ComputeFullInlineCost;
577 void onLoadEliminationOpportunity()
override {
592 assert(NumInstructions == 0);
593 assert(NumVectorInstructions == 0);
596 updateThreshold(CandidateCall, F);
602 assert(SingleBBBonus >= 0);
608 Threshold += (SingleBBBonus + VectorBonus);
620 if (Cost >= Threshold && !ComputeFullInlineCost)
627 InlineCostCallAnalyzer(
633 : CallAnalyzer(TTI, GetAssumptionCache, GetBFI, PSI, ORE, Callee, Call),
635 Params.ComputeFullInlineCost || ORE),
636 Params(Params), Threshold(Params.DefaultThreshold),
637 BoostIndirectCalls(BoostIndirect) {}
640 virtual ~InlineCostCallAnalyzer() {}
642 int getCost() {
return Cost; }
647 bool CallAnalyzer::isAllocaDerivedArg(
Value *V) {
648 return SROAArgValues.
count(V);
651 void CallAnalyzer::disableSROAForArg(
AllocaInst *SROAArg) {
652 onDisableSROA(SROAArg);
653 EnabledSROAArgValues.
erase(SROAArg);
654 disableLoadElimination();
657 void CallAnalyzer::disableSROA(
Value *V) {
658 if (
auto *SROAArg = getSROAArgForValueOrNull(V)) {
659 disableSROAForArg(SROAArg);
663 void CallAnalyzer::disableLoadElimination() {
664 if (EnableLoadElimination) {
665 onDisableLoadElimination();
666 EnableLoadElimination =
false;
682 if (
Constant *SimpleOp = SimplifiedValues.
lookup(GTI.getOperand()))
690 if (
StructType *STy = GTI.getStructTypeOrNull()) {
722 if (
auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
727 return Base::visitAlloca(I);
740 return Base::visitAlloca(I);
746 HasDynamicAlloca =
true;
750 bool CallAnalyzer::visitPHI(
PHINode &I) {
766 std::pair<Value *, APInt> FirstBaseAndOffset = {
nullptr, ZeroOffset};
767 Value *FirstV =
nullptr;
772 if (DeadBlocks.
count(Pred))
776 BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
777 if (KnownSuccessor && KnownSuccessor != I.
getParent())
787 C = SimplifiedValues.
lookup(V);
789 std::pair<Value *, APInt> BaseAndOffset = {
nullptr, ZeroOffset};
791 BaseAndOffset = ConstantOffsetPtrs.
lookup(V);
793 if (!C && !BaseAndOffset.first)
810 if (FirstBaseAndOffset == BaseAndOffset)
824 FirstBaseAndOffset = BaseAndOffset;
829 SimplifiedValues[&
I] = FirstC;
834 if (FirstBaseAndOffset.first) {
835 ConstantOffsetPtrs[&
I] = FirstBaseAndOffset;
837 if (
auto *SROAArg = getSROAArgForValueOrNull(FirstV))
838 SROAArgValues[&
I] = SROAArg;
850 std::pair<Value *, APInt> BaseAndOffset =
852 if (!BaseAndOffset.first)
857 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
861 ConstantOffsetPtrs[&
I] = BaseAndOffset;
872 if (!isa<Constant>(*I) && !SimplifiedValues.
lookup(*I))
877 if ((I.
isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
879 SROAArgValues[&
I] = SROAArg;
887 disableSROAForArg(SROAArg);
894 template <
typename Callable>
895 bool CallAnalyzer::simplifyInstruction(
Instruction &I, Callable Evaluate) {
905 auto *C = Evaluate(COps);
908 SimplifiedValues[&
I] =
C;
920 std::pair<Value *, APInt> BaseAndOffset =
923 if (BaseAndOffset.first)
924 ConstantOffsetPtrs[&
I] = BaseAndOffset;
927 if (
auto *SROAArg = getSROAArgForValueOrNull(I.
getOperand(0)))
928 SROAArgValues[&
I] = SROAArg;
946 std::pair<Value *, APInt> BaseAndOffset =
948 if (BaseAndOffset.first)
949 ConstantOffsetPtrs[&
I] = BaseAndOffset;
959 if (
auto *SROAArg = getSROAArgForValueOrNull(I.
getOperand(0)))
960 SROAArgValues[&
I] = SROAArg;
977 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.
lookup(Op);
978 if (BaseAndOffset.first)
979 ConstantOffsetPtrs[&
I] = BaseAndOffset;
983 if (
auto *SROAArg = getSROAArgForValueOrNull(Op))
984 SROAArgValues[&
I] = SROAArg;
989 bool CallAnalyzer::visitCastInst(
CastInst &I) {
1003 case Instruction::FPTrunc:
1004 case Instruction::FPExt:
1005 case Instruction::UIToFP:
1006 case Instruction::SIToFP:
1007 case Instruction::FPToUI:
1008 case Instruction::FPToSI:
1027 disableSROA(Operand);
1036 bool CallAnalyzer::isKnownNonNullInCallee(
Value *V) {
1042 if (
Argument *A = dyn_cast<Argument>(V))
1043 if (paramHasAttr(A, Attribute::NonNull))
1049 if (isAllocaDerivedArg(V))
1058 bool CallAnalyzer::allowSizeGrowth(
CallBase &Call) {
1074 if (
InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
1075 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
1100 auto CallSiteFreq = CallerBFI->
getBlockFreq(CallSiteBB);
1101 auto CallerEntryFreq =
1103 return CallSiteFreq < CallerEntryFreq * ColdProb;
1107 InlineCostCallAnalyzer::getHotCallSiteThreshold(
CallBase &Call,
1135 void InlineCostCallAnalyzer::updateThreshold(
CallBase &Call,
Function &Callee) {
1137 if (!allowSizeGrowth(Call)) {
1146 return B ? std::min(A,
B.getValue()) : A;
1166 int SingleBBBonusPercent = 50;
1171 auto DisallowAllBonuses = [&]() {
1172 SingleBBBonusPercent = 0;
1173 VectorBonusPercent = 0;
1174 LastCallToStaticBonus = 0;
1185 SingleBBBonusPercent = 0;
1186 VectorBonusPercent = 0;
1211 Threshold = HotCallSiteThreshold.getValue();
1218 DisallowAllBonuses();
1235 DisallowAllBonuses();
1245 SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1246 VectorBonus = Threshold * VectorBonusPercent / 100;
1248 bool OnlyOneCallAndLocalLinkage =
1253 if (OnlyOneCallAndLocalLinkage)
1257 bool CallAnalyzer::visitCmpInst(
CmpInst &I) {
1270 Value *LHSBase, *RHSBase;
1271 APInt LHSOffset, RHSOffset;
1272 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.
lookup(LHS);
1274 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.
lookup(RHS);
1275 if (RHSBase && LHSBase == RHSBase) {
1281 SimplifiedValues[&
I] =
C;
1282 ++NumConstantPtrCmps;
1304 Value *LHSBase, *RHSBase;
1305 APInt LHSOffset, RHSOffset;
1306 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.
lookup(LHS);
1308 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.
lookup(RHS);
1309 if (RHSBase && LHSBase == RHSBase) {
1315 SimplifiedValues[&
I] =
C;
1316 ++NumConstantPtrDiffs;
1324 return Base::visitSub(I);
1331 CLHS = SimplifiedValues.
lookup(LHS);
1334 CRHS = SimplifiedValues.
lookup(RHS);
1336 Value *SimpleV =
nullptr;
1337 if (
auto FI = dyn_cast<FPMathOperator>(&I))
1339 FI->getFastMathFlags(), DL);
1344 if (
Constant *C = dyn_cast_or_null<Constant>(SimpleV))
1345 SimplifiedValues[&I] = C;
1370 COp = SimplifiedValues.
lookup(Op);
1373 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
1375 if (
Constant *C = dyn_cast_or_null<Constant>(SimpleV))
1376 SimplifiedValues[&
I] =
C;
1387 bool CallAnalyzer::visitLoad(
LoadInst &I) {
1394 if (EnableLoadElimination &&
1396 onLoadEliminationOpportunity();
1403 bool CallAnalyzer::visitStore(
StoreInst &I) {
1415 disableLoadElimination();
1463 C = dyn_cast_or_null<Constant>(SimplifiedValues.
lookup(I));
1470 SimplifiedValues[&Call] =
C;
1477 bool CallAnalyzer::visitCallBase(
CallBase &Call) {
1478 if (Call.
hasFnAttr(Attribute::ReturnsTwice) &&
1481 ExposesReturnsTwice =
true;
1484 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
1485 ContainsNoDuplicateCall =
true;
1488 Function *F = dyn_cast_or_null<Function>(Callee);
1489 bool IsIndirectCall = !
F;
1490 if (IsIndirectCall) {
1493 F = dyn_cast_or_null<Function>(SimplifiedValues.
lookup(Callee));
1495 onCallArgumentSetup(Call);
1498 disableLoadElimination();
1499 return Base::visitCallBase(Call);
1503 assert(F &&
"Expected a call to a known function");
1506 if (simplifyCallSite(F, Call))
1512 switch (II->getIntrinsicID()) {
1515 disableLoadElimination();
1516 return Base::visitCallBase(Call);
1518 case Intrinsic::load_relative:
1519 onLoadRelativeIntrinsic();
1522 case Intrinsic::memset:
1523 case Intrinsic::memcpy:
1524 case Intrinsic::memmove:
1525 disableLoadElimination();
1528 case Intrinsic::icall_branch_funnel:
1529 case Intrinsic::localescape:
1530 HasUninlineableIntrinsic =
true;
1532 case Intrinsic::vastart:
1533 InitsVargArgs =
true;
1541 IsRecursiveCall =
true;
1546 onLoweredCall(F, Call, IsIndirectCall);
1550 disableLoadElimination();
1551 return Base::visitCallBase(Call);
1554 bool CallAnalyzer::visitReturnInst(
ReturnInst &RI) {
1556 bool Free = !HasReturn;
1561 bool CallAnalyzer::visitBranchInst(
BranchInst &BI) {
1567 dyn_cast_or_null<ConstantInt>(
1578 TrueC = SimplifiedValues.
lookup(TrueVal);
1581 FalseC = SimplifiedValues.
lookup(FalseVal);
1587 if (TrueC == FalseC && TrueC) {
1588 SimplifiedValues[&
SI] = TrueC;
1593 return Base::visitSelectInst(SI);
1595 std::pair<Value *, APInt> TrueBaseAndOffset =
1596 ConstantOffsetPtrs.
lookup(TrueVal);
1597 std::pair<Value *, APInt> FalseBaseAndOffset =
1598 ConstantOffsetPtrs.
lookup(FalseVal);
1599 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
1600 ConstantOffsetPtrs[&
SI] = TrueBaseAndOffset;
1602 if (
auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
1603 SROAArgValues[&
SI] = SROAArg;
1607 return Base::visitSelectInst(SI);
1618 if (TrueC && FalseC) {
1620 SimplifiedValues[&
SI] =
C;
1624 return Base::visitSelectInst(SI);
1628 if (
Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
1629 SimplifiedValues[&
SI] = SelectedC;
1636 std::pair<Value *, APInt> BaseAndOffset =
1637 ConstantOffsetPtrs.
lookup(SelectedV);
1638 if (BaseAndOffset.first) {
1639 ConstantOffsetPtrs[&
SI] = BaseAndOffset;
1641 if (
auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
1642 SROAArgValues[&
SI] = SROAArg;
1648 bool CallAnalyzer::visitSwitchInst(
SwitchInst &SI) {
1654 if (isa<ConstantInt>(V))
1669 unsigned JumpTableSize = 0;
1671 unsigned NumCaseCluster =
1674 onFinalizeSwitch(JumpTableSize, NumCaseCluster);
1687 HasIndirectBr =
true;
1691 bool CallAnalyzer::visitResumeInst(
ResumeInst &RI) {
1716 bool CallAnalyzer::visitInstruction(
Instruction &I) {
1748 if (isa<DbgInfoIntrinsic>(I))
1752 if (EphValues.
count(&*I))
1757 ++NumVectorInstructions;
1764 if (Base::visit(&*I))
1765 ++NumInstructionsSimplified;
1767 onCommonInstructionSimplification();
1769 using namespace ore;
1772 if (IsRecursiveCall)
1774 else if (ExposesReturnsTwice)
1775 IR =
"exposes returns twice";
1776 else if (HasDynamicAlloca)
1777 IR =
"dynamic alloca";
1778 else if (HasIndirectBr)
1779 IR =
"indirect branch";
1780 else if (HasUninlineableIntrinsic)
1781 IR =
"uninlinable intrinsic";
1782 else if (InitsVargArgs)
1789 <<
NV(
"Callee", &F) <<
" has uninlinable pattern (" 1791 <<
") and cost is not fully computed";
1799 if (IsCallerRecursive &&
1801 InlineResult IR =
"recursive and allocates too much stack space";
1806 <<
NV(
"Callee", &F) <<
" is " <<
NV(
"InlineResult", IR.
message)
1807 <<
". Cost is not fully computed";
1825 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(
Value *&V) {
1838 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1839 if (!GEP->
isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1843 V = cast<Operator>(V)->getOperand(0);
1844 }
else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1845 if (GA->isInterposable())
1847 V = GA->getAliasee();
1852 }
while (Visited.
insert(V).second);
1869 return (DeadBlocks.
count(Pred) ||
1870 (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
1875 return (!DeadBlocks.
count(BB) &&
1877 [&](
BasicBlock *
P) {
return IsEdgeDead(P, BB); }));
1881 if (Succ == NextBB || !IsNewlyDead(Succ))
1885 while (!NewDead.
empty()) {
1887 if (DeadBlocks.
insert(Dead))
1906 auto Result = onAnalysisStart();
1918 IsCallerRecursive =
true;
1927 FAI != FAE; ++FAI, ++CAI) {
1929 if (
Constant *C = dyn_cast<Constant>(CAI))
1930 SimplifiedValues[&*FAI] = C;
1932 Value *PtrArg = *CAI;
1933 if (
ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1934 ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
1937 if (
auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
1938 SROAArgValues[&*FAI] = SROAArg;
1939 onInitializeSROAArg(SROAArg);
1943 NumConstantArgs = SimplifiedValues.
size();
1944 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.
size();
1945 NumAllocaArgs = SROAArgValues.
size();
1963 BBSetVector BBWorklist;
1967 for (
unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1985 if (!isa<CallBrInst>(*U))
1986 return "blockaddress used outside of callbr";
1998 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2002 dyn_cast_or_null<ConstantInt>(SimplifiedValues.
lookup(Cond))) {
2004 BBWorklist.insert(NextBB);
2005 KnownSuccessors[BB] = NextBB;
2006 findDeadBlocks(BB, NextBB);
2010 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2013 dyn_cast_or_null<ConstantInt>(SimplifiedValues.
lookup(Cond))) {
2015 BBWorklist.insert(NextBB);
2016 KnownSuccessors[BB] = NextBB;
2017 findDeadBlocks(BB, NextBB);
2028 onBlockAnalyzed(BB);
2036 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
2037 return "noduplicate";
2039 return finalizeAnalysis();
2042 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2045 #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 2059 #undef DEBUG_PRINT_STAT 2074 for (
unsigned I = 0,
E = Call.
arg_size(); I !=
E; ++
I) {
2083 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2091 NumStores = std::min(NumStores, 8U);
2111 GetAssumptionCache, GetBFI, PSI, ORE);
2131 for (
unsigned I = 0,
E = Call.
arg_size(); I !=
E; ++
I)
2141 if (Call.
hasFnAttr(Attribute::AlwaysInline)) {
2176 <<
"... (caller:" << Caller->
getName() <<
")\n");
2178 InlineCostCallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE,
2179 *Callee, Call, Params);
2185 if (!ShouldInline && CA.getCost() < CA.getThreshold())
2187 if (ShouldInline && CA.getCost() >= CA.getThreshold())
2197 if (isa<IndirectBrInst>(BI->getTerminator()))
2198 return "contains indirect branches";
2202 if (BI->hasAddressTaken())
2204 if (!isa<CallBrInst>(*U))
2205 return "blockaddress used outside of callbr";
2207 for (
auto &II : *BI) {
2214 return "recursive call";
2218 if (!ReturnsTwice && isa<CallInst>(Call) &&
2219 cast<CallInst>(Call)->canReturnTwice())
2220 return "exposes returns-twice attribute";
2226 case llvm::Intrinsic::icall_branch_funnel:
2229 return "disallowed inlining of @llvm.icall.branch.funnel";
2230 case llvm::Intrinsic::localescape:
2233 return "disallowed inlining of @llvm.localescape";
2234 case llvm::Intrinsic::vastart:
2237 return "contains VarArgs initialized with va_start";
2308 unsigned SizeOptLevel) {
2311 if (SizeOptLevel == 1)
2313 if (SizeOptLevel == 2)
static 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)...
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Return a value (possibly void), from a function.
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
Value * getPointerOperand()
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Thresholds to tune inline cost analysis.
This class is the base class for the comparison instructions.
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
unsigned getIndexSizeInBits(unsigned AS) const
Size in bits of index used for address calculation in getelementptr.
bool hasLocalLinkage() const
InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, std::function< AssumptionCache &(Function &)> &GetAssumptionCache, Optional< function_ref< BlockFrequencyInfo &(Function &)>> GetBFI, ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
BinaryOps getOpcode() const
bool hasOptNone() const
Do not optimize this function (-O0).
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Optional< int > OptSizeThreshold
Threshold to use when the caller is optimized for size.
A Module instance is used to store all the information related to an LLVM module. ...
static cl::opt< int > ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore, cl::desc("Threshold for inlining cold callsites"))
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
Function * getCaller()
Helper to get the caller (the parent function).
static int computeThresholdFromOptLevels(unsigned OptLevel, unsigned SizeOptLevel)
static cl::opt< int > LocallyHotCallSiteThreshold("locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, cl::desc("Threshold for locally hot callsites "))
Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant *> Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
Implements a dense probed hash-table based set.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
void push_back(const T &Elt)
Analysis providing profile information.
const int OptMinSizeThreshold
Use when minsize (-Oz) is specified.
Value * getCondition() const
gep_type_iterator gep_type_end(const User *GEP)
const Value * getTrueValue() const
An efficient, type-erasing, non-owning reference to a callable.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
A cache of @llvm.assume calls within a function.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
LLVMContext & getContext() const
All values hold a context through their type.
bool erase(const ValueT &V)
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static void dump(StringRef Title, SpillInfo const &Spills)
BasicBlock * getSuccessor(unsigned i) const
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
STATISTIC(NumFunctions, "Total number of functions")
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
block Block Frequency true
An instruction for reading from memory.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Value * getCondition() const
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
void reserve(size_type N)
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Represents the cost of inlining a function.
bool isFunctionEntryCold(const Function *F)
Returns true if F has cold function entry.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool areInlineCompatible(const Function &Caller, const Function &Callee)
iterator begin()
Instruction iterator methods.
bool isHotCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if CallSite CS is considered hot.
Value * getArgOperand(unsigned i) const
bool match(Val *V, const Pattern &P)
unsigned getAllocaAddrSpace() const
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
static bool isColdCallSite(CallSite CS, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
Type * getIndexType(Type *PtrTy) const
Returns the type of a GEP index.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
This is the base class for all instructions that perform data casts.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Optional< int > HintThreshold
Threshold to use for callees with inline hint.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
#define DEBUG_PRINT_STAT(x)
mir Rename Register Operands
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
This class represents a cast from a pointer to an integer.
Value * SimplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
OtherOps getOpcode() const
Get the opcode casted to the right type.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Value * getCalledOperand() const
static cl::opt< int > ColdCallSiteRelFreq("cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 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."))
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
This class represents a no-op cast from one type to another.
const APInt & getValue() const
Return the constant as an APInt value reference.
const int LastCallToStaticBonus
An instruction for storing to memory.
static cl::opt< bool > OptComputeFullInlineCost("inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::desc("Compute the full inline cost of a call site even when the cost " "exceeds the threshold."))
static cl::opt< int > HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), cl::ZeroOrMore, cl::desc("Threshold for hot callsites "))
static InlineCost getAlways(const char *Reason)
InlineResult is basically true or false.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Class to represent pointers.
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool hasProfileSummary()
Returns true if profile summary is available.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool isNoInline() const
Return true if the call should not be inlined.
const int IndirectCallThreshold
unsigned arg_size() const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Resume the propagation of an exception.
bool isPointerTy() const
True if this is an instance of PointerType.
uint64_t getFixedSize() const
Indirect Branch Instruction.
const int OptAggressiveThreshold
Use when -O3 is specified.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Optional< int > OptMinSizeThreshold
Threshold to use when the caller is optimized for minsize.
static cl::opt< int > HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore, cl::desc("Threshold for inlining functions with inline hint"))
InlineResult isInlineViable(Function &Callee)
Minimal filter to detect invalid constructs for inlining.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Value * getPointerOperand()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
const Value * getCondition() const
bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap. ...
Optional< int > LocallyHotCallSiteThreshold
Threshold to use when the callsite is considered hot relative to function entry.
const Value * getArraySize() const
Get the number of elements allocated.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
std::enable_if< std::is_unsigned< T >::value, T >::type 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.
static bool functionsHaveCompatibleAttributes(Function *Caller, Function *Callee, TargetTransformInfo &TTI)
Test that there are no attribute conflicts between Caller and Callee that prevent inlining...
uint64_t getEntryFreq() const
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static cl::opt< int > HotCallSiteRelFreq("hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 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."))
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isConditional() const
static cl::opt< int > ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore, cl::desc("Threshold for inlining functions with cold attribute"))
pred_range predecessors(BasicBlock *BB)
Optional< int > ColdThreshold
Threshold to use for cold callees.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
int getCallsiteCost(CallBase &Call, const DataLayout &DL)
Return the cost associated with a callsite, including parameter passing and the call/return instructi...
Class for arbitrary precision integers.
amdgpu Simplify well known AMD library false FunctionCallee Callee
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
iterator_range< user_iterator > users()
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
const Value * getFalseValue() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
static cl::opt< int > InlineThreshold("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, cl::desc("Control the amount of inlining to perform (default = 225)"))
Predicate getPredicate() const
Return the predicate for this instruction.
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
static InlineCost getNever(const char *Reason)
bool isFunctionEntryHot(const Function *F)
Returns true if F has hot function entry.
uint64_t getElementOffset(unsigned Idx) const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool onlyReadsMemory(unsigned OpNo) const
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool isUnconditional() const
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool isColdCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if Callsite CS is considered cold.
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
const unsigned TotalAllocaSizeRecursiveCaller
Do not inline functions which allocate this many bytes on the stack when the caller is recursive...
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef< unsigned > getIndices() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
bool isEquality() const
This is just a convenience that dispatches to the subclasses.
A vector that has set insertion semantics.
succ_range successors(Instruction *I)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Optional< int > ColdCallSiteThreshold
Threshold to use when the callsite is considered cold.
static const Function * getParent(const Value *V)
print Print MemDeps of function
bool hasOneUse() const
Return true if there is exactly one user of this value.
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
const int OptSizeThreshold
Use when optsize (-Os) is specified.
bool nullPointerIsDefined() const
Check if null pointer dereferencing is considered undefined behavior for the function.
static APInt getNullValue(unsigned numBits)
Get the '0' value.
Value * getPointerOperand()
Statically lint checks LLVM IR
Type * getElementType() const
Optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
int DefaultThreshold
The default threshold to start with for a callee.
static InlineCost get(int Cost, int Threshold)
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
This instruction inserts a struct field of array element value into an aggregate value.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
gep_type_iterator gep_type_begin(const User *GEP)