67 #define DEBUG_TYPE "partial-inlining" 70 "Number of callsites functions partially inlined into.");
71 STATISTIC(NumColdOutlinePartialInlined,
"Number of times functions with " 72 "cold outlined regions were partially " 73 "inlined into its caller(s).");
75 "Number of cold single entry/exit regions found.");
77 "Number of cold single entry/exit regions outlined.");
87 cl::desc(
"Disable multi-region partial inlining"));
93 cl::desc(
"Force outline regions with live exits"));
99 cl::desc(
"Mark outline function calls with ColdCC"));
105 cl::desc(
"Trace partial inlining."));
119 cl::desc(
"Minimum ratio comparing relative sizes of each " 120 "outline candidate and original function"));
125 cl::desc(
"Minimum block executions to consider " 126 "its BranchProbabilityInfo valid"));
131 cl::desc(
"Minimum BranchProbability to consider a region cold."));
135 cl::desc(
"Max number of blocks to be partially inlined"));
141 cl::desc(
"Max number of partial inlining. The default is unlimited"));
149 cl::desc(
"Relative frequency of outline region to " 154 cl::desc(
"A debug option to add additional penalty to the computed one."));
158 struct FunctionOutliningInfo {
159 FunctionOutliningInfo() =
default;
163 unsigned GetNumInlinedBlocks()
const {
return Entries.size() + 1; }
179 struct FunctionOutliningMultiRegionInfo {
180 FunctionOutliningMultiRegionInfo()
184 struct OutlineRegionInfo {
188 : Region(Region.
begin(), Region.
end()), EntryBlock(EntryBlock),
189 ExitBlock(ExitBlock), ReturnBlock(ReturnBlock) {}
199 struct PartialInlinerImpl {
207 : GetAssumptionCache(GetAC), LookupAssumptionCache(LookupAC),
208 GetTTI(GTTI), GetBFI(GBFI), PSI(ProfSI) {}
218 std::pair<bool, Function *> unswitchFunction(
Function *
F);
224 struct FunctionCloner {
227 FunctionCloner(
Function *
F, FunctionOutliningInfo *OI,
230 FunctionCloner(
Function *F, FunctionOutliningMultiRegionInfo *OMRI,
238 void NormalizeReturnBlock();
241 bool doMultiRegionFunctionOutlining();
248 Function *doSingleRegionFunctionOutlining();
253 typedef std::pair<Function *, BasicBlock *> FuncBodyCallerPair;
259 bool IsFunctionInlined =
false;
261 int OutlinedRegionCost = 0;
263 std::unique_ptr<FunctionOutliningInfo> ClonedOI =
nullptr;
265 std::unique_ptr<FunctionOutliningMultiRegionInfo> ClonedOMRI =
nullptr;
266 std::unique_ptr<BlockFrequencyInfo> ClonedFuncBFI =
nullptr;
272 int NumPartialInlining = 0;
273 std::function<AssumptionCache &(Function &)> *GetAssumptionCache;
275 std::function<TargetTransformInfo &(Function &)> *GetTTI;
287 bool shouldPartialInline(
CallSite CS, FunctionCloner &Cloner,
294 bool tryPartialInline(FunctionCloner &Cloner);
298 void computeCallsiteToProfCountMap(
Function *DuplicateFunction,
301 bool IsLimitReached() {
308 if (
CallInst *CI = dyn_cast<CallInst>(U))
310 else if (
InvokeInst *II = dyn_cast<InvokeInst>(U))
319 return getCallSite(User);
322 std::tuple<DebugLoc, BasicBlock *> getOneDebugLoc(
Function *F) {
326 return std::make_tuple(DLoc, Block);
335 std::tuple<int, int> computeOutliningCosts(FunctionCloner &Cloner);
340 static int computeBBInlineCost(
BasicBlock *BB);
342 std::unique_ptr<FunctionOutliningInfo> computeOutliningInfo(
Function *F);
343 std::unique_ptr<FunctionOutliningMultiRegionInfo>
347 struct PartialInlinerLegacyPass :
public ModulePass {
360 bool runOnModule(
Module &M)
override {
366 &getAnalysis<TargetTransformInfoWrapperPass>();
368 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
370 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
379 std::function<TargetTransformInfo &(Function &)> GetTTI =
381 return TTIWP->getTTI(F);
384 return PartialInlinerImpl(&GetAssumptionCache, LookupAssumptionCache,
392 std::unique_ptr<FunctionOutliningMultiRegionInfo>
393 PartialInlinerImpl::computeOutliningColdRegionsInfo(
Function *F,
400 std::unique_ptr<BlockFrequencyInfo> ScopedBFI;
404 BFI = ScopedBFI.get();
406 BFI = &(*GetBFI)(*F);
409 if (!PSI->hasInstrumentationProfile())
410 return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
412 std::unique_ptr<FunctionOutliningMultiRegionInfo> OutliningInfo =
413 std::make_unique<FunctionOutliningMultiRegionInfo>();
423 for (
auto *Block : BlockList) {
430 <<
"Region dominated by " 431 <<
ore::NV(
"Block", BlockList.front()->getName())
432 <<
" has more than one region exit edge.";
451 int OverallFunctionCost = 0;
453 OverallFunctionCost += computeBBInlineCost(&BB);
457 dbgs() <<
"OverallFunctionCost = " << OverallFunctionCost <<
"\n";
459 int MinOutlineRegionCost =
463 MinBlockCounterExecution);
464 bool ColdCandidateFound =
false;
466 std::vector<BasicBlock *>
DFS;
468 DFS.push_back(CurrEntry);
469 VisitedMap[CurrEntry] =
true;
476 while (!DFS.empty()) {
477 auto *thisBB = DFS.back();
482 if (PSI->isColdBlock(thisBB, BFI) ||
488 VisitedMap[*
SI] =
true;
492 if (SuccProb > MinBranchProbability)
496 dbgs() <<
"Found cold edge: " << thisBB->getName() <<
"->" 497 << (*SI)->getName() <<
"\nBranch Probability = " << SuccProb
502 DT.getDescendants(*SI, DominateVector);
504 if (!IsSingleEntry(DominateVector))
508 if (!(ExitBlock = IsSingleExit(DominateVector)))
510 int OutlineRegionCost = 0;
511 for (
auto *BB : DominateVector)
512 OutlineRegionCost += computeBBInlineCost(BB);
516 dbgs() <<
"OutlineRegionCost = " << OutlineRegionCost <<
"\n";
519 if (OutlineRegionCost < MinOutlineRegionCost) {
523 <<
ore::NV(
"Callee", F) <<
" inline cost-savings smaller than " 524 <<
ore::NV(
"Cost", MinOutlineRegionCost);
532 for (
auto *BB : DominateVector)
533 VisitedMap[BB] =
true;
537 FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegInfo(
538 DominateVector, DominateVector.front(), ExitBlock, ReturnBlock);
539 OutliningInfo->ORI.push_back(RegInfo);
542 dbgs() <<
"Found Cold Candidate starting at block: " 543 << DominateVector.front()->getName() <<
"\n";
546 ColdCandidateFound =
true;
547 NumColdRegionsFound++;
550 if (ColdCandidateFound)
551 return OutliningInfo;
553 return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
556 std::unique_ptr<FunctionOutliningInfo>
557 PartialInlinerImpl::computeOutliningInfo(
Function *F) {
561 return std::unique_ptr<FunctionOutliningInfo>();
570 return isa<ReturnInst>(TI);
574 if (IsReturnBlock(Succ1))
575 return std::make_tuple(Succ1, Succ2);
576 if (IsReturnBlock(Succ2))
577 return std::make_tuple(Succ2, Succ1);
579 return std::make_tuple<BasicBlock *, BasicBlock *>(
nullptr,
nullptr);
584 if (IsSuccessor(Succ1, Succ2))
585 return std::make_tuple(Succ1, Succ2);
586 if (IsSuccessor(Succ2, Succ1))
587 return std::make_tuple(Succ2, Succ1);
589 return std::make_tuple<BasicBlock *, BasicBlock *>(
nullptr,
nullptr);
592 std::unique_ptr<FunctionOutliningInfo> OutliningInfo =
593 std::make_unique<FunctionOutliningInfo>();
596 bool CandidateFound =
false;
611 std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
614 OutliningInfo->Entries.push_back(CurrEntry);
615 OutliningInfo->ReturnBlock = ReturnBlock;
616 OutliningInfo->NonReturnBlock = NonReturnBlock;
617 CandidateFound =
true;
623 std::tie(CommSucc, OtherSucc) = GetCommonSucc(Succ1, Succ2);
628 OutliningInfo->Entries.push_back(CurrEntry);
633 return std::unique_ptr<FunctionOutliningInfo>();
639 "Function Entry must be the first in Entries vector");
646 auto HasNonEntryPred = [Entries](
BasicBlock *BB) {
648 if (!Entries.count(Pred))
653 auto CheckAndNormalizeCandidate =
654 [Entries, HasNonEntryPred](FunctionOutliningInfo *OutliningInfo) {
655 for (
BasicBlock *E : OutliningInfo->Entries) {
657 if (Entries.count(Succ))
659 if (Succ == OutliningInfo->ReturnBlock)
660 OutliningInfo->ReturnBlockPreds.push_back(E);
661 else if (Succ != OutliningInfo->NonReturnBlock)
665 if (HasNonEntryPred(E))
671 if (!CheckAndNormalizeCandidate(OutliningInfo.get()))
672 return std::unique_ptr<FunctionOutliningInfo>();
677 BasicBlock *Cand = OutliningInfo->NonReturnBlock;
681 if (HasNonEntryPred(Cand))
688 std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
689 if (!ReturnBlock || ReturnBlock != OutliningInfo->ReturnBlock)
696 OutliningInfo->Entries.push_back(Cand);
697 OutliningInfo->NonReturnBlock = NonReturnBlock;
698 OutliningInfo->ReturnBlockPreds.push_back(Cand);
699 Entries.insert(Cand);
702 return OutliningInfo;
710 for (
auto *E : OI->Entries) {
722 PartialInlinerImpl::getOutliningCallBBRelativeFreq(FunctionCloner &Cloner) {
723 BasicBlock *OutliningCallBB = Cloner.OutlinedFunctions.back().second;
725 Cloner.ClonedFuncBFI->getBlockFreq(&Cloner.ClonedFunc->getEntryBlock());
726 auto OutliningCallFreq =
727 Cloner.ClonedFuncBFI->getBlockFreq(OutliningCallBB);
731 if (OutliningCallFreq.getFrequency() > EntryFreq.getFrequency()) {
732 OutliningCallFreq = EntryFreq;
735 OutliningCallFreq.getFrequency(), EntryFreq.getFrequency());
738 return OutlineRegionRelFreq;
753 return OutlineRegionRelFreq;
758 return OutlineRegionRelFreq;
761 bool PartialInlinerImpl::shouldPartialInline(
762 CallSite CS, FunctionCloner &Cloner,
769 assert(Callee == Cloner.ClonedFunc);
775 auto &CalleeTTI = (*GetTTI)(*Callee);
776 bool RemarksEnabled =
779 assert(Call &&
"invalid callsite for partial inline");
781 CalleeTTI, *GetAssumptionCache, GetBFI, PSI,
782 RemarksEnabled ? &ORE :
nullptr);
787 <<
NV(
"Callee", Cloner.OrigFunc)
788 <<
" should always be fully inlined, not partially";
796 <<
NV(
"Callee", Cloner.OrigFunc) <<
" not partially inlined into " 797 <<
NV(
"Caller", Caller)
798 <<
" because it should never be inlined (cost=never)";
806 <<
NV(
"Callee", Cloner.OrigFunc) <<
" not partially inlined into " 807 <<
NV(
"Caller", Caller) <<
" because too costly to inline (cost=" 808 <<
NV(
"Cost", IC.
getCost()) <<
", threshold=" 820 if (NormWeightedSavings < WeightedOutliningRcost) {
824 <<
NV(
"Callee", Cloner.OrigFunc) <<
" not partially inlined into " 825 <<
NV(
"Caller", Caller) <<
" runtime overhead (overhead=" 826 <<
NV(
"Overhead", (
unsigned)WeightedOutliningRcost.
getFrequency())
830 <<
" of making the outlined call is too high";
838 <<
NV(
"Callee", Cloner.OrigFunc) <<
" can be partially inlined into " 839 <<
NV(
"Caller", Caller) <<
" with cost=" <<
NV(
"Cost", IC.
getCost())
849 int PartialInlinerImpl::computeBBInlineCost(
BasicBlock *BB) {
854 switch (
I.getOpcode()) {
855 case Instruction::BitCast:
856 case Instruction::PtrToInt:
857 case Instruction::IntToPtr:
858 case Instruction::Alloca:
859 case Instruction::PHI:
861 case Instruction::GetElementPtr:
862 if (cast<GetElementPtrInst>(&
I)->hasAllZeroIndices())
869 if (
I.isLifetimeStartOrEnd())
872 if (
CallInst *CI = dyn_cast<CallInst>(&
I)) {
892 PartialInlinerImpl::computeOutliningCosts(FunctionCloner &Cloner) {
893 int OutliningFuncCallCost = 0, OutlinedFunctionCost = 0;
894 for (
auto FuncBBPair : Cloner.OutlinedFunctions) {
895 Function *OutlinedFunc = FuncBBPair.first;
896 BasicBlock* OutliningCallBB = FuncBBPair.second;
899 OutliningFuncCallCost += computeBBInlineCost(OutliningCallBB);
903 OutlinedFunctionCost += computeBBInlineCost(&BB);
905 assert(OutlinedFunctionCost >= Cloner.OutlinedRegionCost &&
906 "Outlined function cost should be no less than the outlined region");
911 OutlinedFunctionCost -=
914 int OutliningRuntimeOverhead =
915 OutliningFuncCallCost +
916 (OutlinedFunctionCost - Cloner.OutlinedRegionCost) +
919 return std::make_tuple(OutliningFuncCallCost, OutliningRuntimeOverhead);
925 void PartialInlinerImpl::computeCallsiteToProfCountMap(
931 std::unique_ptr<BlockFrequencyInfo> TempBFI;
934 auto ComputeCurrBFI = [&,
this](
Function *Caller) {
941 CurrentCallerBFI = TempBFI.get();
944 CurrentCallerBFI = &(*GetBFI)(*Caller);
948 for (User *User :
Users) {
951 if (CurrentCaller != Caller) {
952 CurrentCaller = Caller;
953 ComputeCurrBFI(Caller);
955 assert(CurrentCallerBFI &&
"CallerBFI is not set");
960 CallSiteToProfCountMap[User] = *Count;
962 CallSiteToProfCountMap[User] = 0;
966 PartialInlinerImpl::FunctionCloner::FunctionCloner(
969 : OrigFunc(F), ORE(ORE), LookupAC(LookupAC) {
970 ClonedOI = std::make_unique<FunctionOutliningInfo>();
976 ClonedOI->ReturnBlock = cast<BasicBlock>(VMap[OI->ReturnBlock]);
977 ClonedOI->NonReturnBlock = cast<BasicBlock>(VMap[OI->NonReturnBlock]);
979 ClonedOI->Entries.push_back(cast<BasicBlock>(VMap[BB]));
983 ClonedOI->ReturnBlockPreds.push_back(NewE);
990 PartialInlinerImpl::FunctionCloner::FunctionCloner(
991 Function *F, FunctionOutliningMultiRegionInfo *OI,
994 : OrigFunc(F), ORE(ORE), LookupAC(LookupAC) {
995 ClonedOMRI = std::make_unique<FunctionOutliningMultiRegionInfo>();
1003 for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo
RegionInfo :
1007 Region.
push_back(cast<BasicBlock>(VMap[BB]));
1009 BasicBlock *NewEntryBlock = cast<BasicBlock>(VMap[RegionInfo.EntryBlock]);
1010 BasicBlock *NewExitBlock = cast<BasicBlock>(VMap[RegionInfo.ExitBlock]);
1012 if (RegionInfo.ReturnBlock)
1013 NewReturnBlock = cast<BasicBlock>(VMap[RegionInfo.ReturnBlock]);
1014 FunctionOutliningMultiRegionInfo::OutlineRegionInfo MappedRegionInfo(
1015 Region, NewEntryBlock, NewExitBlock, NewReturnBlock);
1016 ClonedOMRI->ORI.push_back(MappedRegionInfo);
1023 void PartialInlinerImpl::FunctionCloner::NormalizeReturnBlock() {
1027 while (I != BB->
end()) {
1048 BasicBlock *PreReturn = ClonedOI->ReturnBlock;
1050 PHINode *FirstPhi = getFirstPHI(PreReturn);
1051 unsigned NumPredsFromEntries = ClonedOI->ReturnBlockPreds.size();
1057 Value *CommonValue = PN->getIncomingValue(0);
1058 if (
all_of(PN->incoming_values(),
1059 [&](
Value *V) {
return V == CommonValue; }))
1064 ClonedOI->ReturnBlock = ClonedOI->ReturnBlock->splitBasicBlock(
1065 ClonedOI->ReturnBlock->getFirstNonPHI()->getIterator());
1069 while (I != PreReturn->
end()) {
1077 Ins = ClonedOI->ReturnBlock->getFirstNonPHI();
1080 for (
BasicBlock *E : ClonedOI->ReturnBlockPreds) {
1089 if (
auto *OldPhiVal = IsTrivialPhi(OldPhi)) {
1095 for (
auto *DP : DeadPhis)
1096 DP->eraseFromParent();
1098 for (
auto E : ClonedOI->ReturnBlockPreds) {
1103 bool PartialInlinerImpl::FunctionCloner::doMultiRegionFunctionOutlining() {
1108 Cost += computeBBInlineCost(BB);
1112 assert(ClonedOMRI &&
"Expecting OutlineInfo for multi region outline");
1114 if (ClonedOMRI->ORI.empty())
1130 for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo
RegionInfo :
1132 int CurrentOutlinedRegionCost = ComputeRegionCost(RegionInfo.Region);
1135 ClonedFuncBFI.get(), &BPI,
1136 LookupAC(*RegionInfo.EntryBlock->getParent()),
1143 dbgs() <<
"inputs: " << Inputs.
size() <<
"\n";
1144 dbgs() <<
"outputs: " << Outputs.
size() <<
"\n";
1145 for (
Value *value : Inputs)
1146 dbgs() <<
"value used in func: " << *value <<
"\n";
1147 for (
Value *output : Outputs)
1148 dbgs() <<
"instr used in func: " << *output <<
"\n";
1158 CallSite OCS = PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc);
1161 OutlinedFunctions.push_back(std::make_pair(OutlinedFunc,OutliningCallBB));
1162 NumColdRegionsOutlined++;
1163 OutlinedRegionCost += CurrentOutlinedRegionCost;
1172 &RegionInfo.Region.front()->front())
1173 <<
"Failed to extract region at block " 1174 <<
ore::NV(
"Block", RegionInfo.Region.front());
1178 return !OutlinedFunctions.empty();
1182 PartialInlinerImpl::FunctionCloner::doSingleRegionFunctionOutlining() {
1185 auto ToBeInlined = [&,
this](
BasicBlock *BB) {
1186 return BB == ClonedOI->ReturnBlock ||
1187 (
std::find(ClonedOI->Entries.begin(), ClonedOI->Entries.end(), BB) !=
1188 ClonedOI->Entries.end());
1191 assert(ClonedOI &&
"Expecting OutlineInfo for single region outline");
1202 std::vector<BasicBlock *> ToExtract;
1203 ToExtract.push_back(ClonedOI->NonReturnBlock);
1204 OutlinedRegionCost +=
1205 PartialInlinerImpl::computeBBInlineCost(ClonedOI->NonReturnBlock);
1207 if (!ToBeInlined(&BB) && &BB != ClonedOI->NonReturnBlock) {
1208 ToExtract.push_back(&BB);
1213 OutlinedRegionCost += computeBBInlineCost(&BB);
1220 ClonedFuncBFI.get(), &BPI, LookupAC(*ClonedFunc),
1222 .extractCodeRegion(CEAC);
1226 PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc)
1230 OutlinedFunctions.push_back(std::make_pair(OutlinedFunc, OutliningCallBB));
1234 &ToExtract.front()->front())
1235 <<
"Failed to extract region at block " 1236 <<
ore::NV(
"Block", ToExtract.front());
1239 return OutlinedFunc;
1242 PartialInlinerImpl::FunctionCloner::~FunctionCloner() {
1246 ClonedFunc->eraseFromParent();
1247 if (!IsFunctionInlined) {
1250 for (
auto FuncBBPair : OutlinedFunctions) {
1257 std::pair<bool, Function *> PartialInlinerImpl::unswitchFunction(
Function *F) {
1260 return {
false,
nullptr};
1264 return {
false,
nullptr};
1267 return {
false,
nullptr};
1269 if (PSI->isFunctionEntryCold(F))
1270 return {
false,
nullptr};
1272 if (F->
users().empty())
1273 return {
false,
nullptr};
1281 std::unique_ptr<FunctionOutliningMultiRegionInfo> OMRI =
1282 computeOutliningColdRegionsInfo(F, ORE);
1284 FunctionCloner Cloner(F, OMRI.get(), ORE, LookupAssumptionCache);
1288 dbgs() <<
"HotCountThreshold = " << PSI->getHotCountThreshold() <<
"\n";
1289 dbgs() <<
"ColdCountThreshold = " << PSI->getColdCountThreshold()
1293 bool DidOutline = Cloner.doMultiRegionFunctionOutlining();
1298 dbgs() <<
">>>>>> Outlined (Cloned) Function >>>>>>\n";
1299 Cloner.ClonedFunc->print(
dbgs());
1300 dbgs() <<
"<<<<<< Outlined (Cloned) Function <<<<<<\n";
1304 if (tryPartialInline(Cloner))
1305 return {
true,
nullptr};
1313 std::unique_ptr<FunctionOutliningInfo> OI = computeOutliningInfo(F);
1315 return {
false,
nullptr};
1317 FunctionCloner Cloner(F, OI.get(), ORE, LookupAssumptionCache);
1318 Cloner.NormalizeReturnBlock();
1320 Function *OutlinedFunction = Cloner.doSingleRegionFunctionOutlining();
1322 if (!OutlinedFunction)
1323 return {
false,
nullptr};
1325 bool AnyInline = tryPartialInline(Cloner);
1328 return {
true, OutlinedFunction};
1330 return {
false,
nullptr};
1333 bool PartialInlinerImpl::tryPartialInline(FunctionCloner &Cloner) {
1334 if (Cloner.OutlinedFunctions.empty())
1339 int NonWeightedRcost;
1340 std::tie(SizeCost, NonWeightedRcost) = computeOutliningCosts(Cloner);
1345 if (Cloner.ClonedOI) {
1346 RelativeToEntryFreq = getOutliningCallBBRelativeFreq(Cloner);
1355 WeightedRcost =
BlockFrequency(NonWeightedRcost) * RelativeToEntryFreq;
1365 std::tie(DLoc, Block) = getOneDebugLoc(Cloner.ClonedFunc);
1366 OrigFuncORE.
emit([&]() {
1369 <<
ore::NV(
"Function", Cloner.OrigFunc)
1370 <<
" not partially inlined into callers (Original Size = " 1371 <<
ore::NV(
"OutlinedRegionOriginalSize", Cloner.OutlinedRegionCost)
1372 <<
", Size of call sequence to outlined function = " 1373 <<
ore::NV(
"NewSize", SizeCost) <<
")";
1378 assert(Cloner.OrigFunc->users().empty() &&
1379 "F's users should all be replaced!");
1381 std::vector<User *>
Users(Cloner.ClonedFunc->user_begin(),
1382 Cloner.ClonedFunc->user_end());
1385 auto CalleeEntryCount = Cloner.OrigFunc->getEntryCount();
1386 if (CalleeEntryCount)
1387 computeCallsiteToProfCountMap(Cloner.ClonedFunc, CallSiteToProfCountMap);
1389 uint64_t CalleeEntryCountV =
1390 (CalleeEntryCount ? CalleeEntryCount.getCount() : 0);
1392 bool AnyInline =
false;
1393 for (User *User :
Users) {
1396 if (IsLimitReached())
1400 if (!shouldPartialInline(CS, Cloner, WeightedRcost, CallerORE))
1406 OR <<
ore::NV(
"Callee", Cloner.OrigFunc) <<
" partially inlined into " 1413 (Cloner.ClonedOI ? Cloner.OutlinedFunctions.back().first
1420 if (CalleeEntryCountV && CallSiteToProfCountMap.count(User)) {
1421 uint64_t CallSiteCount = CallSiteToProfCountMap[User];
1422 CalleeEntryCountV -= std::min(CalleeEntryCountV, CallSiteCount);
1426 NumPartialInlining++;
1428 if (Cloner.ClonedOI)
1429 NumPartialInlined++;
1431 NumColdOutlinePartialInlined++;
1436 Cloner.IsFunctionInlined =
true;
1437 if (CalleeEntryCount)
1438 Cloner.OrigFunc->setEntryCount(
1439 CalleeEntryCount.setCount(CalleeEntryCountV));
1441 OrigFuncORE.
emit([&]() {
1443 <<
"Partially inlined into at least one caller";
1451 bool PartialInlinerImpl::run(
Module &M) {
1455 std::vector<Function *> Worklist;
1456 Worklist.reserve(M.
size());
1459 Worklist.push_back(&F);
1461 bool Changed =
false;
1462 while (!Worklist.empty()) {
1464 Worklist.pop_back();
1469 bool Recursive =
false;
1470 for (User *U : CurrFunc->
users())
1472 if (
I->getParent()->getParent() == CurrFunc) {
1479 std::pair<bool, Function * > Result = unswitchFunction(CurrFunc);
1481 Worklist.push_back(Result.second);
1482 Changed |= Result.first;
1491 "Partial Inliner",
false,
false)
1499 return new PartialInlinerLegacyPass();
1506 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
1515 std::function<BlockFrequencyInfo &(Function &)> GetBFI =
1520 std::function<TargetTransformInfo &(Function &)> GetTTI =
1527 if (PartialInlinerImpl(&GetAssumptionCache, LookupAssumptionCache, &GetTTI,
Optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
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.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
size_type size() const
Determine the number of elements in the SetVector.
void initializePartialInlinerLegacyPassPass(PassRegistry &)
A Module instance is used to store all the information related to an LLVM module. ...
static cl::opt< int > MaxNumPartialInlining("max-partial-inlining", cl::init(-1), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of partial inlining. The default is unlimited"))
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Analysis providing profile information.
This class represents a function call, abstracting a target machine's calling convention.
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
An immutable pass that tracks lazily created AssumptionCache objects.
An efficient, type-erasing, non-owning reference to a callable.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
const BasicBlock & back() const
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...
STATISTIC(NumFunctions, "Total number of functions")
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
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...
iv Induction Variable Users
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
Represents the cost of inlining a function.
static cl::opt< bool > ForceLiveExit("pi-force-live-exit-outline", cl::init(false), cl::Hidden, cl::desc("Force outline regions with live exits"))
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
ModulePass * createPartialInliningPass()
createPartialInliningPass - This pass inlines parts of functions.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
static cl::opt< int > OutlineRegionFreqPercent("outline-region-freq-percent", cl::init(75), cl::Hidden, cl::ZeroOrMore, cl::desc("Relative frequency of outline region to " "the entry block"))
This file contains the simple types necessary to represent the attributes associated with functions a...
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
InstrTy * getInstruction() const
Type * getType() const
All values are typed, get the type of this value.
static cl::opt< bool > SkipCostAnalysis("skip-partial-inlining-cost-analysis", cl::init(false), cl::ZeroOrMore, cl::ReallyHidden, cl::desc("Skip Cost Analysis"))
const T & getValue() const LLVM_LVALUE_FUNCTION
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static cl::opt< unsigned > MinBlockCounterExecution("min-block-execution", cl::init(100), cl::Hidden, cl::desc("Minimum block executions to consider " "its BranchProbabilityInfo valid"))
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
static cl::opt< unsigned > ExtraOutliningPenalty("partial-inlining-extra-penalty", cl::init(0), cl::Hidden, cl::desc("A debug option to add additional penalty to the computed one."))
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
void setCallingConv(CallingConv::ID CC)
static cl::opt< bool > MarkOutlinedColdCC("pi-mark-coldcc", cl::init(false), cl::Hidden, cl::desc("Mark outline function calls with ColdCC"))
initializer< Ty > init(const Ty &Val)
Control flow instructions. These all have token chains.
static cl::opt< bool > DisablePartialInlining("disable-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Disable partial inlining"))
A set of analyses that are preserved following a run of a transformation pass.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
static cl::opt< float > ColdBranchRatio("cold-branch-ratio", cl::init(0.1), cl::Hidden, cl::desc("Minimum BranchProbability to consider a region cold."))
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
const Instruction & front() const
std::pair< iterator, bool > insert(const ValueT &V)
Represent the analysis usage information of a pass.
InlineResult isInlineViable(Function &Callee)
Minimal filter to detect invalid constructs for inlining.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
InlineResult InlineFunction(CallBase *CB, InlineFunctionInfo &IFI, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true)
This function inlines the called function into the basic block of the caller.
Used in the streaming interface as the general argument type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
virtual bool isMissedOptRemarkEnabled(StringRef PassName) const
Return true if missed optimization remarks are enabled, override to provide different implementation...
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A function analysis which provides an AssumptionCache.
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
Align max(MaybeAlign Lhs, Align Rhs)
InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
AssumptionCache * lookupAssumptionCache(Function &F)
Return the cached assumptions for a function if it has already been scanned.
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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...
static cl::opt< unsigned > MaxNumInlineBlocks("max-num-inline-blocks", cl::init(5), cl::Hidden, cl::desc("Max number of blocks to be partially inlined"))
amdgpu Simplify well known AMD library false FunctionCallee Callee
BBTy * getParent() const
Get the basic block containing the call site.
iterator_range< user_iterator > users()
int getCost() const
Get the inline cost estimate.
int getCostDelta() const
Get the cost delta from the threshold for inlining.
static cl::opt< bool > DisableMultiRegionPartialInline("disable-mr-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Disable multi-region partial inlining"))
INITIALIZE_PASS_BEGIN(PartialInlinerLegacyPass, "partial-inliner", "Partial Inliner", false, false) INITIALIZE_PASS_END(PartialInlinerLegacyPass
unsigned succ_size(const Instruction *I)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Analysis providing branch probability information.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static cl::opt< bool > TracePartialInlining("trace-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Trace partial inlining."))
const Function * getParent() const
Return the enclosing method, or null if none.
static bool hasProfileData(Function *F, FunctionOutliningInfo *OI)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
bool isUnconditional() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const DiagnosticHandler * getDiagHandlerPtr() const
getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by setDiagnosticHandler.
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
static cl::opt< float > MinRegionSizeRatio("min-region-size-ratio", cl::init(0.1), cl::Hidden, cl::desc("Minimum ratio comparing relative sizes of each " "outline candidate and original function"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(Instruction *I)
AssumptionCache & getAssumptionCache(Function &F)
Get the cached assumptions for a function.
print Print MemDeps of function
A container for analyses that lazily runs them and caches their results.
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
const BasicBlock * getParent() const
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
FunTy * getCaller() const
Return the caller function for this call site.