117 #include <unordered_map> 121 using namespace llvm;
124 #define DEBUG_TYPE "pgo-instrumentation" 126 STATISTIC(NumOfPGOInstrument,
"Number of edges instrumented.");
127 STATISTIC(NumOfPGOSelectInsts,
"Number of select instruction instrumented.");
128 STATISTIC(NumOfPGOMemIntrinsics,
"Number of mem intrinsics instrumented.");
129 STATISTIC(NumOfPGOEdge,
"Number of edges.");
130 STATISTIC(NumOfPGOBB,
"Number of basic-blocks.");
131 STATISTIC(NumOfPGOSplit,
"Number of critical edge splits.");
132 STATISTIC(NumOfPGOFunc,
"Number of functions having valid profile counts.");
133 STATISTIC(NumOfPGOMismatch,
"Number of functions having mismatch profile.");
134 STATISTIC(NumOfPGOMissing,
"Number of functions without profile.");
135 STATISTIC(NumOfPGOICall,
"Number of indirect call value instrumentations.");
142 cl::desc(
"Specify the path of profile data file. This is" 143 "mainly for test purpose."));
149 cl::desc(
"Disable Value Profiling"));
155 cl::desc(
"Max number of annotations for a single indirect " 162 cl::desc(
"Max number of preicise value annotations for a single memop" 169 cl::desc(
"Append function hash to the name of COMDAT function to avoid " 170 "function hash mismatch due to the preinliner"));
176 cl::desc(
"Use this option to turn on/off " 177 "warnings about missing profile data for " 184 cl::desc(
"Use this option to turn off/on " 185 "warnings about profile cfg mismatch."));
193 cl::desc(
"The option is used to turn on/off " 194 "warnings about hash mismatch for comdat " 200 cl::desc(
"Use this option to turn on/off SELECT " 201 "instruction instrumentation. "));
206 cl::desc(
"A boolean option to show CFG dag or text " 207 "with raw profile counts from " 208 "profile data. See also option " 209 "-pgo-view-counts. To limit graph " 210 "display to only one function, use " 211 "filtering option -view-bfi-func-name."),
219 cl::desc(
"Use this option to turn on/off " 220 "memory intrinsic size profiling."));
225 cl::desc(
"When this option is on, the annotated " 226 "branch probability will be emitted as " 227 "optimization remarks: -{Rpass|" 228 "pass-remarks}=pgo-instrumentation"));
243 return std::string();
248 return std::string();
260 else if (CV->
isOne())
278 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
282 struct SelectInstVisitor :
public InstVisitor<SelectInstVisitor> {
286 unsigned *CurCtrIdx =
nullptr;
287 unsigned TotalNumCtrs = 0;
289 uint64_t FuncHash = 0;
290 PGOUseFunc *UseFunc =
nullptr;
292 SelectInstVisitor(
Function &Func) :
F(Func) {}
304 void instrumentSelects(
Function &Func,
unsigned *Ind,
unsigned TotalNC,
306 Mode = VM_instrument;
308 TotalNumCtrs = TotalNC;
315 void annotateSelects(
Function &Func, PGOUseFunc *UF,
unsigned *Ind) {
330 unsigned getNumOfSelectInsts()
const {
return NSIs; }
334 struct MemIntrinsicVisitor :
public InstVisitor<MemIntrinsicVisitor> {
338 unsigned CurCtrId = 0;
339 unsigned TotalNumCtrs = 0;
341 uint64_t FuncHash = 0;
342 PGOUseFunc *UseFunc =
nullptr;
343 std::vector<Instruction *> Candidates;
345 MemIntrinsicVisitor(
Function &Func) :
F(Func) {}
347 void countMemIntrinsics(
Function &Func) {
353 void instrumentMemIntrinsics(
Function &Func,
unsigned TotalNC,
355 Mode = VM_instrument;
356 TotalNumCtrs = TotalNC;
362 std::vector<Instruction *> findMemIntrinsics(
Function &Func) {
375 unsigned getNumOfMemIntrinsics()
const {
return NMemIs; }
378 class PGOInstrumentationGenLegacyPass :
public ModulePass {
382 PGOInstrumentationGenLegacyPass() :
ModulePass(ID) {
387 StringRef getPassName()
const override {
return "PGOInstrumentationGenPass"; }
390 bool runOnModule(
Module &M)
override;
397 class PGOInstrumentationUseLegacyPass :
public ModulePass {
402 PGOInstrumentationUseLegacyPass(std::string Filename =
"")
403 :
ModulePass(ID), ProfileFileName(std::move(Filename)) {
410 StringRef getPassName()
const override {
return "PGOInstrumentationUsePass"; }
413 std::string ProfileFileName;
415 bool runOnModule(
Module &M)
override;
427 "PGO instrumentation.",
false,
false)
434 return new PGOInstrumentationGenLegacyPass();
440 "Read PGO instrumentation profile.",
false,
false)
447 return new PGOInstrumentationUseLegacyPass(Filename.str());
463 bool Removed =
false;
464 bool IsCritical =
false;
467 : SrcBB(Src), DestBB(Dest), Weight(
W) {}
470 const std::string infoString()
const {
471 return (
Twine(Removed ?
"-" :
" ") + (InMST ?
" " :
"*") +
472 (IsCritical ?
"c" :
" ") +
" W=" +
Twine(Weight)).str();
482 BBInfo(
unsigned IX) : Group(
this),
Index(IX) {}
485 const std::string infoString()
const {
486 return (
Twine(
"Index=") +
Twine(Index)).str();
491 template <
class Edge,
class BBInfo>
class FuncPGOInstrumentation {
496 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
498 void computeCFGHash();
499 void renameComdatFunction();
502 std::vector<std::vector<Instruction *>> ValueSites;
503 SelectInstVisitor SIVisitor;
504 MemIntrinsicVisitor MIVisitor;
505 std::string FuncName;
509 uint64_t FunctionHash = 0;
525 void dumpInfo(std::string Str =
"")
const {
527 Twine(FunctionHash) +
"\t" + Str);
530 FuncPGOInstrumentation(
532 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
535 :
F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
536 SIVisitor(Func), MIVisitor(Func), MST(F, BPI,
BFI) {
538 SIVisitor.countSelects(Func);
539 MIVisitor.countMemIntrinsics(Func);
540 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
541 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
543 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
547 if (!ComdatMembers.empty())
548 renameComdatFunction();
551 NumOfPGOBB += MST.
BBInfos.size();
557 NumOfPGOInstrument++;
565 unsigned getNumCounters() {
566 unsigned NumCounters = 0;
567 for (
auto &E : this->MST.
AllEdges) {
568 if (!E->InMST && !E->Removed)
571 return NumCounters + SIVisitor.getNumOfSelectInsts();
579 template <
class Edge,
class BBInfo>
580 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
581 std::vector<char> Indexes;
587 auto BI = findBBInfo(Succ);
591 for (
int J = 0; J < 4; J++)
592 Indexes.push_back((
char)(Index >> (J * 8)));
596 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
597 (uint64_t)ValueSites[IPVK_IndirectCallTarget].
size() << 48 |
598 (uint64_t)MST.AllEdges.size() << 32 | JC.
getCRC();
599 LLVM_DEBUG(
dbgs() <<
"Function Hash Computation for " << F.getName() <<
":\n" 600 <<
" CRC = " << JC.
getCRC()
601 <<
", Selects = " << SIVisitor.getNumOfSelectInsts()
602 <<
", Edges = " << MST.AllEdges.size() <<
", ICSites = " 603 << ValueSites[IPVK_IndirectCallTarget].size()
604 <<
", Hash = " << FunctionHash <<
"\n";);
610 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
622 for (
auto &&CM :
make_range(ComdatMembers.equal_range(C))) {
623 if (dyn_cast<GlobalAlias>(CM.second))
633 template <
class Edge,
class BBInfo>
634 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
637 std::string OrigName =
F.getName().str();
638 std::string NewFuncName =
639 Twine(
F.getName() +
"." +
Twine(FunctionHash)).str();
640 F.setName(
Twine(NewFuncName));
642 FuncName =
Twine(FuncName +
"." +
Twine(FunctionHash)).
str();
648 if (!
F.hasComdat()) {
652 F.setComdat(NewComdat);
657 Comdat *OrigComdat =
F.getComdat();
658 std::string NewComdatName =
663 for (
auto &&CM :
make_range(ComdatMembers.equal_range(OrigComdat))) {
664 if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
666 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &
F);
667 std::string OrigGAName = GA->getName().str();
668 GA->setName(
Twine(GA->getName() +
"." +
Twine(FunctionHash)));
681 template <
class Edge,
class BBInfo>
682 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *
E) {
683 if (E->InMST || E->Removed)
689 if (SrcBB ==
nullptr)
691 if (DestBB ==
nullptr)
706 <<
" --> " << getBBInfo(DestBB).
Index <<
"\n");
709 assert(InstrBB &&
"Critical edge is not split");
719 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
723 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers,
true, BPI,
725 unsigned NumCounters = FuncInfo.getNumCounters();
729 for (
auto &E : FuncInfo.MST.AllEdges) {
730 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
735 assert(Builder.GetInsertPoint() != InstrBB->
end() &&
736 "Cannot get the Instrumentation point");
740 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
741 Builder.getInt32(I++)});
745 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
746 FuncInfo.FunctionHash);
752 unsigned NumIndirectCallSites = 0;
753 for (
auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
756 LLVM_DEBUG(
dbgs() <<
"Instrument one indirect call: CallSite Index = " 757 << NumIndirectCallSites <<
"\n");
760 "Cannot get the Instrumentation point");
764 Builder.
getInt64(FuncInfo.FunctionHash),
766 Builder.
getInt32(IPVK_IndirectCallTarget),
767 Builder.
getInt32(NumIndirectCallSites++)});
769 NumOfPGOICall += NumIndirectCallSites;
772 FuncInfo.MIVisitor.instrumentMemIntrinsics(
773 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
779 struct PGOUseEdge :
public PGOEdge {
780 bool CountValid =
false;
781 uint64_t CountValue = 0;
784 : PGOEdge(Src, Dest,
W) {}
787 void setEdgeCount(uint64_t
Value) {
793 const std::string infoString()
const {
795 return PGOEdge::infoString();
796 return (
Twine(PGOEdge::infoString()) +
" Count=" +
Twine(CountValue))
804 struct UseBBInfo :
public BBInfo {
805 uint64_t CountValue = 0;
807 int32_t UnknownCountInEdge = 0;
808 int32_t UnknownCountOutEdge = 0;
810 DirectEdges OutEdges;
812 UseBBInfo(
unsigned IX) : BBInfo(IX), CountValid(
false) {}
814 UseBBInfo(
unsigned IX, uint64_t
C)
815 : BBInfo(IX), CountValue(C), CountValid(
true) {}
818 void setBBInfoCount(uint64_t
Value) {
824 const std::string infoString()
const {
826 return BBInfo::infoString();
827 return (
Twine(BBInfo::infoString()) +
" Count=" +
Twine(CountValue)).str();
836 for (
auto &E : Edges) {
839 Total += E->CountValue;
849 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
852 :
F(Func), M(Modu),
BFI(BFIin),
853 FuncInfo(Func, ComdatMembers,
false, BPI, BFIin),
854 FreqAttr(FFA_Normal) {}
860 void populateCounters();
866 void annotateValueSites();
872 void annotateIrrLoopHeaderWeights();
875 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
878 FuncFreqAttr getFuncFreqAttr()
const {
return FreqAttr; }
881 uint64_t getFuncHash()
const {
return FuncInfo.FunctionHash; }
887 UseBBInfo &getBBInfo(
const BasicBlock *BB)
const {
888 return FuncInfo.getBBInfo(BB);
892 UseBBInfo *findBBInfo(
const BasicBlock *BB)
const {
893 return FuncInfo.findBBInfo(BB);
898 void dumpInfo(std::string Str =
"")
const {
899 FuncInfo.dumpInfo(Str);
908 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
912 uint64_t ProgramMaxCount;
924 FuncFreqAttr FreqAttr;
927 void setInstrumentedCounts(
const std::vector<uint64_t> &CountFromProfile);
931 void setEdgeCount(DirectEdges &Edges, uint64_t
Value);
934 const std::string getFuncName()
const {
return FuncInfo.FuncName; }
939 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
940 if (ProgramMaxCount == 0)
946 if (EntryCount >= HotFunctionThreshold.
scale(ProgramMaxCount))
948 else if (MaxCount <= ColdFunctionThreshold.
scale(ProgramMaxCount))
957 void PGOUseFunc::setInstrumentedCounts(
958 const std::vector<uint64_t> &CountFromProfile) {
959 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
961 std::vector<PGOUseEdge *> WorkList;
962 for (
auto &E : FuncInfo.MST.AllEdges)
963 WorkList.push_back(E.get());
966 for (
auto &E : WorkList) {
970 uint64_t CountValue = CountFromProfile[I++];
972 getBBInfo(InstrBB).setBBInfoCount(CountValue);
973 E->setEdgeCount(CountValue);
981 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
982 NewEdge.setEdgeCount(CountValue);
984 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
985 NewEdge1.setEdgeCount(CountValue);
986 NewEdge1.InMST =
true;
987 getBBInfo(InstrBB).setBBInfoCount(CountValue);
989 ProfileCountSize = CountFromProfile.size();
995 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t
Value) {
996 for (
auto &E : Edges) {
999 E->setEdgeCount(Value);
1001 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1002 getBBInfo(E->DestBB).UnknownCountInEdge--;
1012 auto &Ctx = M->getContext();
1017 auto Err = IPE.
get();
1018 bool SkipWarning =
false;
1035 std::string Msg = IPE.
message() + std::string(
" ") +
F.getName().str();
1041 ProfileRecord = std::move(Result.
get());
1042 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1046 uint64_t ValueSum = 0;
1047 for (
unsigned I = 0, S = CountFromProfile.size();
I < S;
I++) {
1049 ValueSum += CountFromProfile[
I];
1054 getBBInfo(
nullptr).UnknownCountOutEdge = 2;
1055 getBBInfo(
nullptr).UnknownCountInEdge = 2;
1057 setInstrumentedCounts(CountFromProfile);
1064 void PGOUseFunc::populateCounters() {
1066 for (
auto &E : FuncInfo.MST.AllEdges) {
1072 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1073 UseBBInfo &DestInfo = getBBInfo(DestBB);
1074 SrcInfo.OutEdges.push_back(E.get());
1075 DestInfo.InEdges.push_back(E.get());
1076 SrcInfo.UnknownCountOutEdge++;
1077 DestInfo.UnknownCountInEdge++;
1081 DestInfo.UnknownCountInEdge--;
1082 SrcInfo.UnknownCountOutEdge--;
1085 bool Changes =
true;
1086 unsigned NumPasses = 0;
1094 UseBBInfo *Count = findBBInfo(&BB);
1095 if (Count ==
nullptr)
1097 if (!Count->CountValid) {
1098 if (Count->UnknownCountOutEdge == 0) {
1100 Count->CountValid =
true;
1102 }
else if (Count->UnknownCountInEdge == 0) {
1104 Count->CountValid =
true;
1108 if (Count->CountValid) {
1109 if (Count->UnknownCountOutEdge == 1) {
1115 if (Count->CountValue > OutSum)
1116 Total = Count->CountValue - OutSum;
1117 setEdgeCount(Count->OutEdges, Total);
1120 if (Count->UnknownCountInEdge == 1) {
1123 if (Count->CountValue > InSum)
1124 Total = Count->CountValue - InSum;
1125 setEdgeCount(Count->InEdges, Total);
1132 LLVM_DEBUG(
dbgs() <<
"Populate counts in " << NumPasses <<
" passes.\n");
1135 for (
auto &BB :
F) {
1136 auto BI = findBBInfo(&BB);
1139 assert(BI->CountValid &&
"BB count is not valid");
1142 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1144 uint64_t FuncMaxCount = FuncEntryCount;
1145 for (
auto &BB : F) {
1146 auto BI = findBBInfo(&BB);
1149 FuncMaxCount =
std::max(FuncMaxCount, BI->CountValue);
1151 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1154 FuncInfo.SIVisitor.annotateSelects(F,
this, &CountPosition);
1155 assert(CountPosition == ProfileCountSize);
1157 LLVM_DEBUG(FuncInfo.dumpInfo(
"after reading profile."));
1164 for (
auto &BB :
F) {
1168 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1169 isa<IndirectBrInst>(TI)))
1171 if (getBBInfo(&BB).CountValue == 0)
1175 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1176 unsigned Size = BBCountInfo.OutEdges.size();
1178 uint64_t MaxCount = 0;
1179 for (
unsigned s = 0; s <
Size; s++) {
1180 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1183 if (DestBB ==
nullptr)
1186 uint64_t EdgeCount = E->CountValue;
1187 if (EdgeCount > MaxCount)
1188 MaxCount = EdgeCount;
1189 EdgeCounts[SuccNum] = EdgeCount;
1197 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1203 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1204 LLVM_DEBUG(
dbgs() <<
"\nAnnotating irreducible loop header weights.\n");
1206 for (
auto &BB :
F) {
1212 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1218 void SelectInstVisitor::instrumentOneSelectInst(
SelectInst &
SI) {
1228 Builder.
getInt32(*CurCtrIdx), Step});
1232 void SelectInstVisitor::annotateOneSelectInst(
SelectInst &SI) {
1233 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1234 assert(*CurCtrIdx < CountFromProfile.size() &&
1235 "Out of bound access of counters");
1236 uint64_t SCounts[2];
1237 SCounts[0] = CountFromProfile[*CurCtrIdx];
1239 uint64_t TotalCount = 0;
1240 auto BI = UseFunc->findBBInfo(SI.
getParent());
1242 TotalCount = BI->CountValue;
1244 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1245 uint64_t MaxCount =
std::max(SCounts[0], SCounts[1]);
1250 void SelectInstVisitor::visitSelectInst(
SelectInst &SI) {
1262 instrumentOneSelectInst(SI);
1265 annotateOneSelectInst(SI);
1272 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(
MemIntrinsic &
MI) {
1278 assert(!dyn_cast<ConstantInt>(Length));
1287 void MemIntrinsicVisitor::visitMemIntrinsic(
MemIntrinsic &MI) {
1292 if (dyn_cast<ConstantInt>(Length))
1300 instrumentOneMemIntrinsic(MI);
1303 Candidates.push_back(&MI);
1310 void PGOUseFunc::annotateValueSites() {
1318 annotateValueSites(
Kind);
1323 unsigned ValueSiteIndex = 0;
1324 auto &ValueSites = FuncInfo.ValueSites[
Kind];
1325 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1326 if (NumValueSites != ValueSites.size()) {
1327 auto &Ctx = M->getContext();
1329 M->getName().data(),
1330 Twine(
"Inconsistent number of value sites for kind = ") +
Twine(Kind) +
1331 " in " +
F.getName().str(),
1336 for (
auto &
I : ValueSites) {
1337 LLVM_DEBUG(
dbgs() <<
"Read one value site profile (kind = " << Kind
1338 <<
"): Index = " << ValueSiteIndex <<
" out of " 1339 << NumValueSites <<
"\n");
1341 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1352 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1356 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1359 if (!TT.supportsCOMDAT())
1363 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1370 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1375 ComdatMembers.insert(std::make_pair(
C, &
F));
1377 if (
Comdat *
C = GV.getComdat())
1378 ComdatMembers.insert(std::make_pair(
C, &GV));
1380 if (
Comdat *
C = GA.getComdat())
1381 ComdatMembers.insert(std::make_pair(
C, &GA));
1388 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1392 if (
F.isDeclaration())
1394 auto *BPI = LookupBPI(
F);
1395 auto *
BFI = LookupBFI(
F);
1401 bool PGOInstrumentationGenLegacyPass::runOnModule(
Module &M) {
1406 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(
F).getBPI();
1409 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
1439 if (
Error E = ReaderOrErr.takeError()) {
1447 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1448 std::move(ReaderOrErr.get());
1455 if (!PGOReader->isIRLevelProfile()) {
1457 ProfileFileName.
data(),
"Not an IR level instrumentation profile"));
1461 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1463 std::vector<Function *> HotFunctions;
1464 std::vector<Function *> ColdFunctions;
1466 if (
F.isDeclaration())
1468 auto *BPI = LookupBPI(
F);
1469 auto *
BFI = LookupBFI(
F);
1473 PGOUseFunc Func(
F, &M, ComdatMembers, BPI,
BFI);
1474 if (!Func.readCounters(PGOReader.get()))
1476 Func.populateCounters();
1477 Func.setBranchWeights();
1478 Func.annotateValueSites();
1479 Func.annotateIrrLoopHeaderWeights();
1480 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1481 if (FreqAttr == PGOUseFunc::FFA_Cold)
1482 ColdFunctions.push_back(&
F);
1483 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1484 HotFunctions.push_back(&
F);
1489 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1490 llvm::make_unique<BranchProbabilityInfo>(
F, LI);
1491 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1492 llvm::make_unique<BlockFrequencyInfo>(
F, *NewBPI, LI);
1496 dbgs() <<
"pgo-view-counts: " << Func.getFunc().getName() <<
"\n";
1497 NewBFI->print(
dbgs());
1507 ViewGraph(&Func,
Twine(
"PGORawCounts_") + Func.getFunc().getName());
1509 dbgs() <<
"pgo-view-raw-counts: " << Func.getFunc().getName() <<
"\n";
1514 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1519 for (
auto &
F : HotFunctions) {
1520 F->addFnAttr(Attribute::InlineHint);
1521 LLVM_DEBUG(
dbgs() <<
"Set inline attribute to function: " <<
F->getName()
1524 for (
auto &
F : ColdFunctions) {
1526 LLVM_DEBUG(
dbgs() <<
"Set cold attribute to function: " <<
F->getName()
1533 : ProfileFileName(
std::move(Filename)) {
1556 bool PGOInstrumentationUseLegacyPass::runOnModule(
Module &M) {
1561 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(
F).getBPI();
1564 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
1574 std::string SimpleNodeName;
1582 uint64_t MaxCount) {
1584 assert(MaxCount > 0 &&
"Bad max count");
1587 for (
const auto &ECI : EdgeCounts)
1597 if (BrCondStr.empty())
1601 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1602 [](uint64_t w1, uint64_t w2) {
return w1 + w2; });
1603 uint64_t TotalCount =
1604 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
1605 [](uint64_t c1, uint64_t c2) {
return c1 + c2; });
1609 std::string BranchProbStr;
1612 OS <<
" (total count : " << TotalCount <<
")";
1618 << BrCondStr <<
" is true with probability : " << BranchProbStr;
1628 MDB.createIrrLoopHeaderWeight(Count));
1637 return &G->getFunc().front();
1660 return G->getFunc().getName();
1668 UseBBInfo *BI = Graph->findBBInfo(Node);
1670 if (BI && BI->CountValid)
1671 OS << BI->CountValue <<
"\\l";
1678 for (
auto BI = Node->
begin(); BI != Node->
end(); ++BI) {
1680 if (!isa<SelectInst>(
I))
1683 OS <<
"SELECT : { T = ";
1685 bool HasProf =
I->extractProfMetadata(TC, FC);
1687 OS <<
"Unknown, F = Unknown }\\l";
1689 OS << TC <<
", F = " << FC <<
" }\\l";
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge *> Edges)
void push_back(const T &Elt)
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
void setProfMetadata(Module *M, Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
ModulePass * createPGOInstrumentationGenLegacyPass()
static cl::opt< bool > NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on " "warnings about profile cfg mismatch."))
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Base class for instruction visitors.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
static cl::opt< bool > PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, cl::desc("Use this option to turn on/off " "warnings about missing profile data for " "functions."))
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static ChildIteratorType child_begin(const NodeRef N)
std::vector< std::unique_ptr< Edge > > AllEdges
Diagnostic information for the PGO profiler.
Available for inspection, not emission.
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
An efficient, type-erasing, non-owning reference to a callable.
INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", "PGO instrumentation.", false, false) INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
virtual std::string message() const
Return the error message as a string.
Externally visible function.
static cl::opt< bool > PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off " "memory intrinsic size profiling."))
uint64_t getMaximumFunctionCount()
Return the maximum of all known function counts.
STATISTIC(NumFunctions, "Total number of functions")
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
Error takeError()
Take ownership of the stored error.
Value * getLength() const
Base class for error info classes.
An union-find based Minimum Spanning Tree for CFG.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Function::ProfileCount ProfileCount
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
PGOInstrumentationUse(std::string Filename="")
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
LLVMContext & getContext() const
Get the global data context.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
Legacy analysis pass which computes BlockFrequencyInfo.
static std::string getGraphName(const PGOUseFunc *G)
VisitMode
The select instruction visitor plays three roles specified by the mode.
Tagged union holding either a T or a Error.
This file implements a class to represent arbitrary precision integral constant values and operations...
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...
static bool isSimple(Instruction *I)
Analysis pass which computes BranchProbabilityInfo.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
ValTy * getCalledValue() const
Return the pointer to function that is being called.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
Type * getType() const
All values are typed, get the type of this value.
static cl::opt< bool > DisableValueProfiling("disable-vp", cl::init(false), cl::Hidden, cl::desc("Disable Value Profiling"))
static NodeRef getEntryNode(const PGOUseFunc *G)
static bool isIndirectBrTarget(BasicBlock *BB)
static void createIRLevelProfileFlagVariable(Module &M)
void setComdat(Comdat *C)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
static void setBranchWeights(SwitchInst *SI, ArrayRef< uint32_t > Weights)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void initializePGOInstrumentationGenLegacyPassPass(PassRegistry &)
static bool InstrumentAllFunctions(Module &M, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
static bool canRenameComdat(Function &F, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
static nodes_iterator nodes_end(const PGOUseFunc *G)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
amdgpu Simplify well known AMD library false Value * Callee
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
instrprof_error get() const
Legacy analysis pass which computes BranchProbabilityInfo.
Value * getOperand(unsigned i) const
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static ChildIteratorType child_end(const NodeRef N)
Interval::succ_iterator succ_end(Interval *I)
static cl::opt< unsigned > MaxNumMemOPAnnotations("memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of preicise value annotations for a single memop" "intrinsic"))
std::string message() const override
Return the error message as a string.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
StringRef getName() const
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
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.
void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
static StringRef getPredicateName(Predicate P)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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...
Represent the analysis usage information of a pass.
static cl::opt< PGOViewCountsType > PGOViewRawCounts("pgo-view-raw-counts", cl::Hidden, cl::desc("A boolean option to show CFG dag or text " "with raw profile counts from " "profile data. See also option " "-pgo-view-counts. To limit graph " "display to only one function, use " "filtering option -view-bfi-func-name."), cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), clEnumValN(PGOVCT_Graph, "graph", "show a graph."), clEnumValN(PGOVCT_Text, "text", "show in text.")))
static cl::opt< bool > DoComdatRenaming("do-comdat-renaming", cl::init(false), cl::Hidden, cl::desc("Append function hash to the name of COMDAT function to avoid " "function hash mismatch due to the preinliner"))
ModulePass * createPGOInstrumentationUseLegacyPass(StringRef Filename=StringRef(""))
This instruction compares its operands according to the predicate given to the constructor.
static std::string getBranchCondString(Instruction *TI)
Interval::pred_iterator pred_end(Interval *I)
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
static cl::opt< bool > NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), cl::Hidden, cl::desc("The option is used to turn on/off " "warnings about hash mismatch for comdat " "functions."))
void initializePGOInstrumentationUseLegacyPassPass(PassRegistry &)
DenseMap< const BasicBlock *, std::unique_ptr< BBInfo > > BBInfos
const Value * getCondition() const
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
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.
Class to represent profile counts.
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
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.
Triple - Helper class for working with autoconf configuration names.
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
BBInfo * findBBInfo(const BasicBlock *BB) const
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
DOTGraphTraits(bool isSimple=false)
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
static nodes_iterator nodes_begin(const PGOUseFunc *G)
static cl::opt< bool > PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off SELECT " "instruction instrumentation. "))
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.
pgo instr PGO instrumentation
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
uint64_t scale(uint64_t Num) const
Scale a large integer.
reference get()
Returns a reference to the stored T value.
bool isConditional() const
void dumpEdges(raw_ostream &OS, const Twine &Message) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class for arbitrary precision integers.
static cl::opt< std::string > PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile data file. This is" "mainly for test purpose."))
BBInfo & getBBInfo(const BasicBlock *BB) const
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
const Comdat * getComdat() const
pgo instr Read PGO instrumentation profile
Predicate getPredicate() const
Return the predicate for this instruction.
Analysis providing branch probability information.
unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Profiling information for a single function.
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
static bool annotateAllFunctions(Module &M, StringRef ProfileFileName, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
bool SplitIndirectBrCriticalEdges(Function &F, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
StringRef getName() const
Return a constant reference to the value's name.
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...
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
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)
Keep one copy of named function when linking (weak)
static cl::opt< unsigned > MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of annotations for a single indirect " "call callsite"))
std::string str() const
Return the twine contents as a std::string.
std::vector< Instruction * > findIndirectCallSites(Function &F)
cl::opt< PGOViewCountsType > PGOViewCounts
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
TerminatorInst::SuccIterator< const TerminatorInst *, const BasicBlock > succ_const_iterator
static void instrumentOneFunc(Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
A raw_ostream that writes to an std::string.
LLVM Value Representation.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void update(ArrayRef< char > Data)
Lightweight error class with error context and mandatory checking.
BasicBlock::iterator GetInsertPoint() const
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
cl::opt< std::string > ViewBlockFreqFuncName
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
A container for analyses that lazily runs them and caches their results.
static void collectComdatMembers(Module &M, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
static std::string getSimpleNodeName(const BasicBlock *Node)
static cl::opt< bool > EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, cl::desc("When this option is on, the annotated " "branch probability will be emitted as " "optimization remarks: -{Rpass|" "pass-remarks}=pgo-instrumentation"))
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
const BasicBlock * getParent() const
SelectionKind getSelectionKind() const
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...