90 #include <system_error> 95 using namespace sampleprof;
97 #define DEBUG_TYPE "sample-profile" 98 #define CSINLINE_DEBUG DEBUG_TYPE "-inline" 101 "Number of functions inlined with context sensitive profile");
103 "Number of functions not inlined with context sensitive profile");
119 "sample-profile-max-propagate-iterations",
cl::init(100),
120 cl::desc(
"Maximum number of iterations to go through when propagating " 121 "sample block/edge weights through the CFG."));
125 cl::desc(
"Emit a warning if less than N% of records in the input profile " 126 "are matched to the IR."));
130 cl::desc(
"Emit a warning if less than N% of samples in the input profile " 131 "are matched to the IR."));
135 cl::desc(
"Use this option to turn off/on warnings about function with " 136 "samples but without debug information to use those samples. "));
140 cl::desc(
"If the sample profile is accurate, we will mark all un-sampled " 141 "callsite and function as having 0 samples. Otherwise, treat " 142 "un-sampled callsites and functions conservatively as unknown. "));
147 cl::desc(
"For symbols in profile symbol list, regard their profiles to " 148 "be accurate. It may be overriden by profile-sample-accurate. "));
152 cl::desc(
"Merge past inlinee's profile to outline version if sample " 153 "profile loader decided not to inline a call site."));
157 cl::desc(
"Do profile annotation and inlining for functions in top-down " 158 "order of call graph during sample profile loading."));
162 cl::desc(
"Inline cold call sites in profile loader if it's beneficial " 167 cl::desc(
"Threshold for inlining cold callsites"));
173 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
178 class SampleProfileLoader;
180 class SampleCoverageTracker {
182 SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){};
185 uint32_t Discriminator, uint64_t Samples);
186 unsigned computeCoverage(
unsigned Used,
unsigned Total)
const;
191 uint64_t getTotalUsedSamples()
const {
return TotalUsedSamples; }
196 SampleCoverage.clear();
197 TotalUsedSamples = 0;
201 using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
202 using FunctionSamplesCoverageMap =
214 FunctionSamplesCoverageMap SampleCoverage;
227 uint64_t TotalUsedSamples = 0;
229 SampleProfileLoader &SPLoader;
232 class GUIDToFuncNameMapper {
236 : CurrentReader(Reader), CurrentModule(M),
237 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
241 for (
const auto &
F : CurrentModule) {
243 CurrentGUIDToFuncNameMap.insert(
254 if (CanonName != OrigName)
255 CurrentGUIDToFuncNameMap.insert(
260 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
263 ~GUIDToFuncNameMapper() {
267 CurrentGUIDToFuncNameMap.clear();
271 SetGUIDToFuncNameMapForAll(
nullptr);
276 std::queue<FunctionSamples *> FSToUpdate;
277 for (
auto &IFS : CurrentReader.getProfiles()) {
278 FSToUpdate.push(&IFS.second);
281 while (!FSToUpdate.empty()) {
287 for (
auto &IFS : FSMap) {
289 FSToUpdate.push(&FS);
305 class SampleProfileLoader {
311 : GetAC(
std::move(GetAssumptionCache)),
312 GetTTI(
std::move(GetTargetTransformInfo)), CoverageTracker(*this),
313 Filename(Name), RemappingFilename(RemapName),
314 IsThinLTOPreLink(IsThinLTOPreLink) {}
316 bool doInitialization(
Module &M);
323 friend class SampleCoverageTracker;
331 std::vector<const FunctionSamples *>
332 findIndirectCallFunctionSamples(
const Instruction &
I, uint64_t &Sum)
const;
340 void emitOptimizationRemarksForInlineCandidates(
346 void findEquivalenceClasses(
Function &
F);
347 template <
bool IsPostDom>
352 uint64_t visitEdge(Edge
E,
unsigned *NumUnknownEdges, Edge *UnknownEdge);
355 bool propagateThroughEdges(
Function &
F,
bool UpdateBlockCount);
356 void computeDominanceAndLoopInfo(
Function &
F);
357 void clearFunctionData();
365 BlockWeightMap BlockWeights;
371 EdgeWeightMap EdgeWeights;
385 EquivalenceClassMap EquivalenceClass;
394 std::unique_ptr<DominatorTree> DT;
395 std::unique_ptr<PostDominatorTree> PDT;
396 std::unique_ptr<LoopInfo> LI;
398 std::function<AssumptionCache &(Function &)> GetAC;
399 std::function<TargetTransformInfo &(Function &)> GetTTI;
402 BlockEdgeMap Predecessors;
405 BlockEdgeMap Successors;
407 SampleCoverageTracker CoverageTracker;
410 std::unique_ptr<SampleProfileReader> Reader;
416 std::string Filename;
419 std::string RemappingFilename;
422 bool ProfileIsValid =
false;
428 bool IsThinLTOPreLink;
435 std::unique_ptr<ProfileSymbolList> PSL;
441 uint64_t TotalCollectedSamples = 0;
449 struct NotInlinedProfileInfo {
467 bool ProfAccForSymsInList;
470 class SampleProfileLoaderLegacyPass :
public ModulePass {
476 bool IsThinLTOPreLink =
false)
480 return ACT->getAssumptionCache(
F);
483 return TTIWP->getTTI(
F);
489 void dump() { SampleLoader.dump(); }
491 bool doInitialization(
Module &M)
override {
492 return SampleLoader.doInitialization(M);
495 StringRef getPassName()
const override {
return "Sample profile pass"; }
496 bool runOnModule(
Module &M)
override;
505 SampleProfileLoader SampleLoader;
529 bool SampleProfileLoader::callsiteIsHot(
const FunctionSamples *CallsiteFS,
534 assert(PSI &&
"PSI is expected to be non null");
536 if (ProfAccForSymsInList)
551 unsigned &Count = SampleCoverage[
FS][Loc];
552 bool FirstTime = (++Count == 1);
554 TotalUsedSamples += Samples;
564 auto I = SampleCoverage.find(FS);
568 unsigned Count = (
I != SampleCoverage.end()) ?
I->second.size() : 0;
574 for (
const auto &J :
I.second) {
576 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
577 Count += countUsedRecords(CalleeSamples, PSI);
593 for (
const auto &J :
I.second) {
595 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
596 Count += countBodyRecords(CalleeSamples, PSI);
610 Total +=
I.second.getSamples();
614 for (
const auto &J :
I.second) {
616 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
617 Total += countBodySamples(CalleeSamples, PSI);
628 unsigned SampleCoverageTracker::computeCoverage(
unsigned Used,
629 unsigned Total)
const {
631 "number of used records cannot exceed the total number of records");
632 return Total > 0 ? Used * 100 / Total : 100;
636 void SampleProfileLoader::clearFunctionData() {
637 BlockWeights.clear();
639 VisitedBlocks.clear();
640 VisitedEdges.clear();
641 EquivalenceClass.clear();
645 Predecessors.clear();
647 CoverageTracker.clear();
655 void SampleProfileLoader::printEdgeWeight(
raw_ostream &OS, Edge
E) {
656 OS <<
"weight[" << E.first->getName() <<
"->" << E.second->getName()
657 <<
"]: " << EdgeWeights[
E] <<
"\n";
664 void SampleProfileLoader::printBlockEquivalence(
raw_ostream &OS,
666 const BasicBlock *Equiv = EquivalenceClass[BB];
667 OS <<
"equivalence[" << BB->
getName()
668 <<
"]: " << ((Equiv) ? EquivalenceClass[BB]->
getName() :
"NONE") <<
"\n";
675 void SampleProfileLoader::printBlockWeight(
raw_ostream &OS,
677 const auto &
I = BlockWeights.find(BB);
678 uint64_t
W = (
I == BlockWeights.end() ? 0 :
I->second);
679 OS <<
"weight[" << BB->
getName() <<
"]: " << W <<
"\n";
697 return std::error_code();
701 return std::error_code();
706 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
707 return std::error_code();
713 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
715 findCalleeFunctionSamples(Inst))
724 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.
get());
729 Remark <<
" samples from profile (offset: ";
741 <<
" (line offset: " << LineOffset <<
"." 758 bool HasWeight =
false;
775 bool SampleProfileLoader::computeBlockWeights(
Function &
F) {
776 bool Changed =
false;
778 for (
const auto &BB : F) {
781 BlockWeights[&BB] = Weight.
get();
782 VisitedBlocks.insert(&BB);
804 SampleProfileLoader::findCalleeFunctionSamples(
const Instruction &Inst)
const {
811 if (
const CallInst *CI = dyn_cast<CallInst>(&Inst))
812 if (
Function *Callee = CI->getCalledFunction())
813 CalleeName =
Callee->getName();
827 std::vector<const FunctionSamples *>
828 SampleProfileLoader::findIndirectCallFunctionSamples(
831 std::vector<const FunctionSamples *> R;
847 for (
const auto &T_C :
T.get())
853 for (
const auto &NameFS : *M) {
854 Sum += NameFS.second.getEntrySamples();
855 R.push_back(&NameFS.second);
877 SampleProfileLoader::findFunctionSamples(
const Instruction &Inst)
const {
882 auto it = DILocation2SampleMap.try_emplace(DIL,
nullptr);
884 it.first->second = Samples->findFunctionSamples(DIL);
885 return it.first->second;
888 bool SampleProfileLoader::inlineCallInstruction(
Instruction *
I) {
889 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
891 Function *CalledFunction = CS.getCalledFunction();
904 getInlineCost(cast<CallBase>(*I), Params, GetTTI(*CalledFunction), GetAC,
905 None,
nullptr,
nullptr);
908 <<
"incompatible inlining");
915 <<
"inlined callee '" <<
ore::NV(
"Callee", CalledFunction)
927 if (Callee ==
nullptr)
932 GetTTI(*Callee), GetAC, None,
nullptr,
nullptr);
937 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
940 for (
auto I : Candidates) {
942 if (CalledFunction) {
945 <<
"previous inlining reattempted for " 946 << (Hot ?
"hotness: '" :
"size: '")
947 <<
ore::NV(
"Callee", CalledFunction) <<
"' into '" 948 <<
ore::NV(
"Caller", &F) <<
"'");
966 bool SampleProfileLoader::inlineHotFunctions(
972 assert((!ProfAccForSymsInList ||
975 "ProfAccForSymsInList should be false when profile-sample-accurate " 979 bool Changed =
false;
981 bool LocalChanged =
false;
989 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
990 !isa<IntrinsicInst>(
I) && (FS = findCalleeFunctionSamples(I))) {
993 localNotInlinedCallSites.try_emplace(&I, FS);
994 if (callsiteIsHot(FS, PSI))
996 else if (shouldInlineColdCallee(I))
1002 emitOptimizationRemarksForInlineCandidates(AllCandidates, F,
true);
1006 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F,
false);
1009 for (
auto I : CIS) {
1012 if (CalledFunction == &F)
1015 if (PromotedInsns.
count(I))
1018 for (
const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1019 if (IsThinLTOPreLink) {
1030 if (CalleeFunctionName == F.getName())
1033 if (!callsiteIsHot(FS, PSI))
1036 const char *Reason =
"Callee function not available";
1039 !R->getValue()->isDeclaration() &&
1040 R->getValue()->getSubprogram() &&
1048 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
1049 inlineCallInstruction(DI)) {
1050 localNotInlinedCallSites.erase(I);
1051 LocalChanged =
true;
1056 <<
"\nFailed to promote indirect call to " 1057 << CalleeFunctionName <<
" because " << Reason <<
"\n");
1060 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
1062 if (inlineCallInstruction(I)) {
1063 localNotInlinedCallSites.erase(I);
1064 LocalChanged =
true;
1067 }
else if (IsThinLTOPreLink) {
1068 findCalleeFunctionSamples(*I)->findInlinedFunctions(
1080 for (
const auto &Pair : localNotInlinedCallSites) {
1088 <<
"previous inlining not repeated: '" 1089 <<
ore::NV(
"Callee", Callee) <<
"' into '" 1090 <<
ore::NV(
"Caller", &F) <<
"'");
1108 OutlineFS->
merge(*FS);
1111 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1141 template <
bool IsPostDom>
1142 void SampleProfileLoader::findEquivalencesFor(
1145 const BasicBlock *EC = EquivalenceClass[BB1];
1146 uint64_t Weight = BlockWeights[EC];
1147 for (
const auto *BB2 : Descendants) {
1148 bool IsDomParent = DomTree->
dominates(BB2, BB1);
1149 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
1150 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
1151 EquivalenceClass[BB2] = EC;
1153 if (VisitedBlocks.count(BB2)) {
1154 VisitedBlocks.insert(EC);
1165 Weight =
std::max(Weight, BlockWeights[BB2]);
1169 BlockWeights[EC] = Samples->getHeadSamples() + 1;
1171 BlockWeights[EC] = Weight;
1184 void SampleProfileLoader::findEquivalenceClasses(
Function &F) {
1188 for (
auto &BB : F) {
1192 if (EquivalenceClass.count(BB1)) {
1198 EquivalenceClass[BB1] = BB1;
1210 DominatedBBs.
clear();
1211 DT->getDescendants(BB1, DominatedBBs);
1212 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
1224 dbgs() <<
"\nAssign the same weight to all blocks in the same class\n");
1225 for (
auto &BI : F) {
1227 const BasicBlock *EquivBB = EquivalenceClass[BB];
1229 BlockWeights[BB] = BlockWeights[EquivBB];
1244 uint64_t SampleProfileLoader::visitEdge(Edge E,
unsigned *NumUnknownEdges,
1245 Edge *UnknownEdge) {
1246 if (!VisitedEdges.count(E)) {
1247 (*NumUnknownEdges)++;
1252 return EdgeWeights[
E];
1268 bool SampleProfileLoader::propagateThroughEdges(
Function &F,
1269 bool UpdateBlockCount) {
1270 bool Changed =
false;
1272 for (
const auto &BI : F) {
1281 for (
unsigned i = 0; i < 2; i++) {
1282 uint64_t TotalWeight = 0;
1283 unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1284 Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1288 NumTotalEdges = Predecessors[BB].size();
1289 for (
auto *Pred : Predecessors[BB]) {
1290 Edge E = std::make_pair(Pred, BB);
1291 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1292 if (E.first == E.second)
1293 SelfReferentialEdge =
E;
1295 if (NumTotalEdges == 1) {
1296 SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1300 NumTotalEdges = Successors[BB].size();
1301 for (
auto *Succ : Successors[BB]) {
1302 Edge E = std::make_pair(BB, Succ);
1303 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1305 if (NumTotalEdges == 1) {
1306 SingleEdge = std::make_pair(BB, Successors[BB][0]);
1333 if (NumUnknownEdges <= 1) {
1334 uint64_t &BBWeight = BlockWeights[EC];
1335 if (NumUnknownEdges == 0) {
1336 if (!VisitedBlocks.count(EC)) {
1340 if (TotalWeight > BBWeight) {
1341 BBWeight = TotalWeight;
1344 <<
" known. Set weight for block: ";
1345 printBlockWeight(
dbgs(), BB););
1347 }
else if (NumTotalEdges == 1 &&
1348 EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1351 EdgeWeights[SingleEdge] = BlockWeights[EC];
1354 }
else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1357 if (BBWeight >= TotalWeight)
1358 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1360 EdgeWeights[UnknownEdge] = 0;
1363 OtherEC = EquivalenceClass[UnknownEdge.first];
1365 OtherEC = EquivalenceClass[UnknownEdge.second];
1367 if (VisitedBlocks.count(OtherEC) &&
1368 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1369 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1370 VisitedEdges.insert(UnknownEdge);
1373 printEdgeWeight(
dbgs(), UnknownEdge));
1375 }
else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1378 for (
auto *Pred : Predecessors[BB]) {
1379 Edge E = std::make_pair(Pred, BB);
1381 VisitedEdges.insert(E);
1384 for (
auto *Succ : Successors[BB]) {
1385 Edge E = std::make_pair(BB, Succ);
1387 VisitedEdges.insert(E);
1390 }
else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1391 uint64_t &BBWeight = BlockWeights[BB];
1393 if (BBWeight >= TotalWeight)
1394 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1396 EdgeWeights[SelfReferentialEdge] = 0;
1397 VisitedEdges.insert(SelfReferentialEdge);
1400 printEdgeWeight(
dbgs(), SelfReferentialEdge));
1402 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1403 BlockWeights[EC] = TotalWeight;
1404 VisitedBlocks.insert(EC);
1417 void SampleProfileLoader::buildEdges(
Function &F) {
1418 for (
auto &BI : F) {
1423 if (!Predecessors[B1].
empty())
1427 if (Visited.
insert(B2).second)
1428 Predecessors[B1].push_back(B2);
1433 if (!Successors[B1].
empty())
1437 if (Visited.
insert(B2).second)
1438 Successors[B1].push_back(B2);
1470 void SampleProfileLoader::propagateWeights(
Function &F) {
1471 bool Changed =
true;
1476 for (
auto &BI : F) {
1478 Loop *L = LI->getLoopFor(BB);
1483 if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1484 BlockWeights[Header] = BlockWeights[BB];
1497 Changed = propagateThroughEdges(F,
false);
1503 VisitedEdges.clear();
1506 Changed = propagateThroughEdges(F,
false);
1513 Changed = propagateThroughEdges(F,
true);
1518 LLVM_DEBUG(
dbgs() <<
"\nPropagation complete. Setting branch weights\n");
1521 for (
auto &BI : F) {
1524 if (BlockWeights[BB]) {
1525 for (
auto &I : BB->getInstList()) {
1526 if (!isa<CallInst>(I) && !isa<InvokeInst>(
I))
1530 const DebugLoc &DLoc = I.getDebugLoc();
1541 if (!
T ||
T.get().empty())
1546 findIndirectCallFunctionSamples(I, Sum);
1548 SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1549 SortedCallTargets.
size());
1550 }
else if (!isa<IntrinsicInst>(&I)) {
1551 I.setMetadata(LLVMContext::MD_prof,
1553 {static_cast<uint32_t>(BlockWeights[BB])}));
1560 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1566 :
Twine(
"<UNKNOWN LOCATION>"))
1573 Edge E = std::make_pair(BB, Succ);
1574 uint64_t Weight = EdgeWeights[
E];
1585 Weights.
push_back(static_cast<uint32_t>(Weight + 1));
1587 if (Weight > MaxWeight) {
1596 uint64_t TempWeight;
1608 <<
"most popular destination for conditional branches at " 1609 <<
ore::NV(
"CondBranchesLoc", BranchLoc);
1628 unsigned SampleProfileLoader::getFunctionLoc(
Function &F) {
1630 return S->getLine();
1638 "No debug information found in function " + F.
getName() +
1639 ": Function profile not used",
1644 void SampleProfileLoader::computeDominanceAndLoopInfo(
Function &F) {
1703 bool SampleProfileLoader::emitAnnotations(
Function &F) {
1704 bool Changed =
false;
1706 if (getFunctionLoc(F) == 0)
1710 << F.
getName() <<
": " << getFunctionLoc(F) <<
"\n");
1713 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1716 Changed |= computeBlockWeights(F);
1729 computeDominanceAndLoopInfo(F);
1732 findEquivalenceClasses(F);
1735 propagateWeights(F);
1740 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1741 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1742 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1746 Twine(Used) +
" of " +
Twine(Total) +
" available profile records (" +
1747 Twine(Coverage) +
"%) were applied",
1753 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1754 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1755 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1759 Twine(Used) +
" of " +
Twine(Total) +
" available profile samples (" +
1760 Twine(Coverage) +
"%) were applied",
1770 "Sample Profile loader",
false,
false)
1779 std::vector<Function *> FunctionOrderList;
1780 FunctionOrderList.reserve(M.size());
1785 FunctionOrderList.push_back(&F);
1786 return FunctionOrderList;
1789 assert(&CG->getModule() == &M);
1791 while (!CGI.isAtEnd()) {
1795 FunctionOrderList.push_back(F);
1800 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1801 return FunctionOrderList;
1804 bool SampleProfileLoader::doInitialization(
Module &M) {
1807 std::unique_ptr<SampleProfileReaderItaniumRemapper> RemapReader;
1810 if (std::error_code EC = ReaderOrErr.getError()) {
1811 std::string Msg =
"Could not open profile: " + EC.message();
1815 Reader = std::move(ReaderOrErr.get());
1821 ProfAccForSymsInList =
1823 if (ProfAccForSymsInList) {
1824 NamesInProfile.clear();
1826 NamesInProfile.insert(NameTable->begin(), NameTable->end());
1833 return new SampleProfileLoaderLegacyPass();
1837 return new SampleProfileLoaderLegacyPass(Name);
1842 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1843 if (!ProfileIsValid)
1853 TotalCollectedSamples += I.second.getTotalSamples();
1862 auto pos = OrigName.
find(
'.');
1871 r.first->second =
nullptr;
1875 bool retval =
false;
1876 for (
auto F : buildFunctionOrder(M, CG)) {
1877 assert(!F->isDeclaration());
1878 clearFunctionData();
1883 for (
const std::pair<Function *, NotInlinedProfileInfo> &pair :
1890 bool SampleProfileLoaderLegacyPass::runOnModule(
Module &M) {
1891 ACT = &getAnalysis<AssumptionCacheTracker>();
1892 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1894 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1895 return SampleLoader.runOnModule(M,
nullptr, PSI,
nullptr);
1900 DILocation2SampleMap.clear();
1905 uint64_t initialEntryCount = -1;
1911 initialEntryCount = 0;
1914 ProfAccForSymsInList =
false;
1921 if (ProfAccForSymsInList) {
1923 if (PSL->contains(F.
getName()))
1924 initialEntryCount = 0;
1937 if (NamesInProfile.count(CanonName))
1938 initialEntryCount = -1;
1942 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1949 OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&
F);
1950 ORE = OwnedORE.get();
1953 if (Samples && !Samples->empty())
1954 return emitAnnotations(F);
1970 SampleProfileLoader SampleLoader(
1973 : ProfileRemappingFileName,
1974 IsThinLTOPreLink, GetAssumptionCache, GetTTI);
1976 if (!SampleLoader.doInitialization(M))
1981 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
const Function & getFunction() const
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
static uint64_t getGUID(StringRef Name)
reference emplace_back(ArgTypes &&... Args)
Thresholds to tune inline cost analysis.
Represents either an error or a value T.
static cl::opt< bool > ProfileTopDownLoad("sample-profile-top-down-load", cl::Hidden, cl::init(false), cl::desc("Do profile annotation and inlining for functions in top-down " "order of call graph during sample profile loading."))
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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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.
A Module instance is used to store all the information related to an LLVM module. ...
static ErrorOr< std::unique_ptr< SampleProfileReader > > create(const std::string Filename, LLVMContext &C, const std::string RemapFilename="")
Create a sample profile reader appropriate to the file format.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Implements a dense probed hash-table based set.
virtual void collectFuncsFrom(const Module &M)
bool isColdCount(uint64_t C)
Returns true if count C is considered cold.
void push_back(const T &Elt)
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Analysis providing profile information.
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
Metadata * getProfileSummary(bool IsCS)
Returns profile summary metadata.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
static cl::opt< bool > ProfileAccurateForSymsInList("profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::desc("For symbols in profile symbol list, regard their profiles to " "be accurate. It may be overriden by profile-sample-accurate. "))
LLVMContext & getContext() const
All values hold a context through their type.
bool isLegalToPromote(CallSite CS, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
STATISTIC(NumFunctions, "Total number of functions")
uint64_t getOrCompHotCountThreshold()
Returns HotCountThreshold if set.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const Module *M, uint64_t Threshold) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
static SmallVector< InstrProfValueData, 2 > GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M)
Returns the sorted CallTargetMap M by count in descending order.
bool isHotCount(uint64_t C)
Returns true if count C is considered hot.
A node in the call graph for a module.
Represents the cost of inlining a function.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Metadata * getMD(LLVMContext &Context)
Return summary information as metadata.
Representation of the samples collected for a function.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static const SortedCallTargetSet SortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
static cl::opt< std::string > SampleProfileRemappingFile("sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"), cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden)
LLVMContext & getContext() const
Get the global data context.
static StringRef getName(Value *V)
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
StringRef getFilename() const
BlockT * getHeader() const
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...
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void verifyMisExpect(llvm::Instruction *I, const llvm::SmallVector< uint32_t, 4 > &Weights, llvm::LLVMContext &Ctx)
verifyMisExpect - compares PGO counters to the thresholds used for llvm.expect and warns if the PGO c...
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
static cl::opt< std::string > SampleProfileFile("sample-profile-file", cl::init(""), cl::value_desc("filename"), cl::desc("Profile file loaded by -sample-profile"), cl::Hidden)
ModulePass * createSampleProfileLoaderPass()
Instruction * promoteIndirectCall(Instruction *Inst, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
uint64_t getHeadSamples() const
Return the total number of branch samples that have the function as the branch target.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
static cl::opt< unsigned > SampleProfileRecordCoverage("sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"), cl::desc("Emit a warning if less than N% of records in the input profile " "are matched to the IR."))
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Interval::succ_iterator succ_end(Interval *I)
iterator find(const_arg_type_t< KeyT > Val)
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
static cl::opt< unsigned > SampleProfileMaxPropagateIterations("sample-profile-max-propagate-iterations", cl::init(100), cl::desc("Maximum number of iterations to go through when propagating " "sample block/edge weights through the CFG."))
DISubprogram * getSubprogram() const
Get the attached subprogram.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
FunctionSamples * getSamplesFor(const Function &F)
Return the samples collected for function F.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::error_code read()
The interface to read sample profiles from the associated file.
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.
FunctionSamples * getOrCreateSamplesFor(const Function &F)
Return the samples collected for function F, create empty FunctionSamples if it doesn't exist...
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes...
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Function::ProfileCount ProfileCount
Represent the analysis usage information of a pass.
Interval::pred_iterator pred_end(Interval *I)
DenseMap< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
void initializeSampleProfileLoaderLegacyPassPass(PassRegistry &)
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.
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
std::map< std::string, FunctionSamples, std::less<> > FunctionSamplesMap
Class to represent profile counts.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
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.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
StringRef getFuncNameInModule(const Module *M) const
Return the original function name if it exists in Module M.
static cl::opt< bool > ProfileMergeInlinee("sample-profile-merge-inlinee", cl::Hidden, cl::init(false), cl::desc("Merge past inlinee's profile to outline version if sample " "profile loader decided not to inline a call site."))
Optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
void sort(IteratorTy Start, IteratorTy End)
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName...
A function analysis which provides an AssumptionCache.
virtual std::unique_ptr< ProfileSymbolList > getProfileSymbolList()
const InstListType & getInstList() const
Return the underlying instruction list container.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
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.
static unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
static cl::opt< int > SampleColdCallSiteThreshold("sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining cold callsites"))
virtual std::vector< StringRef > * getNameTable()
It includes all the names that have samples either in outline instance or inline instance.
static cl::opt< bool > ProfileSampleAccurate("profile-sample-accurate", cl::Hidden, cl::init(false), cl::desc("If the sample profile is accurate, we will mark all un-sampled " "callsite and function as having 0 samples. Otherwise, treat " "un-sampled callsites and functions conservatively as unknown. "))
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
StringMap< FunctionSamples > & getProfiles()
Return all the profiles.
amdgpu Simplify well known AMD library false FunctionCallee Callee
int getCost() const
Get the inline cost estimate.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static void clear(coro::Shape &Shape)
iterator insert(iterator I, T &&Elt)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
An analysis pass to compute the CallGraph for a Module.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
The basic data container for the call graph of a Module of IR.
unsigned getBaseDiscriminator() const
Returns the base discriminator stored in the discriminator.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represents the relative location of an instruction.
static cl::opt< unsigned > SampleProfileSampleCoverage("sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"), cl::desc("Emit a warning if less than N% of samples in the input profile " "are matched to the IR."))
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
const Function * getParent() const
Return the enclosing method, or null if none.
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)
StringRef getName() const
Return the function name.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void updateProfileCallee(Function *Callee, int64_t entryDelta, const ValueMap< const Value *, WeakTrackingVH > *VMap=nullptr)
Updates profile information by adjusting the entry count by adding entryDelta then scaling callsite i...
INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", "Sample Profile loader", false, false) INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Provides ErrorOr<T> smart pointer.
ProfileSummary & getSummary() const
Return the profile summary.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
sample Sample Profile loader
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
StringSet - A wrapper for StringMap that provides set-like functionality.
Sample-based profile reader.
This class implements an extremely fast bulk output stream that can only output to a stream...
print Print MemDeps of function
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
StringRef - Represent a constant reference to a string, i.e.
static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, const PPCSubtarget &Subtarget, bool isPatchPoint)
A container for analyses that lazily runs them and caches their results.
uint64_t getEntrySamples() const
Return the sample count of the first instruction of the function.
static cl::opt< bool > NoWarnSampleUnused("no-warn-sample-unused", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on warnings about function with " "samples but without debug information to use those samples. "))
This header defines various interfaces for pass management in LLVM.
static cl::opt< bool > ProfileSizeInline("sample-profile-inline-size", cl::Hidden, cl::init(false), cl::desc("Inline cold call sites in profile loader if it's beneficial " "for code size."))
Diagnostic information for the sample profiler.
void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind)
Attach profile summary metadata to this module.
void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
This file provides the interface for the sampled PGO loader pass.
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
const BasicBlock * getParent() const
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...