71#define DEBUG_TYPE "instrprof"
81 return LibraryOptions.
get<InstrumentationOptions>()
82 .profile_correlate.has_value();
87struct SampledInstrumentationConfig {
88 unsigned BurstDuration;
91 bool IsSimpleSampling;
95static SampledInstrumentationConfig
96getSampledInstrumentationConfig(
const InstrumentationOptions &Opts) {
97 SampledInstrumentationConfig config;
98 config.BurstDuration = Opts.sampled_instr_burst_duration;
99 config.Period = Opts.sampled_instr_period;
100 if (config.BurstDuration > config.Period)
102 "SampledBurstDuration must be less than or equal to SampledPeriod");
103 if (config.Period == 0 || config.BurstDuration == 0)
105 "SampledPeriod and SampledBurstDuration must be greater than 0");
106 config.IsSimpleSampling = (config.BurstDuration == 1);
109 config.IsFastSampling =
110 (!config.IsSimpleSampling && config.Period == USHRT_MAX + 1);
111 config.UseShort = (config.Period <= USHRT_MAX) || config.IsFastSampling;
115using LoadStorePair = std::pair<Instruction *, Instruction *>;
119 assert(Addition && Addition->getOpcode() == Instruction::BinaryOps::Add);
120 auto *Addend = Addition->getOperand(1);
126 ->setNoSanitizeMetadata();
127 Store->eraseFromParent();
128 Addition->eraseFromParent();
129 Load->eraseFromParent();
142static bool enablesValueProfiling(
const Module &M) {
144 getIntModuleFlagOrZero(M,
"EnableValueProfiling") != 0;
148static bool profDataReferencedByCode(
const Module &M) {
149 return enablesValueProfiling(M);
152class InstrLowerer final {
154 InstrLowerer(
const InstrumentationOptions &Opts,
Module &M,
155 const InstrProfOptions &Options,
156 std::function<
const TargetLibraryInfo &(
Function &
F)> GetTLI,
158 : Opts(Opts), M(M), Options(Options), TT(M.getTargetTriple()), IsCS(IsCS),
159 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
164 const InstrumentationOptions &Opts;
166 const InstrProfOptions Options;
171 std::function<
const TargetLibraryInfo &(
Function &
F)> GetTLI;
173 const bool DataReferencedByCode;
175 struct PerFunctionProfileData {
176 uint32_t NumValueSites[IPVK_Last + 1] = {};
177 GlobalVariable *RegionCounters =
nullptr;
178 GlobalVariable *UniformCounters =
180 GlobalVariable *DataVar =
nullptr;
181 GlobalVariable *RegionBitmaps =
nullptr;
182 uint32_t NumBitmapBytes = 0;
184 PerFunctionProfileData() =
default;
186 DenseMap<GlobalVariable *, PerFunctionProfileData> ProfileDataMap;
189 DenseMap<GlobalVariable *, GlobalVariable *> VTableDataMap;
192 DenseMap<const Function *, LoadInst *> FunctionToProfileBiasMap;
193 std::vector<GlobalValue *> CompilerUsedVars;
194 std::vector<GlobalValue *> UsedVars;
195 std::vector<GlobalVariable *> ReferencedNames;
198 std::vector<GlobalVariable *> ReferencedVTables;
199 GlobalVariable *NamesVar =
nullptr;
200 size_t NamesSize = 0;
202 StructType *ProfileDataTy =
nullptr;
205 std::vector<LoadStorePair> PromotionCandidates;
207 int64_t TotalCountersPromoted = 0;
212 struct GPUPGOInvariants {
213 Value *Matched =
nullptr;
214 bool WaveSizeStored =
false;
216 DenseMap<Function *, GPUPGOInvariants> GPUInvariantsCache;
219 GPUPGOInvariants &getOrCreateGPUInvariants(
Function *
F);
226 void promoteCounterLoadStores(
Function *
F);
229 bool isRuntimeCounterRelocationEnabled()
const;
232 bool isCounterPromotionEnabled()
const;
238 bool isSamplingEnabled()
const;
241 void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
244 void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
247 void lowerCover(InstrProfCoverInst *Inc);
251 void lowerTimestamp(InstrProfTimestampInst *TimestampInstruction);
254 void lowerIncrement(InstrProfIncrementInst *Inc);
257 void lowerCoverageData(GlobalVariable *CoverageNamesVar);
261 void lowerMCDCTestVectorBitmapUpdate(InstrProfMCDCTVBitmapUpdate *Ins);
265 GlobalVariable *getOrCreateBiasVar(StringRef VarName);
269 Value *getCounterAddress(InstrProfCntrInstBase *
I);
272 void doSampling(Instruction *
I);
278 GlobalVariable *getOrCreateRegionCounters(InstrProfCntrInstBase *Inc);
282 GlobalVariable *getOrCreateUniformCounters(InstrProfCntrInstBase *Inc);
285 GlobalVariable *createRegionCounters(InstrProfCntrInstBase *Inc,
291 Value *getBitmapAddress(InstrProfMCDCTVBitmapUpdate *
I);
297 GlobalVariable *getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc);
304 GlobalVariable *createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
309 void maybeSetComdat(GlobalVariable *GV, GlobalObject *GO, StringRef VarName);
312 GlobalVariable *setupProfileSection(InstrProfInstBase *Inc,
316 void createDataVariable(InstrProfCntrInstBase *Inc);
319 void getOrCreateVTableProfData(GlobalVariable *GV);
325 void emitVTableNames();
331 void emitRegistration();
335 bool emitRuntimeHook();
342 void emitInitialization();
345 StructType *getProfileDataTy();
357 PGOCounterPromoterHelper(
358 const InstrumentationOptions &Opts, Instruction *L, Instruction *S,
359 SSAUpdater &
SSA,
Value *Init, BasicBlock *PH,
362 LoopInfo &LI,
bool IsAtomic)
363 : LoadAndStorePromoter({
L, S},
SSA), Opts(Opts),
Store(S),
364 ExitBlocks(ExitBlocks), InsertPts(InsertPts),
365 LoopToCandidates(LoopToCands), LI(LI), IsAtomic(IsAtomic) {
368 SSA.AddAvailableValue(PH, Init);
371 void doExtraRewritesBeforeFinalDeletion()
override {
372 for (
unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
378 Value *LiveInValue =
SSA.GetValueInMiddleOfBlock(ExitBlock);
390 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
391 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
392 Addr = Builder.CreateIntToPtr(BiasInst,
396 Opts.iterative_counter_promotion ? LI.getLoopFor(ExitBlock) :
nullptr;
399 if ((IsAtomic && !TargetLoop) || Opts.atomic_counter_update_promoted)
402 MaybeAlign(), AtomicOrdering::Monotonic)
403 ->setNoSanitizeMetadata();
405 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr,
"pgocount.promoted");
407 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
408 auto *NewStore = Builder.CreateStore(NewVal, Addr);
409 NewStore->setNoSanitizeMetadata();
413 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
419 const InstrumentationOptions &Opts;
422 ArrayRef<Instruction *> InsertPts;
423 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
431class PGOCounterPromoter {
434 const InstrumentationOptions &Opts,
436 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI,
bool IsAtomic)
437 : Opts(Opts), LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI),
442 SmallVector<BasicBlock *, 8> LoopExitBlocks;
443 SmallPtrSet<BasicBlock *, 8>
BlockSet;
445 L.getExitBlocks(LoopExitBlocks);
446 if (!isPromotionPossible(&L, LoopExitBlocks))
449 for (BasicBlock *ExitBlock : LoopExitBlocks) {
454 ExitBlocks.push_back(ExitBlock);
460 bool run(int64_t *NumPromoted) {
464 auto &OrigCandidates = LoopToCandidates[&L];
466 OrigCandidates.clear();
467 bool RC = promoteCandidates(Candidates, NumPromoted);
469 "Did not expect new candidates to be added to current loop");
480 for (
auto &Cand : Candidates)
481 if (Cand.first !=
nullptr && Cand.second !=
nullptr)
482 makeAtomic(Cand.first, Cand.second);
487 bool promoteCandidates(SmallVectorImpl<LoadStorePair> &Candidates,
488 int64_t *NumPromoted) {
490 if (ExitBlocks.size() == 0)
498 if (Opts.skip_ret_exit_block) {
499 for (
auto *BB : ExitBlocks)
504 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
508 unsigned Promoted = 0;
509 for (
auto &Cand : Candidates) {
511 SSAUpdater
SSA(&NewPHIs);
512 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
516 auto *BB = Cand.first->getParent();
517 auto InstrCount = BFI->getBlockProfileCount(BB);
520 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
523 if (PreheaderCount && (*PreheaderCount * 3) >= (*
InstrCount * 2))
527 PGOCounterPromoterHelper Promoter(
528 Opts, Cand.first, Cand.second,
SSA, InitVal, L.getLoopPreheader(),
529 ExitBlocks, InsertPts, LoopToCandidates, LI, IsAtomic);
530 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
532 Cand = {
nullptr,
nullptr};
535 if (Promoted >= MaxProm)
539 if (Opts.max_counter_promotions != -1 &&
540 *NumPromoted >= Opts.max_counter_promotions)
544 LLVM_DEBUG(
dbgs() << Promoted <<
" counters promoted for loop (depth="
545 << L.getLoopDepth() <<
")\n");
546 return Promoted != 0;
550 bool allowSpeculativeCounterPromotion(
Loop *LP) {
551 SmallVector<BasicBlock *, 8> ExitingBlocks;
552 L.getExitingBlocks(ExitingBlocks);
554 if (ExitingBlocks.
size() == 1)
556 if (ExitingBlocks.
size() > Opts.speculative_counter_promotion_max_exiting)
564 isPromotionPossible(
Loop *LP,
565 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
583 unsigned getMaxNumOfPromotionsInLoop(
Loop *LP) {
584 SmallVector<BasicBlock *, 8> LoopExitBlocks;
586 if (!isPromotionPossible(LP, LoopExitBlocks))
589 SmallVector<BasicBlock *, 8> ExitingBlocks;
597 if (ExitingBlocks.
size() == 1)
598 return Opts.max_counter_promotions_per_loop;
600 if (ExitingBlocks.
size() > Opts.speculative_counter_promotion_max_exiting)
604 if (Opts.speculative_counter_promotion_to_loop)
605 return Opts.max_counter_promotions_per_loop;
608 unsigned MaxProm = Opts.max_counter_promotions_per_loop;
609 for (
auto *TargetBlock : LoopExitBlocks) {
610 auto *TargetLoop = LI.getLoopFor(TargetBlock);
613 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
614 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
616 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
617 PendingCandsInTarget);
622 const InstrumentationOptions &Opts;
623 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
624 SmallVector<BasicBlock *, 8> ExitBlocks;
625 SmallVector<Instruction *, 8> InsertPts;
628 BlockFrequencyInfo *BFI;
632enum class ValueProfilingCallType {
651 InstrLowerer Lowerer(Opts, M, Options, GetTLI, IsCS);
652 if (!Lowerer.lower())
703 if (!isSamplingEnabled())
706 SampledInstrumentationConfig config = getSampledInstrumentationConfig(Opts);
709 return Builder.getInt16(
C);
711 return Builder.getInt32(
C);
721 assert(SamplingVar &&
"SamplingVar not set properly");
725 Value *NewSamplingVarVal;
729 auto *LoadSamplingVar = CondBuilder.CreateLoad(SamplingVarTy, SamplingVar);
730 if (config.IsSimpleSampling) {
734 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
735 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
738 auto *DurationCond = CondBuilder.CreateICmpULE(
739 LoadSamplingVar, GetConstant(CondBuilder, config.BurstDuration - 1));
740 BranchWeight = MDB.createBranchWeights(
741 config.BurstDuration, config.Period - config.BurstDuration);
743 DurationCond,
I,
false, BranchWeight);
746 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
747 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
751 if (config.IsFastSampling)
757 auto *PeriodCond = PeriodCondBuilder.CreateICmpUGE(
758 NewSamplingVarVal, GetConstant(PeriodCondBuilder, config.Period));
759 BranchWeight = MDB.createBranchWeights(1, config.Period - 1);
761 &ElseTerm, BranchWeight);
764 if (config.IsSimpleSampling)
768 ResetBuilder.CreateStore(GetConstant(ResetBuilder, 0), SamplingVar);
772bool InstrLowerer::lowerIntrinsics(
Function *
F) {
773 bool MadeChange =
false;
774 PromotionCandidates.clear();
787 for (
auto *Instr : InstrProfInsts) {
790 lowerIncrement(IPIS);
802 lowerValueProfileInst(IPVP);
805 IPMP->eraseFromParent();
808 lowerMCDCTestVectorBitmapUpdate(IPBU);
816 promoteCounterLoadStores(
F);
820bool InstrLowerer::isRuntimeCounterRelocationEnabled()
const {
822 if (
TT.isOSBinFormatMachO())
826 return valueOr(Opts.runtime_counter_relocation,
TT.isOSFuchsia());
829bool InstrLowerer::isSamplingEnabled()
const {
833bool InstrLowerer::isCounterPromotionEnabled()
const {
834 return valueOr(Opts.do_counter_promotion,
Options.DoCounterPromotion);
837bool InstrLowerer::isAtomic(
const Function &
F)
const {
840 return valueOr(Opts.instrprof_atomic_counter_update_all,
841 Options.Atomic ||
F.hasFnAttribute(Attribute::SanitizeThread));
846 const Value *Addr =
nullptr;
848 Addr = LI->getOperand(0);
850 Addr = LI->getOperand(1);
860void InstrLowerer::promoteCounterLoadStores(
Function *
F) {
861 if (!isCounterPromotionEnabled())
870 std::unique_ptr<BlockFrequencyInfo> BFI;
871 if (
Options.UseBFIInPromotion) {
872 std::unique_ptr<BranchProbabilityInfo> BPI;
877 for (
const auto &LoadStore : PromotionCandidates) {
884 makeAtomic(CounterLoad, CounterStore);
887 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
895 PGOCounterPromoter Promoter(Opts, LoopPromotionCandidates, *
Loop, LI,
897 Promoter.run(&TotalCountersPromoted);
900 if (
isAtomic(*
F) && Opts.verify_atomic_counter_promoted)
906 if (TT.isOSFuchsia())
914 auto containsIntrinsic = [&](
int ID) {
916 return !
F->use_empty();
919 return containsIntrinsic(Intrinsic::instrprof_cover) ||
920 containsIntrinsic(Intrinsic::instrprof_increment) ||
921 containsIntrinsic(Intrinsic::instrprof_increment_step) ||
922 containsIntrinsic(Intrinsic::instrprof_timestamp) ||
923 containsIntrinsic(Intrinsic::instrprof_value_profile);
926bool InstrLowerer::lower() {
927 bool MadeChange =
false;
929 if (NeedsRuntimeHook)
930 MadeChange = emitRuntimeHook();
932 if (!IsCS && isSamplingEnabled())
939 if (!ContainsProfiling && !CoverageNamesVar)
950 computeNumValueSiteCounts(Ind);
952 if (FirstProfInst ==
nullptr &&
957 static_cast<void>(getOrCreateRegionBitmaps(Params));
964 if (FirstProfInst !=
nullptr) {
965 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
972 if (GV.hasMetadata(LLVMContext::MD_type))
973 getOrCreateVTableProfData(&GV);
976 MadeChange |= lowerIntrinsics(&
F);
978 if (CoverageNamesVar) {
979 lowerCoverageData(CoverageNamesVar);
994 if (!NeedsRuntimeHook && ContainsProfiling)
999 emitInitialization();
1005 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
1010 if (
auto AK =
TLI.getExtAttrForI32Param(
false))
1011 AL = AL.addParamAttribute(M.getContext(), 2, AK);
1013 assert((CallType == ValueProfilingCallType::Default ||
1014 CallType == ValueProfilingCallType::MemOp) &&
1015 "Must be Default or MemOp");
1016 Type *ParamTypes[] = {
1017#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
1020 auto *ValueProfilingCallTy =
1022 StringRef FuncName = CallType == ValueProfilingCallType::Default
1025 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
1032 auto &
PD = ProfileDataMap[
Name];
1034 std::max(
PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
1042 !Opts.profile_correlate &&
1043 "Value profiling is not yet supported with lightweight instrumentation");
1045 auto It = ProfileDataMap.find(Name);
1046 assert(It != ProfileDataMap.end() && It->second.DataVar &&
1047 "value profiling detected in function with no counter increment");
1053 Index += It->second.NumValueSites[Kind];
1056 bool IsMemOpSize = (Ind->
getValueKind()->getZExtValue() ==
1057 llvm::InstrProfValueKind::IPVK_MemOPSize);
1081 if (
auto AK =
TLI->getExtAttrForI32Param(
false))
1104 if (
TT.supportsCOMDAT())
1105 Bias->
setComdat(
M.getOrInsertComdat(VarName));
1111 auto *
Counters = getOrCreateRegionCounters(
I);
1120 if (!isRuntimeCounterRelocationEnabled())
1125 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
1129 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias,
"profc_bias");
1131 BiasLI->
setMetadata(LLVMContext::MD_invariant_load,
1139 auto *Bitmaps = getOrCreateRegionBitmaps(
I);
1140 if (!isRuntimeCounterRelocationEnabled())
1148 auto *BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias,
"profbm_bias");
1150 BiasLI->
setMetadata(LLVMContext::MD_invariant_load,
1159 auto *Addr = getCounterAddress(CoverInstruction);
1167 if (Opts.conditional_counter_update) {
1169 auto &Ctx = CoverInstruction->
getParent()->getContext();
1172 Load->setNoSanitizeMetadata();
1183 Store->setNoSanitizeMetadata();
1189void InstrLowerer::lowerTimestamp(
1192 "timestamp probes are always the first probe for a function");
1193 auto &Ctx =
M.getContext();
1194 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1198 auto Callee =
M.getOrInsertFunction(
1204InstrLowerer::GPUPGOInvariants &
1205InstrLowerer::getOrCreateGPUInvariants(
Function *
F) {
1206 auto It = GPUInvariantsCache.find(
F);
1207 if (It != GPUInvariantsCache.end())
1217 if (Opts.offload_pgo_sampling > 0) {
1220 RTLIB::impl___llvm_profile_sampling_gpu),
1223 IsSampledFn, {ConstantInt::get(Int32Ty, Opts.offload_pgo_sampling)},
1225 Matched = Builder.
CreateICmpNE(SampledInt, ConstantInt::get(Int32Ty, 0),
1229 auto &Inv = GPUInvariantsCache[
F];
1230 Inv.Matched = Matched;
1238 auto &Inv = getOrCreateGPUInvariants(
F);
1244 auto *Addr = getCounterAddress(Inc);
1249 if (!Inv.WaveSizeStored) {
1250 Inv.WaveSizeStored =
true;
1252 auto &
PD = ProfileDataMap[NamePtr];
1254 IRBuilder<> EntryBuilder(&*
F->getEntryBlock().getFirstInsertionPt());
1255 Value *WaveSize16 =
nullptr;
1259 if (
TT.isAMDGPU()) {
1265 Value *WaveSize = EntryBuilder.CreateCall(WaveSizeFn);
1266 WaveSize16 = EntryBuilder.CreateTrunc(
1272 Value *WaveSizeAddr = EntryBuilder.CreateStructGEP(
1273 PD.DataVar->getValueType(),
PD.DataVar, 9,
"profd.wavesize");
1274 EntryBuilder.CreateStore(WaveSize16, WaveSizeAddr);
1278 GlobalVariable *UniformCounters = getOrCreateUniformCounters(Inc);
1280 if (UniformCounters) {
1283 UniformCounters->
getValueType(), UniformCounters, UniformIndices,
1293 {PtrTy, PtrTy, Int64Ty},
false);
1296 RTLIB::impl___llvm_profile_instrument_gpu),
1299 if (Opts.offload_pgo_sampling > 0) {
1307 HeadBuilder.CreateCondBr(Inv.Matched, ThenBB, ContBB);
1310 ThenBuilder.CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1311 ThenBuilder.CreateBr(ContBB);
1313 Builder.
CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1319 auto *Addr = getCounterAddress(Inc);
1331 Load->setNoSanitizeMetadata();
1334 Store->setNoSanitizeMetadata();
1335 if (isCounterPromotionEnabled())
1341void InstrLowerer::lowerCoverageData(
GlobalVariable *CoverageNamesVar) {
1351 ReferencedNames.push_back(Name);
1353 NC->dropAllReferences();
1358void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1360 auto &Ctx =
M.getContext();
1365 auto *BitmapAddr = getBitmapAddress(Update);
1370 Builder.
CreateLoad(Int32Ty, MCDCCondBitmapAddr,
"mcdc.temp"),
1375 auto *BitmapByteOffset = Builder.
CreateLShr(Temp, 0x3);
1393 auto *Bitmap = Builder.
CreateLoad(Int8Ty, BitmapByteAddr,
"mcdc.bits");
1441 return (Prefix + Name).str();
1447 return (Prefix + Name).str();
1456 if (!profDataReferencedByCode(*
F->getParent()))
1460 bool HasAvailableExternallyLinkage =
F->hasAvailableExternallyLinkage();
1461 if (!
F->hasLinkOnceLinkage() && !
F->hasLocalLinkage() &&
1462 !HasAvailableExternallyLinkage)
1468 if (HasAvailableExternallyLinkage &&
1469 F->hasFnAttribute(Attribute::AlwaysInline))
1475 if (
F->hasLocalLinkage() &&
F->hasComdat())
1485 return F->hasAddressTaken() ||
F->hasLinkOnceLinkage();
1538 Fn->
getName() +
".local", Fn);
1567 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1568 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF() ||
1569 TT.isOSBinFormatWasm())
1582 bool UseComdat = (NeedComdat ||
TT.isOSBinFormatELF());
1597 StringRef GroupName =
TT.isOSBinFormatCOFF() && DataReferencedByCode
1600 Comdat *
C =
M.getOrInsertComdat(GroupName);
1620 if (!profDataReferencedByCode(*GV->
getParent()))
1645void InstrLowerer::getOrCreateVTableProfData(
GlobalVariable *GV) {
1647 "Value profiling is not supported with lightweight instrumentation");
1658 auto It = VTableDataMap.find(GV);
1659 if (It != VTableDataMap.end() && It->second)
1667 if (
TT.isOSBinFormatXCOFF()) {
1673 Type *DataTypes[] = {
1674#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1676#undef INSTR_PROF_VTABLE_DATA
1689#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1691#undef INSTR_PROF_VTABLE_DATA
1699 Data->setVisibility(Visibility);
1703 maybeSetComdat(
Data, GV,
Data->getName());
1705 VTableDataMap[GV] =
Data;
1707 ReferencedVTables.push_back(GV);
1711 UsedVars.push_back(
Data);
1734 if (
TT.isOSBinFormatXCOFF()) {
1743 if (IPSK == IPSK_cnts) {
1747 Ptr = createRegionCounters(CntrIncrement, VarName,
Linkage);
1748 }
else if (IPSK == IPSK_bitmap) {
1753 Ptr = createRegionBitmaps(BitmapUpdate, VarName,
Linkage);
1762 Ptr->
setComdat(
M.getOrInsertComdat(VarName));
1766 maybeSetComdat(Ptr, Fn, VarName);
1790 auto CUs =
F.getParent()->debug_compile_units();
1791 return CUs.empty() ? nullptr : *CUs.begin();
1797 auto &
PD = ProfileDataMap[NamePtr];
1798 if (
PD.RegionBitmaps)
1799 return PD.RegionBitmaps;
1803 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1804 PD.RegionBitmaps = BitmapPtr;
1807 if (
PD.NumBitmapBytes &&
1814 Metadata *FunctionNameAnnotation[] = {
1818 Metadata *NumBitmapBitsAnnotation[] = {
1826 auto *DICounter =
DB.createGlobalVariableExpression(
1827 Scope, BitmapPtr->getName(),
StringRef(),
1829 0,
DB.createUnspecifiedType(
"Profile Bitmap Type"),
1830 BitmapPtr->hasLocalLinkage(),
true,
nullptr,
1831 nullptr,
nullptr, 0,
1833 BitmapPtr->addDebugInfo(DICounter);
1835 DB.finalizeSubprogram(SP);
1840 CompilerUsedVars.push_back(
PD.RegionBitmaps);
1843 return PD.RegionBitmaps;
1850 auto &Ctx =
M.getContext();
1856 std::vector<Constant *> InitialValues(NumCounters,
1874 auto &
PD = ProfileDataMap[NamePtr];
1875 if (
PD.RegionCounters)
1876 return PD.RegionCounters;
1880 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1881 PD.RegionCounters = CounterPtr;
1889 Metadata *FunctionNameAnnotation[] = {
1897 Metadata *NumCountersAnnotation[] = {
1906 auto *DICounter =
DB.createGlobalVariableExpression(
1907 Scope, CounterPtr->getName(),
StringRef(),
1909 0,
DB.createUnspecifiedType(
"Profile Data Type"),
1910 CounterPtr->hasLocalLinkage(),
true,
nullptr,
1911 nullptr,
nullptr, 0,
1913 CounterPtr->addDebugInfo(DICounter);
1915 DB.finalizeSubprogram(SP);
1920 CompilerUsedVars.push_back(
PD.RegionCounters);
1925 getOrCreateUniformCounters(Inc);
1928 createDataVariable(Inc);
1930 return PD.RegionCounters;
1940 auto &
PD = ProfileDataMap[NamePtr];
1941 if (
PD.UniformCounters)
1942 return PD.UniformCounters;
1944 assert(
PD.RegionCounters &&
"region counters must be created first");
1964 PD.UniformCounters = GV;
1965 CompilerUsedVars.push_back(GV);
1967 return PD.UniformCounters;
1977 auto &
PD = ProfileDataMap[NamePtr];
1994 if (
TT.isOSBinFormatXCOFF()) {
2003 std::string CntsVarName =
2005 std::string DataVarName =
2013 for (uint32_t Kind = IPVK_First;
Kind <= IPVK_Last; ++
Kind)
2014 NS +=
PD.NumValueSites[Kind];
2015 if (NS > 0 && Opts.vp_static_alloc &&
2021 ValuesVar->setVisibility(Visibility);
2023 ValuesVar->setSection(
2025 ValuesVar->setAlignment(
Align(8));
2026 maybeSetComdat(ValuesVar, Fn, CntsVarName);
2039 auto *
IntPtrTy =
M.getDataLayout().getIntPtrType(
M.getContext());
2042 auto *DataTy = getProfileDataTy();
2046 Constant *Int16ArrayVals[IPVK_Last + 1];
2047 for (uint32_t Kind = IPVK_First;
Kind <= IPVK_Last; ++
Kind)
2048 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty,
PD.NumValueSites[Kind]);
2050 uint16_t OffloadDeviceWaveSizeVal = 0;
2073 !(DataReferencedByCode && NeedComdat && !Renamed) &&
2074 (
TT.isOSBinFormatELF() ||
2075 (!DataReferencedByCode &&
TT.isOSBinFormatCOFF()))) {
2082 if (
TT.isGPU() &&
TT.isOSBinFormatELF() &&
2096 DataSectionKind = IPSK_covdata;
2098 if (BitmapPtr !=
nullptr)
2101 RelativeUniformCounterPtr =
2103 }
else if (
TT.isNVPTX()) {
2107 DataSectionKind = IPSK_data;
2112 DataSectionKind = IPSK_data;
2113 RelativeCounterPtr =
2116 if (BitmapPtr !=
nullptr)
2127#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
2132 Data->setVisibility(Visibility);
2137 Data->setComdat(
M.getOrInsertComdat(CntsVarName));
2140 maybeSetComdat(
Data, Fn, CntsVarName);
2146 CompilerUsedVars.push_back(
Data);
2152 ReferencedNames.push_back(NamePtr);
2155void InstrLowerer::emitVNodes() {
2156 if (!Opts.vp_static_alloc)
2166 for (
auto &PD : ProfileDataMap) {
2167 for (uint32_t Kind = IPVK_First;
Kind <= IPVK_Last; ++
Kind)
2168 TotalNS +=
PD.second.NumValueSites[Kind];
2174 uint64_t NumCounters = TotalNS * Opts.vp_counters_per_site;
2182#define INSTR_PROF_MIN_VAL_COUNTS 10
2186 auto &Ctx =
M.getContext();
2187 Type *VNodeTypes[] = {
2188#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
2198 VNodesVar->setSection(
2200 VNodesVar->setAlignment(
M.getDataLayout().getABITypeAlign(VNodesTy));
2203 UsedVars.push_back(VNodesVar);
2211 std::string Name = (
"__llvm_profile_sections" + CUIDPostfix).str();
2212 if (M.getNamedValue(Name))
2216 unsigned AS = M.getDataLayout().getDefaultGlobalsAddressSpace();
2222 nullptr, Sym,
nullptr,
2231 Constant *Fields[] = {
Extern(
"__start___llvm_prf_names", I8,
false, Hidden),
2232 Extern(
"__stop___llvm_prf_names", I8,
false, Hidden),
2233 Extern(
"__start___llvm_prf_cnts", I8,
false, Hidden),
2234 Extern(
"__stop___llvm_prf_cnts", I8,
false, Hidden),
2235 Extern(
"__start___llvm_prf_data", I8,
false, Hidden),
2236 Extern(
"__stop___llvm_prf_data", I8,
false, Hidden),
2237 Extern(
"__start___llvm_prf_ucnts", I8,
false, Hidden),
2238 Extern(
"__stop___llvm_prf_ucnts", I8,
false, Hidden),
2239 Extern(
"__llvm_profile_raw_version",
2244 Ctx, {PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy});
2253void InstrLowerer::emitNameData() {
2254 if (ReferencedNames.empty())
2257 std::string CompressedNameStr;
2263 auto &Ctx =
M.getContext();
2269 std::string GPUCUIDPostfix;
2274 if (
Init->isCString()) {
2275 GPUCUIDPostfix =
Init->getAsCString().str();
2276 NamesVarName += GPUCUIDPostfix;
2280 M, [GV](
Constant *
C) {
return C->stripPointerCasts() == GV; });
2286 NamesVar =
new GlobalVariable(M, NamesVal->getType(),
true, NamesLinkage,
2287 NamesVal, NamesVarName);
2288 NamesVar->setVisibility(NamesVisibility);
2290 NamesSize = CompressedNameStr.size();
2292 std::string NamesSectionName =
2296 NamesVar->setSection(NamesSectionName);
2300 NamesVar->setAlignment(
Align(1));
2303 UsedVars.push_back(NamesVar);
2305 for (
auto *NamePtr : ReferencedNames)
2311 [](
const auto &KV) { return KV.second.DataVar; });
2312 if (!GPUCUIDPostfix.empty() && HasData)
2314 CompilerUsedVars.push_back(GV);
2317void InstrLowerer::emitVTableNames() {
2322 std::string CompressedVTableNames;
2328 auto &Ctx =
M.getContext();
2330 Ctx,
StringRef(CompressedVTableNames),
false );
2339 UsedVars.push_back(VTableNamesVar);
2342void InstrLowerer::emitRegistration() {
2355 RegisterF->addFnAttr(Attribute::NoRedZone);
2358 auto *RuntimeRegisterF =
2366 IRB.CreateCall(RuntimeRegisterF,
2367 IRB.CreatePointerBitCastOrAddrSpaceCast(
Data, VoidPtrTy));
2370 IRB.CreateCall(RuntimeRegisterF,
2371 IRB.CreatePointerBitCastOrAddrSpaceCast(
Data, VoidPtrTy));
2374 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
2375 auto *NamesRegisterTy =
2377 auto *NamesRegisterF =
2380 IRB.CreateCall(NamesRegisterF, {IRB.CreatePointerBitCastOrAddrSpaceCast(
2381 NamesVar, VoidPtrTy),
2382 IRB.getInt64(NamesSize)});
2385 IRB.CreateRetVoid();
2388bool InstrLowerer::emitRuntimeHook() {
2396 if (
TT.isOSLinux() ||
TT.isOSAIX())
2410 if (
TT.isOSBinFormatELF() && !
TT.isPS()) {
2412 CompilerUsedVars.push_back(Var);
2418 User->addFnAttr(Attribute::NoInline);
2420 User->addFnAttr(Attribute::NoRedZone);
2422 if (
TT.supportsCOMDAT())
2425 User->setEntryCount(0);
2428 auto *
Load = IRB.CreateLoad(Int32Ty, Var);
2429 IRB.CreateRet(
Load);
2432 CompilerUsedVars.push_back(
User);
2437void InstrLowerer::emitUses() {
2447 if (
TT.isOSBinFormatELF() ||
TT.isOSBinFormatMachO() ||
2448 (
TT.isOSBinFormatCOFF() && !DataReferencedByCode))
2459void InstrLowerer::emitInitialization() {
2476 F->addFnAttr(Attribute::NoInline);
2478 F->addFnAttr(Attribute::NoRedZone);
2482 IRB.CreateCall(RegisterF, {});
2483 IRB.CreateRetVoid();
2495 if (getSampledInstrumentationConfig(Opts).UseShort) {
2505 SamplingVar->setThreadLocal(
true);
2506 Triple TT(M.getTargetTriple());
2507 if (TT.supportsCOMDAT()) {
2509 SamplingVar->setComdat(M.getOrInsertComdat(VarName));
2518StructType *InstrLowerer::getProfileDataTy() {
2520 return ProfileDataTy;
2522 auto &Ctx =
M.getContext();
2523 auto *
IntPtrTy =
M.getDataLayout().getIntPtrType(
M.getContext());
2526 Type *DataTypes[] = {
2527#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
2531 return ProfileDataTy;
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
static unsigned InstrCount
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define INSTR_PROF_QUOTE(x)
#define INSTR_PROF_DATA_ALIGNMENT
#define INSTR_PROF_PROFILE_SET_TIMESTAMP
#define INSTR_PROF_PROFILE_SAMPLING_VAR
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 DIScope * getCorrelationScope(const Function &F)
Return the scope in which to describe F's profile variables for debug info correlation,...
#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 void doAtomicCheck(Function *F)
static GlobalVariable * emitGPUOffloadSectionsStruct(Module &M, StringRef CUIDPostfix)
static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT)
static std::string getVarName(const InstrumentationOptions &Opts, InstrProfInstBase *Inc, StringRef Prefix, bool &Renamed)
Get the name of a profiling variable for a particular function.
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
static bool isAtomic(MachineBasicBlock::iterator I)
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file defines the SmallVector class.
Class for arbitrary precision integers.
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:
Class to represent array types.
static LLVM_ABI 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.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction & front() const
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
@ NoDeduplicate
No deduplication is performed.
ConstantArray - Constant Array Declarations.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI 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...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
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 LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
const Function & getFunction() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static GEPNoWrapFlags inBounds()
void compute(FunctionT &F)
Compute the cycle info for a function.
static LLVM_ABI 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 GlobalObject has any metadata attached to it.
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
bool hasLinkOnceLinkage() const
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI 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.
@ ProtectedVisibility
The GV is protected.
void setVisibility(VisibilityTypes V)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
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.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreatePtrAddWithZExtOrTrunc(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd where the offset is zero-extended or truncated to the index type.
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.
BasicBlock * GetInsertBlock() const
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreatePtrAddWithSExtOrTrunc(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd where the offset is sign-extended or truncated to the index type.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
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="")
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.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
AtomicRMWInst * CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, bool Elementwise=false)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
A base class for all instrprof counter intrinsics.
LLVM_ABI ConstantInt * getIndex() const
LLVM_ABI ConstantInt * getNumCounters() const
static LLVM_ABI const char * FunctionNameAttributeName
static LLVM_ABI const char * CFGHashAttributeName
static LLVM_ABI const char * NumCountersAttributeName
static LLVM_ABI const char * NumBitmapBitsAttributeName
This represents the llvm.instrprof.cover intrinsic.
This represents the llvm.instrprof.increment intrinsic.
LLVM_ABI Value * getStep() const
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.
ConstantInt * getNumBitmapBits() const
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
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void setNoSanitizeMetadata()
Sets the nosanitize metadata on this instruction.
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...
void analyze(ParentT F)
Create the loop forest for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
A Module instance is used to store all the information related to an LLVM module.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
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
Get the string size.
Class to represent struct types.
static LLVM_ABI 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 LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI 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.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
self_iterator getIterator()
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.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
LLVM_ABI bool isProfileCorrelationEnabled(const cl::LibraryOptionsContext &LibraryOptions)
Return true if -profile-correlate is set.
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void createProfileSamplingVar(Module &M)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
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...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
StringRef getInstrProfVTableNamesVarName()
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
RelativeUniformCounterPtr ValuesPtrExpr Int16ArrayTy
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
auto dyn_cast_or_null(const Y &Val)
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 ...
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
LLVM_ABI 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.
LLVM_ABI 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.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
inst_range instructions(Function *F)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
LLVM_ABI void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
StringRef getInstrProfNamesVarPostfixVarName()
LLVM_ABI 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.
LLVM_ABI bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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...
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI 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 ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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...
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI 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:
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
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."))
@ Extern
Replace returns with jump to thunk, don't emit thunk.
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
This struct is a compact representation of a valid (non-zero power of two) alignment.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.