65#define DEBUG_TYPE "instrprof"
74 "debug-info-correlate",
75 cl::desc(
"Use debug info to correlate profiles. (Deprecated, use "
76 "-profile-correlate=debug-info)"),
81 cl::desc(
"Use debug info or binary file to correlate profiles."),
84 "No profile correlation"),
86 "Use debug info to correlate"),
88 "Use binary to correlate")));
94 "hash-based-counter-split",
95 cl::desc(
"Rename counter variable of a comdat function based on cfg hash"),
99 RuntimeCounterRelocation(
"runtime-counter-relocation",
100 cl::desc(
"Enable relocating counters at runtime."),
105 cl::desc(
"Do static counter allocation for value profiler"),
109 "vp-counters-per-site",
110 cl::desc(
"The average number of profile counters allocated "
111 "per value profiling site."),
119 "instrprof-atomic-counter-update-all",
120 cl::desc(
"Make all profile counter updates atomic (for testing only)"),
124 "atomic-counter-update-promoted",
125 cl::desc(
"Do counter update using atomic fetch add "
126 " for promoted counters only"),
130 "atomic-first-counter",
131 cl::desc(
"Use atomic fetch add for first counter in a function (usually "
132 "the entry counter)"),
136 "conditional-counter-update",
137 cl::desc(
"Do conditional counter updates in single byte counters mode)"),
146 cl::desc(
"Do counter register promotion"),
149 "max-counter-promotions-per-loop",
cl::init(20),
150 cl::desc(
"Max number counter promotions per loop to avoid"
151 " increasing register pressure too much"));
155 MaxNumOfPromotions(
"max-counter-promotions",
cl::init(-1),
156 cl::desc(
"Max number of allowed counter promotions"));
159 "speculative-counter-promotion-max-exiting",
cl::init(3),
160 cl::desc(
"The max number of exiting blocks of a loop to allow "
161 " speculative counter promotion"));
164 "speculative-counter-promotion-to-loop",
165 cl::desc(
"When the option is false, if the target block is in a loop, "
166 "the promotion will be disallowed unless the promoted counter "
167 " update can be further/iteratively promoted into an acyclic "
171 "iterative-counter-promotion",
cl::init(
true),
172 cl::desc(
"Allow counter promotion across the whole loop nest."));
175 "skip-ret-exit-block",
cl::init(
true),
176 cl::desc(
"Suppress counter promotion if exit blocks contain ret."));
180 cl::desc(
"Do PGO instrumentation sampling"));
183 "sampled-instr-period",
184 cl::desc(
"Set the profile instrumentation sample period. For each sample "
185 "period, a fixed number of consecutive samples will be recorded. "
186 "The number is controlled by 'sampled-instr-burst-duration' flag. "
187 "The default sample period of 65535 is optimized for generating "
188 "efficient code that leverages unsigned integer wrapping in "
193 "sampled-instr-burst-duration",
194 cl::desc(
"Set the profile instrumentation burst duration, which can range "
195 "from 0 to one less than the value of 'sampled-instr-period'. "
196 "This number of samples will be recorded for each "
197 "'sampled-instr-period' count update. Setting to 1 enables "
198 "simple sampling, in which case it is recommended to set "
199 "'sampled-instr-period' to a prime number."),
202using LoadStorePair = std::pair<Instruction *, Instruction *>;
205 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
211 return cast<ConstantInt>(MD->getValue())->getZExtValue();
214static bool enablesValueProfiling(
const Module &M) {
216 getIntModuleFlagOrZero(M,
"EnableValueProfiling") != 0;
220static bool profDataReferencedByCode(
const Module &M) {
221 return enablesValueProfiling(M);
224class InstrLowerer final {
229 :
M(
M), Options(Options),
TT(
Triple(
M.getTargetTriple())), IsCS(IsCS),
230 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(
M)) {}
243 const bool DataReferencedByCode;
245 struct PerFunctionProfileData {
246 uint32_t NumValueSites[IPVK_Last + 1] = {};
252 PerFunctionProfileData() =
default;
261 std::vector<GlobalValue *> CompilerUsedVars;
262 std::vector<GlobalValue *> UsedVars;
263 std::vector<GlobalVariable *> ReferencedNames;
266 std::vector<GlobalVariable *> ReferencedVTables;
268 size_t NamesSize = 0;
275 std::vector<LoadStorePair> PromotionCandidates;
277 int64_t TotalCountersPromoted = 0;
284 void promoteCounterLoadStores(
Function *
F);
287 bool isRuntimeCounterRelocationEnabled()
const;
290 bool isCounterPromotionEnabled()
const;
293 bool isSamplingEnabled()
const;
384 void emitVTableNames();
390 void emitRegistration();
394 bool emitRuntimeHook();
401 void emitInitialization();
413 PGOCounterPromoterHelper(
420 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
422 assert(isa<StoreInst>(S));
423 SSA.AddAvailableValue(PH,
Init);
427 for (
unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
433 Value *LiveInValue =
SSA.GetValueInMiddleOfBlock(ExitBlock);
434 Value *
Addr = cast<StoreInst>(Store)->getPointerOperand();
437 if (
auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(
Addr)) {
444 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
445 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
446 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
447 Addr = Builder.CreateIntToPtr(BiasInst,
450 if (AtomicCounterUpdatePromoted)
455 AtomicOrdering::SequentiallyConsistent);
457 LoadInst *OldVal = Builder.CreateLoad(Ty,
Addr,
"pgocount.promoted");
458 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
459 auto *NewStore = Builder.CreateStore(NewVal,
Addr);
462 if (IterativeCounterPromotion) {
463 auto *TargetLoop = LI.getLoopFor(ExitBlock);
465 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
482class PGOCounterPromoter {
487 : LoopToCandidates(LoopToCands),
L(CurLoop), LI(LI),
BFI(
BFI) {
494 L.getExitBlocks(LoopExitBlocks);
495 if (!isPromotionPossible(&L, LoopExitBlocks))
498 for (
BasicBlock *ExitBlock : LoopExitBlocks) {
499 if (BlockSet.
insert(ExitBlock).second &&
503 ExitBlocks.push_back(ExitBlock);
509 bool run(int64_t *NumPromoted) {
511 if (ExitBlocks.size() == 0)
519 if (SkipRetExitBlock) {
520 for (
auto *BB : ExitBlocks)
521 if (isa<ReturnInst>(BB->getTerminator()))
525 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
529 unsigned Promoted = 0;
530 for (
auto &Cand : LoopToCandidates[&L]) {
534 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
538 auto *BB = Cand.first->getParent();
542 auto PreheaderCount =
BFI->getBlockProfileCount(
L.getLoopPreheader());
545 if (PreheaderCount && (*PreheaderCount * 3) >= (*
InstrCount * 2))
549 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second,
SSA, InitVal,
550 L.getLoopPreheader(), ExitBlocks,
551 InsertPts, LoopToCandidates, LI);
554 if (Promoted >= MaxProm)
558 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
562 LLVM_DEBUG(
dbgs() << Promoted <<
" counters promoted for loop (depth="
563 <<
L.getLoopDepth() <<
")\n");
564 return Promoted != 0;
568 bool allowSpeculativeCounterPromotion(
Loop *LP) {
570 L.getExitingBlocks(ExitingBlocks);
572 if (ExitingBlocks.
size() == 1)
574 if (ExitingBlocks.
size() > SpeculativeCounterPromotionMaxExiting)
582 isPromotionPossible(
Loop *LP,
586 return isa<CatchSwitchInst>(
Exit->getTerminator());
601 unsigned getMaxNumOfPromotionsInLoop(
Loop *LP) {
604 if (!isPromotionPossible(LP, LoopExitBlocks))
615 if (ExitingBlocks.
size() == 1)
616 return MaxNumOfPromotionsPerLoop;
618 if (ExitingBlocks.
size() > SpeculativeCounterPromotionMaxExiting)
622 if (SpeculativeCounterPromotionToLoop)
623 return MaxNumOfPromotionsPerLoop;
626 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
627 for (
auto *TargetBlock : LoopExitBlocks) {
628 auto *TargetLoop = LI.
getLoopFor(TargetBlock);
631 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
632 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
634 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
635 PendingCandsInTarget);
648enum class ValueProfilingCallType {
666 InstrLowerer Lowerer(M, Options, GetTLI, IsCS);
667 if (!Lowerer.lower())
718 if (!isSamplingEnabled())
721 unsigned SampledBurstDuration = SampledInstrBurstDuration.getValue();
722 unsigned SampledPeriod = SampledInstrPeriod.getValue();
723 if (SampledBurstDuration >= SampledPeriod) {
725 "SampledPeriod needs to be greater than SampledBurstDuration");
727 bool UseShort = (SampledPeriod <= USHRT_MAX);
728 bool IsSimpleSampling = (SampledBurstDuration == 1);
731 bool IsFastSampling = (!IsSimpleSampling && SampledPeriod == 65535);
746 M.getGlobalVariable(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SAMPLING_VAR));
747 assert(SamplingVar &&
"SamplingVar not set properly");
751 Value *NewSamplingVarVal;
755 auto *LoadSamplingVar = CondBuilder.CreateLoad(SamplingVarTy, SamplingVar);
756 if (IsSimpleSampling) {
760 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
761 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
764 auto *DurationCond = CondBuilder.CreateICmpULE(
765 LoadSamplingVar, GetConstant(CondBuilder, SampledBurstDuration));
766 BranchWeight = MDB.createBranchWeights(
767 SampledBurstDuration, SampledPeriod + 1 - SampledBurstDuration);
769 DurationCond,
I,
false, BranchWeight);
772 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
773 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
774 I->moveBefore(ThenTerm);
783 auto *PeriodCond = PeriodCondBuilder.CreateICmpUGE(
784 NewSamplingVarVal, GetConstant(PeriodCondBuilder, SampledPeriod));
785 BranchWeight = MDB.createBranchWeights(1, SampledPeriod);
787 &ElseTerm, BranchWeight);
790 if (IsSimpleSampling)
791 I->moveBefore(ThenTerm);
794 ResetBuilder.CreateStore(GetConstant(ResetBuilder, 0), SamplingVar);
798bool InstrLowerer::lowerIntrinsics(
Function *
F) {
799 bool MadeChange =
false;
800 PromotionCandidates.clear();
808 if (
auto *IP = dyn_cast<InstrProfInstBase>(&Instr))
813 for (
auto *Instr : InstrProfInsts) {
815 if (
auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(Instr)) {
816 lowerIncrement(IPIS);
818 }
else if (
auto *IPI = dyn_cast<InstrProfIncrementInst>(Instr)) {
821 }
else if (
auto *IPC = dyn_cast<InstrProfTimestampInst>(Instr)) {
824 }
else if (
auto *IPC = dyn_cast<InstrProfCoverInst>(Instr)) {
827 }
else if (
auto *IPVP = dyn_cast<InstrProfValueProfileInst>(Instr)) {
828 lowerValueProfileInst(IPVP);
830 }
else if (
auto *IPMP = dyn_cast<InstrProfMCDCBitmapParameters>(Instr)) {
831 IPMP->eraseFromParent();
833 }
else if (
auto *IPBU = dyn_cast<InstrProfMCDCTVBitmapUpdate>(Instr)) {
834 lowerMCDCTestVectorBitmapUpdate(IPBU);
842 promoteCounterLoadStores(
F);
846bool InstrLowerer::isRuntimeCounterRelocationEnabled()
const {
848 if (
TT.isOSBinFormatMachO())
851 if (RuntimeCounterRelocation.getNumOccurrences() > 0)
852 return RuntimeCounterRelocation;
855 return TT.isOSFuchsia();
858bool InstrLowerer::isSamplingEnabled()
const {
859 if (SampledInstr.getNumOccurrences() > 0)
864bool InstrLowerer::isCounterPromotionEnabled()
const {
865 if (DoCounterPromotion.getNumOccurrences() > 0)
866 return DoCounterPromotion;
868 return Options.DoCounterPromotion;
871void InstrLowerer::promoteCounterLoadStores(
Function *
F) {
872 if (!isCounterPromotionEnabled())
879 std::unique_ptr<BlockFrequencyInfo>
BFI;
880 if (
Options.UseBFIInPromotion) {
881 std::unique_ptr<BranchProbabilityInfo> BPI;
886 for (
const auto &LoadStore : PromotionCandidates) {
893 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
901 PGOCounterPromoter Promoter(LoopPromotionCandidates, *
Loop, LI,
BFI.get());
902 Promoter.run(&TotalCountersPromoted);
908 if (TT.isOSFuchsia())
916 auto containsIntrinsic = [&](
int ID) {
918 return !
F->use_empty();
921 return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
922 containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
923 containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
924 containsIntrinsic(llvm::Intrinsic::instrprof_timestamp) ||
925 containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
928bool InstrLowerer::lower() {
929 bool MadeChange =
false;
931 if (NeedsRuntimeHook)
932 MadeChange = emitRuntimeHook();
934 if (!IsCS && isSamplingEnabled())
941 if (!ContainsProfiling && !CoverageNamesVar)
950 for (
auto I = BB.
begin(), E = BB.
end();
I != E;
I++) {
951 if (
auto *Ind = dyn_cast<InstrProfValueProfileInst>(
I))
952 computeNumValueSiteCounts(Ind);
954 if (FirstProfInst ==
nullptr &&
955 (isa<InstrProfIncrementInst>(
I) || isa<InstrProfCoverInst>(
I)))
956 FirstProfInst = dyn_cast<InstrProfCntrInstBase>(
I);
958 if (
const auto &Params = dyn_cast<InstrProfMCDCBitmapParameters>(
I))
959 static_cast<void>(getOrCreateRegionBitmaps(Params));
966 if (FirstProfInst !=
nullptr) {
967 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
974 if (GV.hasMetadata(LLVMContext::MD_type))
975 getOrCreateVTableProfData(&GV);
978 MadeChange |= lowerIntrinsics(&
F);
980 if (CoverageNamesVar) {
981 lowerCoverageData(CoverageNamesVar);
996 if (!NeedsRuntimeHook && ContainsProfiling)
1001 emitInitialization();
1007 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
1012 if (
auto AK = TLI.getExtAttrForI32Param(
false))
1013 AL = AL.addParamAttribute(M.getContext(), 2, AK);
1015 assert((CallType == ValueProfilingCallType::Default ||
1016 CallType == ValueProfilingCallType::MemOp) &&
1017 "Must be Default or MemOp");
1018 Type *ParamTypes[] = {
1019#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
1022 auto *ValueProfilingCallTy =
1024 StringRef FuncName = CallType == ValueProfilingCallType::Default
1027 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
1034 auto &
PD = ProfileDataMap[
Name];
1045 "Value profiling is not yet supported with lightweight instrumentation");
1047 auto It = ProfileDataMap.find(
Name);
1048 assert(It != ProfileDataMap.end() && It->second.DataVar &&
1049 "value profiling detected in function with no counter incerement");
1055 Index += It->second.NumValueSites[Kind];
1059 llvm::InstrProfValueKind::IPVK_MemOPSize);
1079 if (
auto AK = TLI->getExtAttrForI32Param(
false))
1080 Call->addParamAttr(2, AK);
1102 if (
TT.supportsCOMDAT())
1103 Bias->
setComdat(
M.getOrInsertComdat(VarName));
1109 auto *
Counters = getOrCreateRegionCounters(
I);
1112 if (isa<InstrProfTimestampInst>(
I))
1118 if (!isRuntimeCounterRelocationEnabled())
1122 Function *Fn =
I->getParent()->getParent();
1123 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
1127 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias,
"profc_bias");
1129 BiasLI->
setMetadata(LLVMContext::MD_invariant_load,
1138Function *InstrLowerer::createRMWOrFunc() {
1139 auto &Ctx =
M.getContext();
1146 auto *ArgAddr = Fn->
getArg(0);
1147 auto *ArgVal = Fn->
getArg(1);
1152 auto *Bitmap = Builder.
CreateLoad(Int8Ty, ArgAddr,
"mcdc.bits");
1154 if (
Options.Atomic || AtomicCounterUpdateAll) {
1164 Builder.
CreateCondBr(ShouldStore, ThenTerm, ElseTerm, Unlikely);
1169 ThenBuilder.CreateRetVoid();
1172 ElseBuilder.CreateRetVoid();
1193 RMWOrFunc = createRMWOrFunc();
1199 auto *Bitmaps = getOrCreateRegionBitmaps(
I);
1200 if (!isRuntimeCounterRelocationEnabled())
1208 auto *BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias,
"profbm_bias");
1210 BiasLI->
setMetadata(LLVMContext::MD_invariant_load,
1215 return Builder.
CreatePtrAdd(Bitmaps, BiasLI,
"profbm_addr");
1219 auto *
Addr = getCounterAddress(CoverInstruction);
1221 if (ConditionalCounterUpdate) {
1223 auto &Ctx = CoverInstruction->
getParent()->getContext();
1237void InstrLowerer::lowerTimestamp(
1240 "timestamp probes are always the first probe for a function");
1241 auto &Ctx =
M.getContext();
1242 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1246 auto Callee =
M.getOrInsertFunction(
1247 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SET_TIMESTAMP), CalleeTy);
1253 auto *
Addr = getCounterAddress(Inc);
1256 if (
Options.Atomic || AtomicCounterUpdateAll ||
1265 if (isCounterPromotionEnabled())
1266 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
1271void InstrLowerer::lowerCoverageData(
GlobalVariable *CoverageNamesVar) {
1276 Value *
V =
NC->stripPointerCasts();
1277 assert(isa<GlobalVariable>(V) &&
"Missing reference to function name");
1281 ReferencedNames.push_back(
Name);
1282 if (isa<ConstantExpr>(
NC))
1283 NC->dropAllReferences();
1288void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1294 auto *BitmapAddr = getBitmapAddress(Update);
1299 Builder.
CreateLoad(Int32Ty, MCDCCondBitmapAddr,
"mcdc.temp"),
1304 auto *BitmapByteOffset = Builder.
CreateLShr(Temp, 0x3);
1308 auto *BitmapByteAddr =
1320 Builder.
Insert(getRMWOrCall(BitmapByteAddr, ShiftedVal));
1334 return (Prefix +
Name).str();
1340 return (Prefix +
Name).str();
1341 return (Prefix +
Name +
"." +
Twine(FuncHash)).str();
1349 if (!profDataReferencedByCode(*
F->getParent()))
1353 bool HasAvailableExternallyLinkage =
F->hasAvailableExternallyLinkage();
1354 if (!
F->hasLinkOnceLinkage() && !
F->hasLocalLinkage() &&
1355 !HasAvailableExternallyLinkage)
1361 if (HasAvailableExternallyLinkage &&
1362 F->hasFnAttribute(Attribute::AlwaysInline))
1368 if (
F->hasLocalLinkage() &&
F->hasComdat())
1378 return F->hasAddressTaken() ||
F->hasLinkOnceLinkage();
1425 Fn->
getName() +
".local", Fn);
1450 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1451 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF())
1464 bool UseComdat = (NeedComdat ||
TT.isOSBinFormatELF());
1479 StringRef GroupName =
TT.isOSBinFormatCOFF() && DataReferencedByCode
1482 Comdat *
C =
M.getOrInsertComdat(GroupName);
1502 if (!profDataReferencedByCode(*GV->
getParent()))
1529void InstrLowerer::getOrCreateVTableProfData(
GlobalVariable *GV) {
1531 "Value profiling is not supported with lightweight instrumentation");
1542 auto It = VTableDataMap.find(GV);
1543 if (It != VTableDataMap.end() && It->second)
1551 if (
TT.isOSBinFormatXCOFF()) {
1557 Type *DataTypes[] = {
1558#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1560#undef INSTR_PROF_VTABLE_DATA
1567 const std::string PGOVTableName =
getPGOName(*GV);
1574#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1576#undef INSTR_PROF_VTABLE_DATA
1584 Data->setVisibility(Visibility);
1588 maybeSetComdat(
Data, GV,
Data->getName());
1590 VTableDataMap[GV] =
Data;
1592 ReferencedVTables.push_back(GV);
1596 UsedVars.push_back(
Data);
1620 if (
TT.isOSBinFormatXCOFF()) {
1629 if (IPSK == IPSK_cnts) {
1633 Ptr = createRegionCounters(CntrIncrement, VarName, Linkage);
1634 }
else if (IPSK == IPSK_bitmap) {
1638 dyn_cast<InstrProfMCDCBitmapInstBase>(Inc);
1639 Ptr = createRegionBitmaps(BitmapUpdate, VarName, Linkage);
1644 Ptr->setVisibility(Visibility);
1648 Ptr->setLinkage(Linkage);
1649 maybeSetComdat(
Ptr, Fn, VarName);
1668 auto &
PD = ProfileDataMap[NamePtr];
1669 if (
PD.RegionBitmaps)
1670 return PD.RegionBitmaps;
1674 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1675 PD.RegionBitmaps = BitmapPtr;
1677 return PD.RegionBitmaps;
1684 auto &Ctx =
M.getContext();
1686 if (isa<InstrProfCoverInst>(Inc)) {
1690 std::vector<Constant *> InitialValues(NumCounters,
1708 auto &
PD = ProfileDataMap[NamePtr];
1709 if (
PD.RegionCounters)
1710 return PD.RegionCounters;
1714 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1715 PD.RegionCounters = CounterPtr;
1723 Metadata *FunctionNameAnnotation[] = {
1731 Metadata *NumCountersAnnotation[] = {
1740 auto *DICounter =
DB.createGlobalVariableExpression(
1741 SP, CounterPtr->getName(),
StringRef(), SP->getFile(),
1742 0,
DB.createUnspecifiedType(
"Profile Data Type"),
1743 CounterPtr->hasLocalLinkage(),
true,
nullptr,
1744 nullptr,
nullptr, 0,
1746 CounterPtr->addDebugInfo(DICounter);
1751 CompilerUsedVars.push_back(
PD.RegionCounters);
1755 createDataVariable(Inc);
1757 return PD.RegionCounters;
1767 auto &
PD = ProfileDataMap[NamePtr];
1784 if (
TT.isOSBinFormatXCOFF()) {
1793 std::string CntsVarName =
1795 std::string DataVarName =
1804 NS +=
PD.NumValueSites[Kind];
1805 if (NS > 0 && ValueProfileStaticAlloc &&
1811 ValuesVar->setVisibility(Visibility);
1813 ValuesVar->setSection(
1815 ValuesVar->setAlignment(
Align(8));
1816 maybeSetComdat(ValuesVar, Fn, CntsVarName);
1817 ValuesPtrExpr = ValuesVar;
1821 auto *CounterPtr =
PD.RegionCounters;
1826 auto *IntPtrTy =
M.getDataLayout().getIntPtrType(
M.getContext());
1829 Type *DataTypes[] = {
1830#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1837 Constant *Int16ArrayVals[IPVK_Last + 1];
1839 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty,
PD.NumValueSites[Kind]);
1852 if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1853 (
TT.isOSBinFormatELF() ||
1854 (!DataReferencedByCode &&
TT.isOSBinFormatCOFF()))) {
1859 new GlobalVariable(M, DataTy,
false, Linkage,
nullptr, DataVarName);
1862 Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
1867 DataSectionKind = IPSK_covdata;
1869 if (BitmapPtr !=
nullptr)
1874 DataSectionKind = IPSK_data;
1875 RelativeCounterPtr =
1878 if (BitmapPtr !=
nullptr)
1885#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1890 Data->setVisibility(Visibility);
1893 Data->setAlignment(
Align(INSTR_PROF_DATA_ALIGNMENT));
1894 maybeSetComdat(
Data, Fn, CntsVarName);
1899 CompilerUsedVars.push_back(
Data);
1905 ReferencedNames.push_back(NamePtr);
1908void InstrLowerer::emitVNodes() {
1909 if (!ValueProfileStaticAlloc)
1919 for (
auto &PD : ProfileDataMap) {
1921 TotalNS +=
PD.second.NumValueSites[Kind];
1927 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1935#define INSTR_PROF_MIN_VAL_COUNTS 10
1939 auto &Ctx =
M.getContext();
1940 Type *VNodeTypes[] = {
1941#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1951 VNodesVar->setSection(
1953 VNodesVar->setAlignment(
M.getDataLayout().getABITypeAlign(VNodesTy));
1956 UsedVars.push_back(VNodesVar);
1959void InstrLowerer::emitNameData() {
1960 std::string UncompressedData;
1962 if (ReferencedNames.empty())
1965 std::string CompressedNameStr;
1971 auto &Ctx =
M.getContext();
1977 NamesSize = CompressedNameStr.size();
1979 NamesVar->setSection(
1986 NamesVar->setAlignment(
Align(1));
1989 UsedVars.push_back(NamesVar);
1991 for (
auto *NamePtr : ReferencedNames)
1995void InstrLowerer::emitVTableNames() {
2000 std::string CompressedVTableNames;
2006 auto &Ctx =
M.getContext();
2008 Ctx,
StringRef(CompressedVTableNames),
false );
2017 UsedVars.push_back(VTableNamesVar);
2020void InstrLowerer::emitRegistration() {
2033 RegisterF->addFnAttr(Attribute::NoRedZone);
2036 auto *RuntimeRegisterF =
2042 if (!isa<Function>(
Data))
2043 IRB.CreateCall(RuntimeRegisterF,
Data);
2045 if (
Data != NamesVar && !isa<Function>(
Data))
2046 IRB.CreateCall(RuntimeRegisterF,
Data);
2049 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
2050 auto *NamesRegisterTy =
2052 auto *NamesRegisterF =
2055 IRB.CreateCall(NamesRegisterF, {NamesVar, IRB.getInt64(NamesSize)});
2058 IRB.CreateRetVoid();
2061bool InstrLowerer::emitRuntimeHook() {
2064 if (
TT.isOSLinux() ||
TT.isOSAIX())
2078 if (
TT.isOSBinFormatELF() && !
TT.isPS()) {
2080 CompilerUsedVars.push_back(Var);
2086 User->addFnAttr(Attribute::NoInline);
2088 User->addFnAttr(Attribute::NoRedZone);
2090 if (
TT.supportsCOMDAT())
2094 auto *
Load = IRB.CreateLoad(Int32Ty, Var);
2095 IRB.CreateRet(Load);
2098 CompilerUsedVars.push_back(
User);
2103void InstrLowerer::emitUses() {
2113 if (
TT.isOSBinFormatELF() ||
TT.isOSBinFormatMachO() ||
2114 (
TT.isOSBinFormatCOFF() && !DataReferencedByCode))
2125void InstrLowerer::emitInitialization() {
2142 F->addFnAttr(Attribute::NoInline);
2144 F->addFnAttr(Attribute::NoRedZone);
2148 IRB.CreateCall(RegisterF, {});
2149 IRB.CreateRetVoid();
2157 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SAMPLING_VAR));
2160 if (SampledInstrPeriod.getValue() <= USHRT_MAX) {
2170 SamplingVar->setThreadLocal(
true);
2171 Triple TT(M.getTargetTriple());
2172 if (TT.supportsCOMDAT()) {
2174 SamplingVar->setComdat(M.getOrInsertComdat(VarName));
This file contains the simple types necessary to represent the attributes associated with functions a...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static unsigned InstrCount
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool shouldRecordVTableAddr(GlobalVariable *GV)
static bool shouldRecordFunctionAddr(Function *F)
static bool needsRuntimeHookUnconditionally(const Triple &TT)
static bool containsProfilingIntrinsics(Module &M)
Check if the module contains uses of any profiling intrinsics.
static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix, bool &Renamed)
Get the name of a profiling variable for a particular function.
#define INSTR_PROF_MIN_VAL_COUNTS
static Constant * getFuncAddrForProfData(Function *Fn)
static bool shouldUsePublicSymbol(Function *Fn)
static FunctionCallee getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI, ValueProfilingCallType CallType=ValueProfilingCallType::Default)
static Constant * getVTableAddrForProfData(GlobalVariable *GV)
static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT)
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
Module.h This file contains the declarations for the Module class.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Annotations lets you mark points and ranges inside source code, for tests:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Instruction & front() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Function * getParent() const
Return the enclosing method, or null if none.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ NoDeduplicate
No deduplication is performed.
ConstantArray - Constant Array Declarations.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
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...
static Constant * getAllOnesValue(Type *Ty)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
bool isZeroValue() const
Return true if the value is negative zero or null value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Lightweight error class with error context and mandatory checking.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Argument * getArg(unsigned i) const
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...
bool hasMetadata() const
Return true if this value has any metadata attached to it.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
void setSection(StringRef S)
Change the section for this global.
bool hasLinkOnceLinkage() const
VisibilityTypes getVisibility() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
void setLinkage(LinkageTypes LT)
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
void setVisibility(VisibilityTypes V)
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
AtomicRMWInst * CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
ConstantInt * getInt16(uint16_t C)
Get a constant 16-bit value.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
A base class for all instrprof counter intrinsics.
ConstantInt * getIndex() const
ConstantInt * getNumCounters() const
static const char * FunctionNameAttributeName
static const char * CFGHashAttributeName
static const char * NumCountersAttributeName
This represents the llvm.instrprof.cover intrinsic.
This represents the llvm.instrprof.increment intrinsic.
A base class for all instrprof intrinsics.
GlobalVariable * getName() const
ConstantInt * getHash() const
A base class for instrprof mcdc intrinsics that require global bitmap bytes.
auto getNumBitmapBytes() const
This represents the llvm.instrprof.mcdc.tvbitmap.update intrinsic.
Value * getMCDCCondBitmapAddr() const
ConstantInt * getBitmapIndex() const
This represents the llvm.instrprof.timestamp intrinsic.
This represents the llvm.instrprof.value.profile intrinsic.
ConstantInt * getIndex() const
Value * getTargetValue() const
ConstantInt * getValueKind() const
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
A Module instance is used to store all the information related to an LLVM module.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Helper class for SSA formation on a set of values defined in multiple blocks.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr size_t size() const
size - Get the string size.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
This is an optimization pass for GlobalISel generic memory operations.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
void createProfileSamplingVar(Module &M)
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
cl::opt< bool > DoInstrProfNameCompression
cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate("profile-correlate", cl::desc("Use debug info or binary file to correlate profiles."), cl::init(InstrProfCorrelator::NONE), cl::values(clEnumValN(InstrProfCorrelator::NONE, "", "No profile correlation"), clEnumValN(InstrProfCorrelator::DEBUG_INFO, "debug-info", "Use debug info to correlate"), clEnumValN(InstrProfCorrelator::BINARY, "binary", "Use binary to correlate")))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
StringRef getInstrProfVTableNamesVarName()
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
cl::opt< bool > DebugInfoCorrelate
bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
StringRef getInstrProfCounterBiasVarName()
auto reverse(ContainerTy &&C)
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
auto predecessors(const MachineBasicBlock *BB)
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Options for the frontend instrumentation based profiling pass.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.