LLVM 24.0.0git
InstrProfiling.cpp
Go to the documentation of this file.
1//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass lowers instrprof_* intrinsics emitted by an instrumentor.
10// It also builds the data structures and initialization code needed for
11// updating execution counts and emitting the profile at runtime.
12//
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
24#include "llvm/Analysis/CFG.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CFG.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/CycleInfo.h"
33#include "llvm/IR/DIBuilder.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/MDBuilder.h"
47#include "llvm/IR/Module.h"
49#include "llvm/IR/Type.h"
50#include "llvm/Pass.h"
56#include "llvm/Support/Error.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <string>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "instrprof"
72
73namespace llvm {
74// Command line option to enable vtable value profiling. Defined in
75// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
77} // namespace llvm
78
80 const cl::LibraryOptionsContext &LibraryOptions) {
81 return LibraryOptions.get<InstrumentationOptions>()
82 .profile_correlate.has_value();
83}
84
85namespace {
86
87struct SampledInstrumentationConfig {
88 unsigned BurstDuration;
89 unsigned Period;
90 bool UseShort;
91 bool IsSimpleSampling;
92 bool IsFastSampling;
93};
94
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);
107 // If (BurstDuration == 1 && Period == 65536), generate the simple sampling
108 // style code.
109 config.IsFastSampling =
110 (!config.IsSimpleSampling && config.Period == USHRT_MAX + 1);
111 config.UseShort = (config.Period <= USHRT_MAX) || config.IsFastSampling;
112 return config;
113}
114
115using LoadStorePair = std::pair<Instruction *, Instruction *>;
116
117static void makeAtomic(Instruction *Load, Instruction *Store) {
118 auto *Addition = dyn_cast<BinaryOperator>(Store->getOperand(0));
119 assert(Addition && Addition->getOpcode() == Instruction::BinaryOps::Add);
120 auto *Addend = Addition->getOperand(1);
121
122 IRBuilder<> Builder(Load);
123 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Store->getOperand(1), Addend,
125 Store->eraseFromParent();
126 Addition->eraseFromParent();
127 Load->eraseFromParent();
128}
129
130static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
131 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
132 if (!MD)
133 return 0;
134
135 // If the flag is a ConstantAsMetadata, it should be an integer representable
136 // in 64-bits.
137 return cast<ConstantInt>(MD->getValue())->getZExtValue();
138}
139
140static bool enablesValueProfiling(const Module &M) {
141 return isIRPGOFlagSet(&M) ||
142 getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
143}
144
145// Conservatively returns true if value profiling is enabled.
146static bool profDataReferencedByCode(const Module &M) {
147 return enablesValueProfiling(M);
148}
149
150class InstrLowerer final {
151public:
152 InstrLowerer(const InstrumentationOptions &Opts, Module &M,
153 const InstrProfOptions &Options,
154 std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
155 bool IsCS)
156 : Opts(Opts), M(M), Options(Options), TT(M.getTargetTriple()), IsCS(IsCS),
157 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
158
159 bool lower();
160
161private:
162 const InstrumentationOptions &Opts;
163 Module &M;
164 const InstrProfOptions Options;
165 const Triple TT;
166 // Is this lowering for the context-sensitive instrumentation.
167 const bool IsCS;
168
169 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
170
171 const bool DataReferencedByCode;
172
173 struct PerFunctionProfileData {
174 uint32_t NumValueSites[IPVK_Last + 1] = {};
175 GlobalVariable *RegionCounters = nullptr;
176 GlobalVariable *UniformCounters =
177 nullptr; // Per-block uniform-entry counters
178 GlobalVariable *DataVar = nullptr;
179 GlobalVariable *RegionBitmaps = nullptr;
180 uint32_t NumBitmapBytes = 0;
181
182 PerFunctionProfileData() = default;
183 };
184 DenseMap<GlobalVariable *, PerFunctionProfileData> ProfileDataMap;
185 // Key is virtual table variable, value is 'VTableProfData' in the form of
186 // GlobalVariable.
187 DenseMap<GlobalVariable *, GlobalVariable *> VTableDataMap;
188 /// If runtime relocation is enabled, this maps functions to the load
189 /// instruction that produces the profile relocation bias.
190 DenseMap<const Function *, LoadInst *> FunctionToProfileBiasMap;
191 std::vector<GlobalValue *> CompilerUsedVars;
192 std::vector<GlobalValue *> UsedVars;
193 std::vector<GlobalVariable *> ReferencedNames;
194 // The list of virtual table variables of which the VTableProfData is
195 // collected.
196 std::vector<GlobalVariable *> ReferencedVTables;
197 GlobalVariable *NamesVar = nullptr;
198 size_t NamesSize = 0;
199
200 StructType *ProfileDataTy = nullptr;
201
202 // vector of counter load/store pairs to be register promoted.
203 std::vector<LoadStorePair> PromotionCandidates;
204
205 int64_t TotalCountersPromoted = 0;
206
207 // Per-function cache of invariant values for GPU PGO instrumentation.
208 // Computed once at the function entry and reused across all instrumentation
209 // points to avoid redundant IR and help the optimizer.
210 struct GPUPGOInvariants {
211 Value *Matched = nullptr;
212 bool WaveSizeStored = false;
213 };
214 DenseMap<Function *, GPUPGOInvariants> GPUInvariantsCache;
215
216 /// Emit invariant PGO values at the function entry block and cache them.
217 GPUPGOInvariants &getOrCreateGPUInvariants(Function *F);
218
219 /// Lower instrumentation intrinsics in the function. Returns true if there
220 /// any lowering.
221 bool lowerIntrinsics(Function *F);
222
223 /// Register-promote counter loads and stores in loops.
224 void promoteCounterLoadStores(Function *F);
225
226 /// Returns true if relocating counters at runtime is enabled.
227 bool isRuntimeCounterRelocationEnabled() const;
228
229 /// Returns true if profile counter update register promotion is enabled.
230 bool isCounterPromotionEnabled() const;
231
232 /// Returns true if profile counter updates should be atomic.
233 bool isAtomic() const;
234
235 /// Return true if profile sampling is enabled.
236 bool isSamplingEnabled() const;
237
238 /// Count the number of instrumented value sites for the function.
239 void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
240
241 /// Replace instrprof.value.profile with a call to runtime library.
242 void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
243
244 /// Replace instrprof.cover with a store instruction to the coverage byte.
245 void lowerCover(InstrProfCoverInst *Inc);
246
247 /// Replace instrprof.timestamp with a call to
248 /// INSTR_PROF_PROFILE_SET_TIMESTAMP.
249 void lowerTimestamp(InstrProfTimestampInst *TimestampInstruction);
250
251 /// Replace instrprof.increment with an increment of the appropriate value.
252 void lowerIncrement(InstrProfIncrementInst *Inc);
253
254 /// Force emitting of name vars for unused functions.
255 void lowerCoverageData(GlobalVariable *CoverageNamesVar);
256
257 /// Replace instrprof.mcdc.tvbitmask.update with a shift and or instruction
258 /// using the index represented by the a temp value into a bitmap.
259 void lowerMCDCTestVectorBitmapUpdate(InstrProfMCDCTVBitmapUpdate *Ins);
260
261 /// Get the Bias value for data to access mmap-ed area.
262 /// Create it if it hasn't been seen.
263 GlobalVariable *getOrCreateBiasVar(StringRef VarName);
264
265 /// Compute the address of the counter value that this profiling instruction
266 /// acts on.
267 Value *getCounterAddress(InstrProfCntrInstBase *I);
268
269 /// Lower the incremental instructions under profile sampling predicates.
270 void doSampling(Instruction *I);
271
272 /// Get the region counters for an increment, creating them if necessary.
273 ///
274 /// If the counter array doesn't yet exist, the profile data variables
275 /// referring to them will also be created.
276 GlobalVariable *getOrCreateRegionCounters(InstrProfCntrInstBase *Inc);
277
278 /// Get the uniform entry counters for GPU divergence tracking.
279 /// These counters track how often blocks are entered with all lanes active.
280 GlobalVariable *getOrCreateUniformCounters(InstrProfCntrInstBase *Inc);
281
282 /// Create the region counters.
283 GlobalVariable *createRegionCounters(InstrProfCntrInstBase *Inc,
284 StringRef Name,
286
287 /// Compute the address of the test vector bitmap that this profiling
288 /// instruction acts on.
289 Value *getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I);
290
291 /// Get the region bitmaps for an increment, creating them if necessary.
292 ///
293 /// If the bitmap array doesn't yet exist, the profile data variables
294 /// referring to them will also be created.
295 GlobalVariable *getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc);
296
297 /// Create the MC/DC bitmap as a byte-aligned array of bytes associated with
298 /// an MC/DC Decision region. The number of bytes required is indicated by
299 /// the intrinsic used (type InstrProfMCDCBitmapInstBase). This is called
300 /// as part of setupProfileSection() and is conceptually very similar to
301 /// what is done for profile data counters in createRegionCounters().
302 GlobalVariable *createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
303 StringRef Name,
305
306 /// Set Comdat property of GV, if required.
307 void maybeSetComdat(GlobalVariable *GV, GlobalObject *GO, StringRef VarName);
308
309 /// Setup the sections into which counters and bitmaps are allocated.
310 GlobalVariable *setupProfileSection(InstrProfInstBase *Inc,
311 InstrProfSectKind IPSK);
312
313 /// Create INSTR_PROF_DATA variable for counters and bitmaps.
314 void createDataVariable(InstrProfCntrInstBase *Inc);
315
316 /// Get the counters for virtual table values, creating them if necessary.
317 void getOrCreateVTableProfData(GlobalVariable *GV);
318
319 /// Emit the section with compressed function names.
320 void emitNameData();
321
322 /// Emit the section with compressed vtable names.
323 void emitVTableNames();
324
325 /// Emit value nodes section for value profiling.
326 void emitVNodes();
327
328 /// Emit runtime registration functions for each profile data variable.
329 void emitRegistration();
330
331 /// Emit the necessary plumbing to pull in the runtime initialization.
332 /// Returns true if a change was made.
333 bool emitRuntimeHook();
334
335 /// Add uses of our data variables and runtime hook.
336 void emitUses();
337
338 /// Create a static initializer for our data, on platforms that need it,
339 /// and for any profile output file that was specified.
340 void emitInitialization();
341
342 /// Return the __llvm_profile_data struct type.
343 StructType *getProfileDataTy();
344};
345
346///
347/// A helper class to promote one counter RMW operation in the loop
348/// into register update.
349///
350/// RWM update for the counter will be sinked out of the loop after
351/// the transformation.
352///
353class PGOCounterPromoterHelper : public LoadAndStorePromoter {
354public:
355 PGOCounterPromoterHelper(
356 const InstrumentationOptions &Opts, Instruction *L, Instruction *S,
357 SSAUpdater &SSA, Value *Init, BasicBlock *PH,
358 ArrayRef<BasicBlock *> ExitBlocks, ArrayRef<Instruction *> InsertPts,
359 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
360 LoopInfo &LI, bool IsAtomic)
361 : LoadAndStorePromoter({L, S}, SSA), Opts(Opts), Store(S),
362 ExitBlocks(ExitBlocks), InsertPts(InsertPts),
363 LoopToCandidates(LoopToCands), LI(LI), IsAtomic(IsAtomic) {
366 SSA.AddAvailableValue(PH, Init);
367 }
368
369 void doExtraRewritesBeforeFinalDeletion() override {
370 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
371 BasicBlock *ExitBlock = ExitBlocks[i];
372 Instruction *InsertPos = InsertPts[i];
373 // Get LiveIn value into the ExitBlock. If there are multiple
374 // predecessors, the value is defined by a PHI node in this
375 // block.
376 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
377 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
378 Type *Ty = LiveInValue->getType();
379 IRBuilder<> Builder(InsertPos);
380 if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
381 // If isRuntimeCounterRelocationEnabled() is true then the address of
382 // the store instruction is computed with two instructions in
383 // InstrProfiling::getCounterAddress(). We need to copy those
384 // instructions to this block to compute Addr correctly.
385 // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
386 // %Addr = inttoptr i64 %BiasAdd to i64*
387 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
388 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
389 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
390 Addr = Builder.CreateIntToPtr(BiasInst,
391 PointerType::getUnqual(Ty->getContext()));
392 }
393 auto *TargetLoop =
394 Opts.iterative_counter_promotion ? LI.getLoopFor(ExitBlock) : nullptr;
395 // Generate the relaxed atomic RMW if we've asked for it and no more
396 // promotion is possible.
397 if ((IsAtomic && !TargetLoop) || Opts.atomic_counter_update_promoted)
398 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
399 MaybeAlign(), AtomicOrdering::Monotonic);
400 else {
401 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
402 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
403 auto *NewStore = Builder.CreateStore(NewVal, Addr);
404
405 // Now update the parent loop's candidate list:
406 if (TargetLoop)
407 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
408 }
409 }
410 }
411
412private:
413 const InstrumentationOptions &Opts;
414 Instruction *Store;
415 ArrayRef<BasicBlock *> ExitBlocks;
416 ArrayRef<Instruction *> InsertPts;
417 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
418 LoopInfo &LI;
419 const bool IsAtomic;
420};
421
422/// A helper class to do register promotion for all profile counter
423/// updates in a loop.
424///
425class PGOCounterPromoter {
426public:
427 PGOCounterPromoter(
428 const InstrumentationOptions &Opts,
429 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
430 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI, bool IsAtomic)
431 : Opts(Opts), LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI),
432 IsAtomic(IsAtomic) {
433
434 // Skip collection of ExitBlocks and InsertPts for loops that will not be
435 // able to have counters promoted.
436 SmallVector<BasicBlock *, 8> LoopExitBlocks;
437 SmallPtrSet<BasicBlock *, 8> BlockSet;
438
439 L.getExitBlocks(LoopExitBlocks);
440 if (!isPromotionPossible(&L, LoopExitBlocks))
441 return;
442
443 for (BasicBlock *ExitBlock : LoopExitBlocks) {
444 if (BlockSet.insert(ExitBlock).second &&
445 llvm::none_of(predecessors(ExitBlock), [&](const BasicBlock *Pred) {
446 return llvm::isPresplitCoroSuspendExitEdge(*Pred, *ExitBlock);
447 })) {
448 ExitBlocks.push_back(ExitBlock);
449 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
450 }
451 }
452 }
453
454 bool run(int64_t *NumPromoted) {
455 // Move L's candidates out of LoopToCandidates before promoting them, as
456 // promoting a counter to an enclosing loop may insert a new key into
457 // LoopToCandidates and trigger DenseMap::grow().
458 auto &OrigCandidates = LoopToCandidates[&L];
459 SmallVector<LoadStorePair, 8> Candidates = std::move(OrigCandidates);
460 OrigCandidates.clear();
461 bool RC = promoteCandidates(Candidates, NumPromoted);
462 assert(LoopToCandidates[&L].empty() &&
463 "Did not expect new candidates to be added to current loop");
464 // In certain case, e.g. with -fprofile-update=atomic, we want to generate
465 // atomic updates of the PGO counters, but also perform promotion of these
466 // updates out of loops to reduce train time. The strategy is:
467 // 1) generate non-atomic load-increment-store sequence of instructions
468 // during lowerIntrinsics phase,
469 // 2) perform the promotion (in promoteCandidates function), then
470 // 3) convert all (promoted and unpromotable) updates to atomicRMW.
471 // This requires that promoted candidates are set to nullptr in the
472 // Candidates array by the promoteCandidates() function.
473 if (IsAtomic)
474 for (auto &Cand : Candidates)
475 if (Cand.first != nullptr && Cand.second != nullptr)
476 makeAtomic(Cand.first, Cand.second);
477 return RC;
478 }
479
480private:
481 bool promoteCandidates(SmallVectorImpl<LoadStorePair> &Candidates,
482 int64_t *NumPromoted) {
483 // Skip 'infinite' loops:
484 if (ExitBlocks.size() == 0)
485 return false;
486
487 // Skip if any of the ExitBlocks contains a ret instruction.
488 // This is to prevent dumping of incomplete profile -- if the
489 // the loop is a long running loop and dump is called in the middle
490 // of the loop, the result profile is incomplete.
491 // FIXME: add other heuristics to detect long running loops.
492 if (Opts.skip_ret_exit_block) {
493 for (auto *BB : ExitBlocks)
494 if (isa<ReturnInst>(BB->getTerminator()))
495 return false;
496 }
497
498 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
499 if (MaxProm == 0)
500 return false;
501
502 unsigned Promoted = 0;
503 for (auto &Cand : Candidates) {
505 SSAUpdater SSA(&NewPHIs);
506 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
507
508 // If BFI is set, we will use it to guide the promotions.
509 if (BFI) {
510 auto *BB = Cand.first->getParent();
511 auto InstrCount = BFI->getBlockProfileCount(BB);
512 if (!InstrCount)
513 continue;
514 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
515 // If the average loop trip count is not greater than 1.5, we skip
516 // promotion.
517 if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
518 continue;
519 }
520
521 PGOCounterPromoterHelper Promoter(
522 Opts, Cand.first, Cand.second, SSA, InitVal, L.getLoopPreheader(),
523 ExitBlocks, InsertPts, LoopToCandidates, LI, IsAtomic);
524 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
525
526 Cand = {nullptr, nullptr};
527
528 Promoted++;
529 if (Promoted >= MaxProm)
530 break;
531
532 (*NumPromoted)++;
533 if (Opts.max_counter_promotions != -1 &&
534 *NumPromoted >= Opts.max_counter_promotions)
535 break;
536 }
537
538 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
539 << L.getLoopDepth() << ")\n");
540 return Promoted != 0;
541 }
542
543private:
544 bool allowSpeculativeCounterPromotion(Loop *LP) {
545 SmallVector<BasicBlock *, 8> ExitingBlocks;
546 L.getExitingBlocks(ExitingBlocks);
547 // Not considierered speculative.
548 if (ExitingBlocks.size() == 1)
549 return true;
550 if (ExitingBlocks.size() > Opts.speculative_counter_promotion_max_exiting)
551 return false;
552 return true;
553 }
554
555 // Check whether the loop satisfies the basic conditions needed to perform
556 // Counter Promotions.
557 bool
558 isPromotionPossible(Loop *LP,
559 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
560 // We can't insert into a catchswitch.
561 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
562 return isa<CatchSwitchInst>(Exit->getTerminator());
563 }))
564 return false;
565
566 if (!LP->hasDedicatedExits())
567 return false;
568
569 BasicBlock *PH = LP->getLoopPreheader();
570 if (!PH)
571 return false;
572
573 return true;
574 }
575
576 // Returns the max number of Counter Promotions for LP.
577 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
578 SmallVector<BasicBlock *, 8> LoopExitBlocks;
579 LP->getExitBlocks(LoopExitBlocks);
580 if (!isPromotionPossible(LP, LoopExitBlocks))
581 return 0;
582
583 SmallVector<BasicBlock *, 8> ExitingBlocks;
584 LP->getExitingBlocks(ExitingBlocks);
585
586 // If BFI is set, we do more aggressive promotions based on BFI.
587 if (BFI)
588 return (unsigned)-1;
589
590 // Not considierered speculative.
591 if (ExitingBlocks.size() == 1)
592 return Opts.max_counter_promotions_per_loop;
593
594 if (ExitingBlocks.size() > Opts.speculative_counter_promotion_max_exiting)
595 return 0;
596
597 // Whether the target block is in a loop does not matter:
598 if (Opts.speculative_counter_promotion_to_loop)
599 return Opts.max_counter_promotions_per_loop;
600
601 // Now check the target block:
602 unsigned MaxProm = Opts.max_counter_promotions_per_loop;
603 for (auto *TargetBlock : LoopExitBlocks) {
604 auto *TargetLoop = LI.getLoopFor(TargetBlock);
605 if (!TargetLoop)
606 continue;
607 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
608 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
609 MaxProm =
610 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
611 PendingCandsInTarget);
612 }
613 return MaxProm;
614 }
615
616 const InstrumentationOptions &Opts;
617 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
618 SmallVector<BasicBlock *, 8> ExitBlocks;
619 SmallVector<Instruction *, 8> InsertPts;
620 Loop &L;
621 LoopInfo &LI;
622 BlockFrequencyInfo *BFI;
623 const bool IsAtomic; // Whether to convert counter updates to atomics.
624};
625
626enum class ValueProfilingCallType {
627 // Individual values are tracked. Currently used for indiret call target
628 // profiling.
629 Default,
630
631 // MemOp: the memop size value profiling.
632 MemOp
633};
634
635} // end anonymous namespace
636
641 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
642 return FAM.getResult<TargetLibraryAnalysis>(F);
643 };
644 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
645 InstrLowerer Lowerer(Opts, M, Options, GetTLI, IsCS);
646 if (!Lowerer.lower())
647 return PreservedAnalyses::all();
648
650}
651
652//
653// Perform instrumentation sampling.
654//
655// There are 3 favors of sampling:
656// (1) Full burst sampling: We transform:
657// Increment_Instruction;
658// to:
659// if (__llvm_profile_sampling__ <= SampledInstrBurstDuration - 1) {
660// Increment_Instruction;
661// }
662// __llvm_profile_sampling__ += 1;
663// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
664// __llvm_profile_sampling__ = 0;
665// }
666//
667// "__llvm_profile_sampling__" is a thread-local global shared by all PGO
668// counters (value-instrumentation and edge instrumentation).
669//
670// (2) Fast burst sampling:
671// "__llvm_profile_sampling__" variable is an unsigned type, meaning it will
672// wrap around to zero when overflows. In this case, the second check is
673// unnecessary, so we won't generate check2 when the SampledInstrPeriod is
674// set to 65536 (64K). The code after:
675// if (__llvm_profile_sampling__ <= SampledInstrBurstDuration - 1) {
676// Increment_Instruction;
677// }
678// __llvm_profile_sampling__ += 1;
679//
680// (3) Simple sampling:
681// When SampledInstrBurstDuration is set to 1, we do a simple sampling:
682// __llvm_profile_sampling__ += 1;
683// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
684// __llvm_profile_sampling__ = 0;
685// Increment_Instruction;
686// }
687//
688// Note that, the code snippet after the transformation can still be counter
689// promoted. However, with sampling enabled, counter updates are expected to
690// be infrequent, making the benefits of counter promotion negligible.
691// Moreover, counter promotion can potentially cause issues in server
692// applications, particularly when the counters are dumped without a clean
693// exit. To mitigate this risk, counter promotion is disabled by default when
694// sampling is enabled. This behavior can be overridden using the internal
695// option.
696void InstrLowerer::doSampling(Instruction *I) {
697 if (!isSamplingEnabled())
698 return;
699
700 SampledInstrumentationConfig config = getSampledInstrumentationConfig(Opts);
701 auto GetConstant = [&config](IRBuilder<> &Builder, uint32_t C) {
702 if (config.UseShort)
703 return Builder.getInt16(C);
704 else
705 return Builder.getInt32(C);
706 };
707
708 IntegerType *SamplingVarTy;
709 if (config.UseShort)
710 SamplingVarTy = Type::getInt16Ty(M.getContext());
711 else
712 SamplingVarTy = Type::getInt32Ty(M.getContext());
713 auto *SamplingVar =
715 assert(SamplingVar && "SamplingVar not set properly");
716
717 // Create the condition for checking the burst duration.
718 Instruction *SamplingVarIncr;
719 Value *NewSamplingVarVal;
720 MDBuilder MDB(I->getContext());
721 MDNode *BranchWeight;
722 IRBuilder<> CondBuilder(I);
723 auto *LoadSamplingVar = CondBuilder.CreateLoad(SamplingVarTy, SamplingVar);
724 if (config.IsSimpleSampling) {
725 // For the simple sampling, just create the load and increments.
726 IRBuilder<> IncBuilder(I);
727 NewSamplingVarVal =
728 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
729 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
730 } else {
731 // For the burst-sampling, create the conditional update.
732 auto *DurationCond = CondBuilder.CreateICmpULE(
733 LoadSamplingVar, GetConstant(CondBuilder, config.BurstDuration - 1));
734 BranchWeight = MDB.createBranchWeights(
735 config.BurstDuration, config.Period - config.BurstDuration);
737 DurationCond, I, /* Unreachable */ false, BranchWeight);
738 IRBuilder<> IncBuilder(I);
739 NewSamplingVarVal =
740 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
741 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
742 I->moveBefore(ThenTerm->getIterator());
743 }
744
745 if (config.IsFastSampling)
746 return;
747
748 // Create the condition for checking the period.
749 Instruction *ThenTerm, *ElseTerm;
750 IRBuilder<> PeriodCondBuilder(SamplingVarIncr);
751 auto *PeriodCond = PeriodCondBuilder.CreateICmpUGE(
752 NewSamplingVarVal, GetConstant(PeriodCondBuilder, config.Period));
753 BranchWeight = MDB.createBranchWeights(1, config.Period - 1);
754 SplitBlockAndInsertIfThenElse(PeriodCond, SamplingVarIncr, &ThenTerm,
755 &ElseTerm, BranchWeight);
756
757 // For the simple sampling, the counter update happens in sampling var reset.
758 if (config.IsSimpleSampling)
759 I->moveBefore(ThenTerm->getIterator());
760
761 IRBuilder<> ResetBuilder(ThenTerm);
762 ResetBuilder.CreateStore(GetConstant(ResetBuilder, 0), SamplingVar);
763 SamplingVarIncr->moveBefore(ElseTerm->getIterator());
764}
765
766bool InstrLowerer::lowerIntrinsics(Function *F) {
767 bool MadeChange = false;
768 PromotionCandidates.clear();
770
771 // To ensure compatibility with sampling, we save the intrinsics into
772 // a buffer to prevent potential breakage of the iterator (as the
773 // intrinsics will be moved to a different BB).
774 for (BasicBlock &BB : *F) {
775 for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
776 if (auto *IP = dyn_cast<InstrProfInstBase>(&Instr))
777 InstrProfInsts.push_back(IP);
778 }
779 }
780
781 for (auto *Instr : InstrProfInsts) {
782 doSampling(Instr);
783 if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(Instr)) {
784 lowerIncrement(IPIS);
785 MadeChange = true;
786 } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(Instr)) {
787 lowerIncrement(IPI);
788 MadeChange = true;
789 } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(Instr)) {
790 lowerTimestamp(IPC);
791 MadeChange = true;
792 } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(Instr)) {
793 lowerCover(IPC);
794 MadeChange = true;
795 } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(Instr)) {
796 lowerValueProfileInst(IPVP);
797 MadeChange = true;
798 } else if (auto *IPMP = dyn_cast<InstrProfMCDCBitmapParameters>(Instr)) {
799 IPMP->eraseFromParent();
800 MadeChange = true;
801 } else if (auto *IPBU = dyn_cast<InstrProfMCDCTVBitmapUpdate>(Instr)) {
802 lowerMCDCTestVectorBitmapUpdate(IPBU);
803 MadeChange = true;
804 }
805 }
806
807 if (!MadeChange)
808 return false;
809
810 promoteCounterLoadStores(F);
811 return true;
812}
813
814bool InstrLowerer::isRuntimeCounterRelocationEnabled() const {
815 // Mach-O don't support weak external references.
816 if (TT.isOSBinFormatMachO())
817 return false;
818
819 // Fuchsia uses runtime counter relocation by default.
820 return valueOr(Opts.runtime_counter_relocation, TT.isOSFuchsia());
821}
822
823bool InstrLowerer::isSamplingEnabled() const {
824 return valueOr(Opts.sampled_instrumentation, Options.Sampling);
825}
826
827bool InstrLowerer::isCounterPromotionEnabled() const {
828 return valueOr(Opts.do_counter_promotion, Options.DoCounterPromotion);
829}
830
831bool InstrLowerer::isAtomic() const {
832 return Options.Atomic || Opts.instrprof_atomic_counter_update_all;
833}
834
835static void doAtomicCheck(Function *F) {
836 for (const llvm::Instruction &I : llvm::instructions(F)) {
837 const Value *Addr = nullptr;
838 if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
839 Addr = LI->getOperand(0);
840 else if (const StoreInst *LI = dyn_cast<StoreInst>(&I))
841 Addr = LI->getOperand(1);
842
843 if (Addr && Addr->stripInBoundsOffsets()->getName().starts_with(
845 LLVM_DEBUG(dbgs() << "Missed candidate: "; I.dump());
846 report_fatal_error("Candidate load/store not converted to atomic");
847 }
848 }
849}
850
851void InstrLowerer::promoteCounterLoadStores(Function *F) {
852 if (!isCounterPromotionEnabled())
853 return;
854
855 CycleInfo CI;
856 CI.compute(*F);
857 LoopInfo LI;
858 LI.analyze(F);
859 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
860
861 std::unique_ptr<BlockFrequencyInfo> BFI;
862 if (Options.UseBFIInPromotion) {
863 std::unique_ptr<BranchProbabilityInfo> BPI;
864 BPI.reset(new BranchProbabilityInfo(*F, CI, &GetTLI(*F)));
865 BFI.reset(new BlockFrequencyInfo(*F, *BPI, CI));
866 }
867
868 for (const auto &LoadStore : PromotionCandidates) {
869 auto *CounterLoad = LoadStore.first;
870 auto *CounterStore = LoadStore.second;
871 BasicBlock *BB = CounterLoad->getParent();
872 Loop *ParentLoop = LI.getLoopFor(BB);
873 if (!ParentLoop) {
874 if (isAtomic())
875 makeAtomic(CounterLoad, CounterStore);
876 continue;
877 }
878 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
879 }
880
882
883 // Do a post-order traversal of the loops so that counter updates can be
884 // iteratively hoisted outside the loop nest.
885 for (auto *Loop : llvm::reverse(Loops)) {
886 PGOCounterPromoter Promoter(Opts, LoopPromotionCandidates, *Loop, LI,
887 BFI.get(), isAtomic());
888 Promoter.run(&TotalCountersPromoted);
889 }
890
891 if (isAtomic() && Opts.verify_atomic_counter_promoted)
893}
894
896 // On Fuchsia, we only need runtime hook if any counters are present.
897 if (TT.isOSFuchsia())
898 return false;
899
900 return true;
901}
902
903/// Check if the module contains uses of any profiling intrinsics.
905 auto containsIntrinsic = [&](int ID) {
906 if (auto *F = Intrinsic::getDeclarationIfExists(&M, ID))
907 return !F->use_empty();
908 return false;
909 };
910 return containsIntrinsic(Intrinsic::instrprof_cover) ||
911 containsIntrinsic(Intrinsic::instrprof_increment) ||
912 containsIntrinsic(Intrinsic::instrprof_increment_step) ||
913 containsIntrinsic(Intrinsic::instrprof_timestamp) ||
914 containsIntrinsic(Intrinsic::instrprof_value_profile);
915}
916
917bool InstrLowerer::lower() {
918 bool MadeChange = false;
919 bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
920 if (NeedsRuntimeHook)
921 MadeChange = emitRuntimeHook();
922
923 if (!IsCS && isSamplingEnabled())
925
926 bool ContainsProfiling = containsProfilingIntrinsics(M);
927 GlobalVariable *CoverageNamesVar =
928 M.getNamedGlobal(getCoverageUnusedNamesVarName());
929 // Improve compile time by avoiding linear scans when there is no work.
930 if (!ContainsProfiling && !CoverageNamesVar)
931 return MadeChange;
932
933 // We did not know how many value sites there would be inside
934 // the instrumented function. This is counting the number of instrumented
935 // target value sites to enter it as field in the profile data variable.
936 for (Function &F : M) {
937 InstrProfCntrInstBase *FirstProfInst = nullptr;
938 for (BasicBlock &BB : F) {
939 for (auto I = BB.begin(), E = BB.end(); I != E; I++) {
940 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
941 computeNumValueSiteCounts(Ind);
942 else {
943 if (FirstProfInst == nullptr &&
945 FirstProfInst = dyn_cast<InstrProfCntrInstBase>(I);
946 // If the MCDCBitmapParameters intrinsic seen, create the bitmaps.
947 if (const auto &Params = dyn_cast<InstrProfMCDCBitmapParameters>(I))
948 static_cast<void>(getOrCreateRegionBitmaps(Params));
949 }
950 }
951 }
952
953 // Use a profile intrinsic to create the region counters and data variable.
954 // Also create the data variable based on the MCDCParams.
955 if (FirstProfInst != nullptr) {
956 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
957 }
958 }
959
961 for (GlobalVariable &GV : M.globals())
962 // Global variables with type metadata are virtual table variables.
963 if (GV.hasMetadata(LLVMContext::MD_type))
964 getOrCreateVTableProfData(&GV);
965
966 for (Function &F : M)
967 MadeChange |= lowerIntrinsics(&F);
968
969 if (CoverageNamesVar) {
970 lowerCoverageData(CoverageNamesVar);
971 MadeChange = true;
972 }
973
974 if (!MadeChange)
975 return false;
976
977 emitVNodes();
978 emitNameData();
979 emitVTableNames();
980
981 // Emit runtime hook for the cases where the target does not unconditionally
982 // require pulling in profile runtime, and coverage is enabled on code that is
983 // not eliminated by the front-end, e.g. unused functions with internal
984 // linkage.
985 if (!NeedsRuntimeHook && ContainsProfiling)
986 emitRuntimeHook();
987
988 emitRegistration();
989 emitUses();
990 emitInitialization();
991 return true;
992}
993
995 Module &M, const TargetLibraryInfo &TLI,
996 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
997 LLVMContext &Ctx = M.getContext();
998 auto *ReturnTy = Type::getVoidTy(M.getContext());
999
1000 AttributeList AL;
1001 if (auto AK = TLI.getExtAttrForI32Param(false))
1002 AL = AL.addParamAttribute(M.getContext(), 2, AK);
1003
1004 assert((CallType == ValueProfilingCallType::Default ||
1005 CallType == ValueProfilingCallType::MemOp) &&
1006 "Must be Default or MemOp");
1007 Type *ParamTypes[] = {
1008#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
1010 };
1011 auto *ValueProfilingCallTy =
1012 FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
1013 StringRef FuncName = CallType == ValueProfilingCallType::Default
1016 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
1017}
1018
1019void InstrLowerer::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
1020 GlobalVariable *Name = Ind->getName();
1022 uint64_t Index = Ind->getIndex()->getZExtValue();
1023 auto &PD = ProfileDataMap[Name];
1024 PD.NumValueSites[ValueKind] =
1025 std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
1026}
1027
1028void InstrLowerer::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
1029 // TODO: Value profiling heavily depends on the data section which is omitted
1030 // in lightweight mode. We need to move the value profile pointer to the
1031 // Counter struct to get this working.
1032 assert(
1033 !Opts.profile_correlate &&
1034 "Value profiling is not yet supported with lightweight instrumentation");
1035 GlobalVariable *Name = Ind->getName();
1036 auto It = ProfileDataMap.find(Name);
1037 assert(It != ProfileDataMap.end() && It->second.DataVar &&
1038 "value profiling detected in function with no counter increment");
1039
1040 GlobalVariable *DataVar = It->second.DataVar;
1042 uint64_t Index = Ind->getIndex()->getZExtValue();
1043 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
1044 Index += It->second.NumValueSites[Kind];
1045
1046 IRBuilder<> Builder(Ind);
1047 bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
1048 llvm::InstrProfValueKind::IPVK_MemOPSize);
1049 CallInst *Call = nullptr;
1050 auto *TLI = &GetTLI(*Ind->getFunction());
1051 auto *NormalizedDataVarPtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1052 DataVar, PointerType::get(M.getContext(), 0));
1053
1054 // To support value profiling calls within Windows exception handlers, funclet
1055 // information contained within operand bundles needs to be copied over to
1056 // the library call. This is required for the IR to be processed by the
1057 // WinEHPrepare pass.
1059 Ind->getOperandBundlesAsDefs(OpBundles);
1060 if (!IsMemOpSize) {
1061 Value *Args[3] = {Ind->getTargetValue(), NormalizedDataVarPtr,
1062 Builder.getInt32(Index)};
1063 Call = Builder.CreateCall(getOrInsertValueProfilingCall(M, *TLI), Args,
1064 OpBundles);
1065 } else {
1066 Value *Args[3] = {Ind->getTargetValue(), NormalizedDataVarPtr,
1067 Builder.getInt32(Index)};
1068 Call = Builder.CreateCall(
1069 getOrInsertValueProfilingCall(M, *TLI, ValueProfilingCallType::MemOp),
1070 Args, OpBundles);
1071 }
1072 if (auto AK = TLI->getExtAttrForI32Param(false))
1073 Call->addParamAttr(2, AK);
1075 Ind->eraseFromParent();
1076}
1077
1078GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
1079 GlobalVariable *Bias = M.getGlobalVariable(VarName);
1080 if (Bias)
1081 return Bias;
1082
1083 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1084
1085 // Compiler must define this variable when runtime counter relocation
1086 // is being used. Runtime has a weak external reference that is used
1087 // to check whether that's the case or not.
1088 Bias = new GlobalVariable(M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
1089 Constant::getNullValue(Int64Ty), VarName);
1091 // A definition that's weak (linkonce_odr) without being in a COMDAT
1092 // section wouldn't lead to link errors, but it would lead to a dead
1093 // data word from every TU but one. Putting it in COMDAT ensures there
1094 // will be exactly one data slot in the link.
1095 if (TT.supportsCOMDAT())
1096 Bias->setComdat(M.getOrInsertComdat(VarName));
1097
1098 return Bias;
1099}
1100
1101Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
1102 auto *Counters = getOrCreateRegionCounters(I);
1103 IRBuilder<> Builder(I);
1104
1106 Counters->setAlignment(Align(8));
1107
1108 auto *Addr = Builder.CreateConstInBoundsGEP2_32(
1109 Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
1110
1111 if (!isRuntimeCounterRelocationEnabled())
1112 return Addr;
1113
1114 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1115 Function *Fn = I->getParent()->getParent();
1116 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
1117 if (!BiasLI) {
1118 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1119 auto *Bias = getOrCreateBiasVar(getInstrProfCounterBiasVarName());
1120 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profc_bias");
1121 // Bias doesn't change after startup.
1122 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1123 MDNode::get(M.getContext(), {}));
1124 }
1125 auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
1126 return Builder.CreateIntToPtr(Add, Addr->getType());
1127}
1128
1129Value *InstrLowerer::getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I) {
1130 auto *Bitmaps = getOrCreateRegionBitmaps(I);
1131 if (!isRuntimeCounterRelocationEnabled())
1132 return Bitmaps;
1133
1134 // Put BiasLI onto the entry block.
1135 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1136 Function *Fn = I->getFunction();
1137 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1138 auto *Bias = getOrCreateBiasVar(getInstrProfBitmapBiasVarName());
1139 auto *BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profbm_bias");
1140 // Assume BiasLI invariant (in the function at least)
1141 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1142 MDNode::get(M.getContext(), {}));
1143
1144 // Add Bias to Bitmaps and put it before the intrinsic.
1145 IRBuilder<> Builder(I);
1146 return Builder.CreatePtrAdd(Bitmaps, BiasLI, "profbm_addr");
1147}
1148
1149void InstrLowerer::lowerCover(InstrProfCoverInst *CoverInstruction) {
1150 auto *Addr = getCounterAddress(CoverInstruction);
1151 IRBuilder<> Builder(CoverInstruction);
1152 if (Opts.conditional_counter_update) {
1153 Instruction *SplitBefore = CoverInstruction->getNextNode();
1154 auto &Ctx = CoverInstruction->getParent()->getContext();
1155 auto *Int8Ty = llvm::Type::getInt8Ty(Ctx);
1156 Value *Load = Builder.CreateLoad(Int8Ty, Addr, "pgocount");
1157 Value *Cmp = Builder.CreateIsNotNull(Load, "pgocount.ifnonzero");
1158 Instruction *ThenBranch =
1159 SplitBlockAndInsertIfThen(Cmp, SplitBefore, false);
1160 Builder.SetInsertPoint(ThenBranch);
1161 }
1162
1163 // We store zero to represent that this block is covered.
1164 Builder.CreateStore(Builder.getInt8(0), Addr);
1165 CoverInstruction->eraseFromParent();
1166}
1167
1168void InstrLowerer::lowerTimestamp(
1169 InstrProfTimestampInst *TimestampInstruction) {
1170 assert(TimestampInstruction->getIndex()->isNullValue() &&
1171 "timestamp probes are always the first probe for a function");
1172 auto &Ctx = M.getContext();
1173 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1174 IRBuilder<> Builder(TimestampInstruction);
1175 auto *CalleeTy =
1176 FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
1177 auto Callee = M.getOrInsertFunction(
1179 Builder.CreateCall(Callee, {TimestampAddr});
1180 TimestampInstruction->eraseFromParent();
1181}
1182
1183InstrLowerer::GPUPGOInvariants &
1184InstrLowerer::getOrCreateGPUInvariants(Function *F) {
1185 auto It = GPUInvariantsCache.find(F);
1186 if (It != GPUInvariantsCache.end())
1187 return It->second;
1188
1189 LLVMContext &Context = M.getContext();
1190 auto *Int32Ty = Type::getInt32Ty(Context);
1191
1192 BasicBlock &EntryBB = F->getEntryBlock();
1193 IRBuilder<> Builder(&*EntryBB.getFirstInsertionPt());
1194
1196 if (Opts.offload_pgo_sampling > 0) {
1197 FunctionCallee IsSampledFn =
1199 RTLIB::impl___llvm_profile_sampling_gpu),
1200 Int32Ty, Int32Ty);
1201 Value *SampledInt = Builder.CreateCall(
1202 IsSampledFn, {ConstantInt::get(Int32Ty, Opts.offload_pgo_sampling)},
1203 "pgo.sampled");
1204 Matched = Builder.CreateICmpNE(SampledInt, ConstantInt::get(Int32Ty, 0),
1205 "pgo.matched");
1206 }
1207
1208 auto &Inv = GPUInvariantsCache[F];
1209 Inv.Matched = Matched;
1210 return Inv;
1211}
1212
1213void InstrLowerer::lowerIncrement(InstrProfIncrementInst *Inc) {
1214 IRBuilder<> Builder(Inc);
1215 if (isGPUProfTarget(M)) {
1216 Function *F = Inc->getFunction();
1217 auto &Inv = getOrCreateGPUInvariants(F);
1218
1219 LLVMContext &Context = M.getContext();
1220 auto *Int64Ty = Type::getInt64Ty(Context);
1221 auto *PtrTy = PointerType::getUnqual(Context);
1222
1223 auto *Addr = getCounterAddress(Inc);
1224
1225 // Store the device wave/warp size into the profile data struct once per
1226 // function. AMDGPU folds llvm.amdgcn.wavefrontsize to the subtarget's
1227 // constant; other GPUs use their fixed warp size.
1228 if (!Inv.WaveSizeStored) {
1229 Inv.WaveSizeStored = true;
1230 GlobalVariable *NamePtr = Inc->getName();
1231 auto &PD = ProfileDataMap[NamePtr];
1232 if (PD.DataVar) {
1233 IRBuilder<> EntryBuilder(&*F->getEntryBlock().getFirstInsertionPt());
1234 Value *WaveSize16 = nullptr;
1235 // Look the intrinsic up by name so this target-agnostic pass does not
1236 // pull in IntrinsicsAMDGPU.h. AMDGPU folds the intrinsic to the
1237 // subtarget's wavefront size; other GPUs fall back to a 32-lane warp.
1238 if (TT.isAMDGPU()) {
1239 Intrinsic::ID WaveSizeID =
1240 Intrinsic::lookupIntrinsicID("llvm.amdgcn.wavefrontsize");
1241 if (WaveSizeID != Intrinsic::not_intrinsic) {
1242 Function *WaveSizeFn =
1243 Intrinsic::getOrInsertDeclaration(&M, WaveSizeID);
1244 Value *WaveSize = EntryBuilder.CreateCall(WaveSizeFn);
1245 WaveSize16 = EntryBuilder.CreateTrunc(
1246 WaveSize, Type::getInt16Ty(Context), "wavesize.i16");
1247 }
1248 }
1249 if (!WaveSize16)
1250 WaveSize16 = ConstantInt::get(Type::getInt16Ty(Context), 32);
1251 Value *WaveSizeAddr = EntryBuilder.CreateStructGEP(
1252 PD.DataVar->getValueType(), PD.DataVar, 9, "profd.wavesize");
1253 EntryBuilder.CreateStore(WaveSize16, WaveSizeAddr);
1254 }
1255 }
1256
1257 GlobalVariable *UniformCounters = getOrCreateUniformCounters(Inc);
1258 Value *UniformAddrArg = ConstantPointerNull::get(PtrTy);
1259 if (UniformCounters) {
1260 Value *UniformIndices[] = {Builder.getInt32(0), Inc->getIndex()};
1261 Value *UniformAddr = Builder.CreateInBoundsGEP(
1262 UniformCounters->getValueType(), UniformCounters, UniformIndices,
1263 "unifctr.addr");
1264 UniformAddrArg =
1265 Builder.CreatePointerBitCastOrAddrSpaceCast(UniformAddr, PtrTy);
1266 }
1267 Value *CastAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PtrTy);
1268 Value *StepI64 =
1269 Builder.CreateZExtOrTrunc(Inc->getStep(), Int64Ty, "step.i64");
1270
1271 auto *CalleeTy = FunctionType::get(Type::getVoidTy(Context),
1272 {PtrTy, PtrTy, Int64Ty}, false);
1275 RTLIB::impl___llvm_profile_instrument_gpu),
1276 CalleeTy);
1277
1278 if (Opts.offload_pgo_sampling > 0) {
1279 BasicBlock *CurBB = Builder.GetInsertBlock();
1280 BasicBlock *ContBB =
1281 CurBB->splitBasicBlock(BasicBlock::iterator(Inc), "po_cont");
1282 BasicBlock *ThenBB = BasicBlock::Create(Context, "po_then", F);
1283
1284 CurBB->getTerminator()->eraseFromParent();
1285 IRBuilder<> HeadBuilder(CurBB);
1286 HeadBuilder.CreateCondBr(Inv.Matched, ThenBB, ContBB);
1287
1288 IRBuilder<> ThenBuilder(ThenBB);
1289 ThenBuilder.CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1290 ThenBuilder.CreateBr(ContBB);
1291 } else {
1292 Builder.CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1293 }
1294 Inc->eraseFromParent();
1295 return;
1296 }
1297
1298 auto *Addr = getCounterAddress(Inc);
1299 // If promotion is enabled then delay generating atomic updates until
1300 // after promotion is done.
1301 if ((!isCounterPromotionEnabled() && isAtomic()) ||
1302 (Inc->getIndex()->isNullValue() && Opts.atomic_first_counter)) {
1303 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
1305 } else {
1306 Value *IncStep = Inc->getStep();
1307 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
1308 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
1309 auto *Store = Builder.CreateStore(Count, Addr);
1310 if (isCounterPromotionEnabled())
1311 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
1312 }
1313 Inc->eraseFromParent();
1314}
1315
1316void InstrLowerer::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
1317 ConstantArray *Names =
1318 cast<ConstantArray>(CoverageNamesVar->getInitializer());
1319 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
1320 Constant *NC = Names->getOperand(I);
1321 Value *V = NC->stripPointerCasts();
1322 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
1324
1325 Name->setLinkage(GlobalValue::PrivateLinkage);
1326 ReferencedNames.push_back(Name);
1327 if (isa<ConstantExpr>(NC))
1328 NC->dropAllReferences();
1329 }
1330 CoverageNamesVar->eraseFromParent();
1331}
1332
1333void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1335 auto &Ctx = M.getContext();
1336 IRBuilder<> Builder(Update);
1337 auto *Int8Ty = Type::getInt8Ty(Ctx);
1338 auto *Int32Ty = Type::getInt32Ty(Ctx);
1339 auto *MCDCCondBitmapAddr = Update->getMCDCCondBitmapAddr();
1340 auto *BitmapAddr = getBitmapAddress(Update);
1341
1342 // Load Temp Val + BitmapIdx.
1343 // %mcdc.temp = load i32, ptr %mcdc.addr, align 4
1344 auto *Temp = Builder.CreateAdd(
1345 Builder.CreateLoad(Int32Ty, MCDCCondBitmapAddr, "mcdc.temp"),
1346 Update->getBitmapIndex());
1347
1348 // Calculate byte offset using div8.
1349 // %1 = lshr i32 %mcdc.temp, 3
1350 auto *BitmapByteOffset = Builder.CreateLShr(Temp, 0x3);
1351
1352 // Add byte offset to section base byte address.
1353 // %4 = getelementptr inbounds i8, ptr @__profbm_test, i32 %1
1354 auto *BitmapByteAddr =
1355 Builder.CreateInBoundsPtrAdd(BitmapAddr, BitmapByteOffset);
1356
1357 // Calculate bit offset into bitmap byte by using div8 remainder (AND ~8)
1358 // %5 = and i32 %mcdc.temp, 7
1359 // %6 = trunc i32 %5 to i8
1360 auto *BitToSet = Builder.CreateTrunc(Builder.CreateAnd(Temp, 0x7), Int8Ty);
1361
1362 // Shift bit offset left to form a bitmap.
1363 // %7 = shl i8 1, %6
1364 auto *ShiftedVal = Builder.CreateShl(Builder.getInt8(0x1), BitToSet);
1365
1366 // Load profile bitmap byte.
1367 // %mcdc.bits = load i8, ptr %4, align 1
1368 auto *Bitmap = Builder.CreateLoad(Int8Ty, BitmapByteAddr, "mcdc.bits");
1369
1370 if (isAtomic()) {
1371 // If ((Bitmap & Val) != Val), then execute atomic (Bitmap |= Val).
1372 // Note, just-loaded Bitmap might not be up-to-date. Use it just for
1373 // early testing.
1374 auto *Masked = Builder.CreateAnd(Bitmap, ShiftedVal);
1375 auto *ShouldStore = Builder.CreateICmpNE(Masked, ShiftedVal);
1376
1377 // Assume updating will be rare.
1378 auto *Unlikely = MDBuilder(Ctx).createUnlikelyBranchWeights();
1379 Instruction *ThenBranch =
1380 SplitBlockAndInsertIfThen(ShouldStore, Update, false, Unlikely);
1381
1382 // Execute if (unlikely(ShouldStore)).
1383 Builder.SetInsertPoint(ThenBranch);
1384 Builder.CreateAtomicRMW(AtomicRMWInst::Or, BitmapByteAddr, ShiftedVal,
1386 } else {
1387 // Perform logical OR of profile bitmap byte and shifted bit offset.
1388 // %8 = or i8 %mcdc.bits, %7
1389 auto *Result = Builder.CreateOr(Bitmap, ShiftedVal);
1390
1391 // Store the updated profile bitmap byte.
1392 // store i8 %8, ptr %3, align 1
1393 Builder.CreateStore(Result, BitmapByteAddr);
1394 }
1395
1396 Update->eraseFromParent();
1397}
1398
1399/// Get the name of a profiling variable for a particular function.
1400static std::string getVarName(const InstrumentationOptions &Opts,
1401 InstrProfInstBase *Inc, StringRef Prefix,
1402 bool &Renamed) {
1403 StringRef NamePrefix = getInstrProfNameVarPrefix();
1404 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
1405 Function *F = Inc->getParent()->getParent();
1406 Module *M = F->getParent();
1407 if (!Opts.hash_based_counter_split || !isIRPGOFlagSet(M) ||
1409 Renamed = false;
1410 return (Prefix + Name).str();
1411 }
1412 Renamed = true;
1414 SmallVector<char, 24> HashPostfix;
1415 if (Name.ends_with((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
1416 return (Prefix + Name).str();
1417 return (Prefix + Name + "." + Twine(FuncHash)).str();
1418}
1419
1421 // Only record function addresses if IR PGO is enabled or if clang value
1422 // profiling is enabled. Recording function addresses greatly increases object
1423 // file size, because it prevents the inliner from deleting functions that
1424 // have been inlined everywhere.
1425 if (!profDataReferencedByCode(*F->getParent()))
1426 return false;
1427
1428 // Check the linkage
1429 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
1430 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
1431 !HasAvailableExternallyLinkage)
1432 return true;
1433
1434 // A function marked 'alwaysinline' with available_externally linkage can't
1435 // have its address taken. Doing so would create an undefined external ref to
1436 // the function, which would fail to link.
1437 if (HasAvailableExternallyLinkage &&
1438 F->hasFnAttribute(Attribute::AlwaysInline))
1439 return false;
1440
1441 // Prohibit function address recording if the function is both internal and
1442 // COMDAT. This avoids the profile data variable referencing internal symbols
1443 // in COMDAT.
1444 if (F->hasLocalLinkage() && F->hasComdat())
1445 return false;
1446
1447 // Check uses of this function for other than direct calls or invokes to it.
1448 // Inline virtual functions have linkeOnceODR linkage. When a key method
1449 // exists, the vtable will only be emitted in the TU where the key method
1450 // is defined. In a TU where vtable is not available, the function won't
1451 // be 'addresstaken'. If its address is not recorded here, the profile data
1452 // with missing address may be picked by the linker leading to missing
1453 // indirect call target info.
1454 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
1455}
1456
1457static inline bool shouldUsePublicSymbol(Function *Fn) {
1458 // It isn't legal to make an alias of this function at all
1459 if (Fn->isDeclarationForLinker())
1460 return true;
1461
1462 // Symbols with local linkage can just use the symbol directly without
1463 // introducing relocations
1464 if (Fn->hasLocalLinkage())
1465 return true;
1466
1467 // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
1468 // unfavorable interaction between the new alias and the alias renaming done
1469 // in LowerTypeTests under ThinLTO. For comdat functions that would normally
1470 // be deduplicated, but the renaming scheme ends up preventing renaming, since
1471 // it creates unique names for each alias, resulting in duplicated symbols. In
1472 // the future, we should update the CFI related passes to migrate these
1473 // aliases to the same module as the jump-table they refer to will be defined.
1474 if (Fn->hasMetadata(LLVMContext::MD_type))
1475 return true;
1476
1477 // For comdat functions, an alias would need the same linkage as the original
1478 // function and hidden visibility. There is no point in adding an alias with
1479 // identical linkage an visibility to avoid introducing symbolic relocations.
1480 if (Fn->hasComdat() &&
1482 return true;
1483
1484 // its OK to use an alias
1485 return false;
1486}
1487
1489 auto *Int8PtrTy = PointerType::getUnqual(Fn->getContext());
1490 // Store a nullptr in __llvm_profd, if we shouldn't use a real address
1491 if (!shouldRecordFunctionAddr(Fn))
1492 return ConstantPointerNull::get(Int8PtrTy);
1493
1494 // If we can't use an alias, we must use the public symbol, even though this
1495 // may require a symbolic relocation.
1496 if (shouldUsePublicSymbol(Fn))
1497 return Fn;
1498
1499 // For GPU targets, weak functions cannot use private aliases because
1500 // LTO may pick a different TU's copy, leaving the alias undefined
1501 if (isGPUProfTarget(*Fn->getParent()) &&
1503 return Fn;
1504
1505 // When possible use a private alias to avoid symbolic relocations.
1507 Fn->getName() + ".local", Fn);
1508
1509 // When the instrumented function is a COMDAT function, we cannot use a
1510 // private alias. If we did, we would create reference to a local label in
1511 // this function's section. If this version of the function isn't selected by
1512 // the linker, then the metadata would introduce a reference to a discarded
1513 // section. So, for COMDAT functions, we need to adjust the linkage of the
1514 // alias. Using hidden visibility avoids a dynamic relocation and an entry in
1515 // the dynamic symbol table.
1516 //
1517 // Note that this handles COMDAT functions with visibility other than Hidden,
1518 // since that case is covered in shouldUsePublicSymbol()
1519 if (Fn->hasComdat()) {
1520 GA->setLinkage(Fn->getLinkage());
1522 }
1523
1524 // appendToCompilerUsed(*Fn->getParent(), {GA});
1525
1526 return GA;
1527}
1528
1530 // NVPTX is an ELF target but PTX does not expose sections or linker symbols.
1531 if (TT.isNVPTX())
1532 return true;
1533
1534 // compiler-rt uses linker support to get data/counters/name start/end for
1535 // ELF, COFF, Mach-O, XCOFF, and Wasm.
1536 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1537 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF() ||
1538 TT.isOSBinFormatWasm())
1539 return false;
1540
1541 return true;
1542}
1543
1544void InstrLowerer::maybeSetComdat(GlobalVariable *GV, GlobalObject *GO,
1545 StringRef CounterGroupName) {
1546 // Place lowered global variables in a comdat group if the associated function
1547 // or global variable is a COMDAT. This will make sure that only one copy of
1548 // global variable (e.g. function counters) of the COMDAT function will be
1549 // emitted after linking.
1550 bool NeedComdat = needsComdatForCounter(*GO, M);
1551 bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1552
1553 if (!UseComdat)
1554 return;
1555
1556 // Keep in mind that this pass may run before the inliner, so we need to
1557 // create a new comdat group (for counters, profiling data, etc). If we use
1558 // the comdat of the parent function, that will result in relocations against
1559 // discarded sections.
1560 //
1561 // If the data variable is referenced by code, non-counter variables (notably
1562 // profiling data) and counters have to be in different comdats for COFF
1563 // because the Visual C++ linker will report duplicate symbol errors if there
1564 // are multiple external symbols with the same name marked
1565 // IMAGE_COMDAT_SELECT_ASSOCIATIVE.
1566 StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1567 ? GV->getName()
1568 : CounterGroupName;
1569 Comdat *C = M.getOrInsertComdat(GroupName);
1570
1571 if (!NeedComdat) {
1572 // Object file format must be ELF since `UseComdat && !NeedComdat` is true.
1573 //
1574 // For ELF, when not using COMDAT, put counters, data and values into a
1575 // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
1576 // allows -z start-stop-gc to discard the entire group when the function is
1577 // discarded.
1578 C->setSelectionKind(Comdat::NoDeduplicate);
1579 }
1580 GV->setComdat(C);
1581 // COFF doesn't allow the comdat group leader to have private linkage, so
1582 // upgrade private linkage to internal linkage to produce a symbol table
1583 // entry.
1584 if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1586}
1587
1589 if (!profDataReferencedByCode(*GV->getParent()))
1590 return false;
1591
1592 if (!GV->hasLinkOnceLinkage() && !GV->hasLocalLinkage() &&
1594 return true;
1595
1596 // This avoids the profile data from referencing internal symbols in
1597 // COMDAT.
1598 if (GV->hasLocalLinkage() && GV->hasComdat())
1599 return false;
1600
1601 return true;
1602}
1603
1604// FIXME: Introduce an internal alias like what's done for functions to reduce
1605// the number of relocation entries.
1607 // Store a nullptr in __profvt_ if a real address shouldn't be used.
1608 if (!shouldRecordVTableAddr(GV))
1610
1611 return GV;
1612}
1613
1614void InstrLowerer::getOrCreateVTableProfData(GlobalVariable *GV) {
1615 assert(Opts.profile_correlate != ProfCorrelatorKind::DebugInfo &&
1616 "Value profiling is not supported with lightweight instrumentation");
1618 return;
1619
1620 // Skip llvm internal global variable or __prof variables.
1621 if (GV->getName().starts_with("llvm.") ||
1622 GV->getName().starts_with("__llvm") ||
1623 GV->getName().starts_with("__prof"))
1624 return;
1625
1626 // VTableProfData already created
1627 auto It = VTableDataMap.find(GV);
1628 if (It != VTableDataMap.end() && It->second)
1629 return;
1630
1633
1634 // This is to keep consistent with per-function profile data
1635 // for correctness.
1636 if (TT.isOSBinFormatXCOFF()) {
1638 Visibility = GlobalValue::DefaultVisibility;
1639 }
1640
1641 LLVMContext &Ctx = M.getContext();
1642 Type *DataTypes[] = {
1643#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1645#undef INSTR_PROF_VTABLE_DATA
1646 };
1647
1648 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1649
1650 // Used by INSTR_PROF_VTABLE_DATA MACRO
1651 Constant *VTableAddr = getVTableAddrForProfData(GV);
1652 const std::string PGOVTableName = getIRPGOObjectName(*GV);
1653 // Record the length of the vtable. This is needed since vtable pointers
1654 // loaded from C++ objects might be from the middle of a vtable definition.
1655 uint32_t VTableSizeVal = GV->getGlobalSize(M.getDataLayout());
1656
1657 Constant *DataVals[] = {
1658#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1660#undef INSTR_PROF_VTABLE_DATA
1661 };
1662
1663 auto *Data =
1664 new GlobalVariable(M, DataTy, /*constant=*/false, Linkage,
1665 ConstantStruct::get(DataTy, DataVals),
1666 getInstrProfVTableVarPrefix() + PGOVTableName);
1667
1668 Data->setVisibility(Visibility);
1669 Data->setSection(getInstrProfSectionName(IPSK_vtab, TT.getObjectFormat()));
1670 Data->setAlignment(Align(8));
1671
1672 maybeSetComdat(Data, GV, Data->getName());
1673
1674 VTableDataMap[GV] = Data;
1675
1676 ReferencedVTables.push_back(GV);
1677
1678 // VTable <Hash, Addr> is used by runtime but not referenced by other
1679 // sections. Conservatively mark it linker retained.
1680 UsedVars.push_back(Data);
1681}
1682
1683GlobalVariable *InstrLowerer::setupProfileSection(InstrProfInstBase *Inc,
1684 InstrProfSectKind IPSK) {
1685 GlobalVariable *NamePtr = Inc->getName();
1686
1687 // Match the linkage and visibility of the name global.
1688 Function *Fn = Inc->getParent()->getParent();
1690 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1691
1692 // Use internal rather than private linkage so the counter variable shows up
1693 // in the symbol table when using debug info for correlation.
1694 if (Opts.profile_correlate == ProfCorrelatorKind::DebugInfo &&
1695 TT.isOSBinFormatMachO() && Linkage == GlobalValue::PrivateLinkage)
1697
1698 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1699 // symbols in the same csect won't be discarded. When there are duplicate weak
1700 // symbols, we can NOT guarantee that the relocations get resolved to the
1701 // intended weak symbol, so we can not ensure the correctness of the relative
1702 // CounterPtr, so we have to use private linkage for counter and data symbols.
1703 if (TT.isOSBinFormatXCOFF()) {
1705 Visibility = GlobalValue::DefaultVisibility;
1706 }
1707 // Move the name variable to the right section.
1708 bool Renamed;
1709 GlobalVariable *Ptr;
1710 StringRef VarPrefix;
1711 std::string VarName;
1712 if (IPSK == IPSK_cnts) {
1713 VarPrefix = getInstrProfCountersVarPrefix();
1714 VarName = getVarName(Opts, Inc, VarPrefix, Renamed);
1716 Ptr = createRegionCounters(CntrIncrement, VarName, Linkage);
1717 } else if (IPSK == IPSK_bitmap) {
1718 VarPrefix = getInstrProfBitmapVarPrefix();
1719 VarName = getVarName(Opts, Inc, VarPrefix, Renamed);
1720 InstrProfMCDCBitmapInstBase *BitmapUpdate =
1722 Ptr = createRegionBitmaps(BitmapUpdate, VarName, Linkage);
1723 } else {
1724 llvm_unreachable("Profile Section must be for Counters or Bitmaps");
1725 }
1726
1727 Ptr->setVisibility(Visibility);
1728 Ptr->setSection(getInstrProfSectionName(IPSK, TT.getObjectFormat()));
1729 Ptr->setLinkage(Linkage);
1730 if (isGPUProfTarget(M) && !Ptr->hasComdat()) {
1731 Ptr->setComdat(M.getOrInsertComdat(VarName));
1734 } else {
1735 maybeSetComdat(Ptr, Fn, VarName);
1736 }
1737 return Ptr;
1738}
1739
1741InstrLowerer::createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
1742 StringRef Name,
1744 uint64_t NumBytes = Inc->getNumBitmapBytes();
1745 auto *BitmapTy = ArrayType::get(Type::getInt8Ty(M.getContext()), NumBytes);
1746 auto GV = new GlobalVariable(M, BitmapTy, false, Linkage,
1747 Constant::getNullValue(BitmapTy), Name);
1748 GV->setAlignment(Align(1));
1749 return GV;
1750}
1751
1753InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
1754 GlobalVariable *NamePtr = Inc->getName();
1755 auto &PD = ProfileDataMap[NamePtr];
1756 if (PD.RegionBitmaps)
1757 return PD.RegionBitmaps;
1758
1759 // If RegionBitmaps doesn't already exist, create it by first setting up
1760 // the corresponding profile section.
1761 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1762 PD.RegionBitmaps = BitmapPtr;
1763 PD.NumBitmapBytes = Inc->getNumBitmapBytes();
1764
1765 if (PD.NumBitmapBytes &&
1766 Opts.profile_correlate == ProfCorrelatorKind::DebugInfo) {
1767 LLVMContext &Ctx = M.getContext();
1768 Function *Fn = Inc->getParent()->getParent();
1769 if (auto *SP = Fn->getSubprogram()) {
1770 DIBuilder DB(M, true, SP->getUnit());
1771 Metadata *FunctionNameAnnotation[] = {
1774 };
1775 Metadata *NumBitmapBitsAnnotation[] = {
1778 };
1779 auto Annotations = DB.getOrCreateArray({
1780 MDNode::get(Ctx, FunctionNameAnnotation),
1781 MDNode::get(Ctx, NumBitmapBitsAnnotation),
1782 });
1783 auto *DICounter = DB.createGlobalVariableExpression(
1784 SP, BitmapPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1785 /*LineNo=*/0, DB.createUnspecifiedType("Profile Bitmap Type"),
1786 BitmapPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1787 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1788 Annotations);
1789 BitmapPtr->addDebugInfo(DICounter);
1790 DB.finalizeSubprogram(SP);
1791 DB.finalize();
1792 }
1793
1794 // Mark the bitmap variable as used so that it isn't optimized out.
1795 CompilerUsedVars.push_back(PD.RegionBitmaps);
1796 }
1797
1798 return PD.RegionBitmaps;
1799}
1800
1802InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
1804 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1805 auto &Ctx = M.getContext();
1806 GlobalVariable *GV;
1807 if (isa<InstrProfCoverInst>(Inc)) {
1808 auto *CounterTy = Type::getInt8Ty(Ctx);
1809 auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
1810 // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
1811 std::vector<Constant *> InitialValues(NumCounters,
1812 Constant::getAllOnesValue(CounterTy));
1813 GV = new GlobalVariable(M, CounterArrTy, false, Linkage,
1814 ConstantArray::get(CounterArrTy, InitialValues),
1815 Name);
1816 GV->setAlignment(Align(1));
1817 } else {
1818 auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
1819 GV = new GlobalVariable(M, CounterTy, false, Linkage,
1820 Constant::getNullValue(CounterTy), Name);
1821 GV->setAlignment(Align(8));
1822 }
1823 return GV;
1824}
1825
1827InstrLowerer::getOrCreateRegionCounters(InstrProfCntrInstBase *Inc) {
1828 GlobalVariable *NamePtr = Inc->getName();
1829 auto &PD = ProfileDataMap[NamePtr];
1830 if (PD.RegionCounters)
1831 return PD.RegionCounters;
1832
1833 // If RegionCounters doesn't already exist, create it by first setting up
1834 // the corresponding profile section.
1835 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1836 PD.RegionCounters = CounterPtr;
1837
1838 if (Opts.profile_correlate == ProfCorrelatorKind::DebugInfo) {
1839 LLVMContext &Ctx = M.getContext();
1840 Function *Fn = Inc->getParent()->getParent();
1841 if (auto *SP = Fn->getSubprogram()) {
1842 DIBuilder DB(M, true, SP->getUnit());
1843 Metadata *FunctionNameAnnotation[] = {
1846 };
1847 Metadata *CFGHashAnnotation[] = {
1850 };
1851 Metadata *NumCountersAnnotation[] = {
1854 };
1855 auto Annotations = DB.getOrCreateArray({
1856 MDNode::get(Ctx, FunctionNameAnnotation),
1857 MDNode::get(Ctx, CFGHashAnnotation),
1858 MDNode::get(Ctx, NumCountersAnnotation),
1859 });
1860 auto *DICounter = DB.createGlobalVariableExpression(
1861 SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1862 /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
1863 CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1864 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1865 Annotations);
1866 CounterPtr->addDebugInfo(DICounter);
1867 DB.finalizeSubprogram(SP);
1868 DB.finalize();
1869 }
1870
1871 // Mark the counter variable as used so that it isn't optimized out.
1872 CompilerUsedVars.push_back(PD.RegionCounters);
1873 }
1874
1875 // Create uniform counters before the data variable so that
1876 // UniformCounterPtr can reference them in createDataVariable().
1877 getOrCreateUniformCounters(Inc);
1878
1879 // Create the data variable (if it doesn't already exist).
1880 createDataVariable(Inc);
1881
1882 return PD.RegionCounters;
1883}
1884
1886InstrLowerer::getOrCreateUniformCounters(InstrProfCntrInstBase *Inc) {
1887 // Uniform counters are only meaningful for GPU profile targets.
1888 if (!isGPUProfTarget(M))
1889 return nullptr;
1890
1891 GlobalVariable *NamePtr = Inc->getName();
1892 auto &PD = ProfileDataMap[NamePtr];
1893 if (PD.UniformCounters)
1894 return PD.UniformCounters;
1895
1896 assert(PD.RegionCounters && "region counters must be created first");
1897
1898 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1899
1900 LLVMContext &Ctx = M.getContext();
1901 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
1902
1903 bool Renamed;
1904 std::string VarName = getVarName(Opts, Inc, "__llvm_prf_unifcnt_", Renamed);
1905
1906 auto *GV = new GlobalVariable(M, CounterTy, false, NamePtr->getLinkage(),
1907 Constant::getNullValue(CounterTy), VarName);
1908 GV->setAlignment(Align(8));
1909
1910 GV->setSection(getInstrProfSectionName(IPSK_ucnts, TT.getObjectFormat()));
1911
1912 GV->setComdat(M.getOrInsertComdat(VarName));
1915
1916 PD.UniformCounters = GV;
1917 CompilerUsedVars.push_back(GV);
1918
1919 return PD.UniformCounters;
1920}
1921
1922void InstrLowerer::createDataVariable(InstrProfCntrInstBase *Inc) {
1923 // When debug information is correlated to profile data, a data variable
1924 // is not needed.
1925 if (Opts.profile_correlate == ProfCorrelatorKind::DebugInfo)
1926 return;
1927
1928 GlobalVariable *NamePtr = Inc->getName();
1929 auto &PD = ProfileDataMap[NamePtr];
1930
1931 // Return if data variable was already created.
1932 if (PD.DataVar)
1933 return;
1934
1935 LLVMContext &Ctx = M.getContext();
1936
1937 Function *Fn = Inc->getParent()->getParent();
1939 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1940
1941 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1942 // symbols in the same csect won't be discarded. When there are duplicate weak
1943 // symbols, we can NOT guarantee that the relocations get resolved to the
1944 // intended weak symbol, so we can not ensure the correctness of the relative
1945 // CounterPtr, so we have to use private linkage for counter and data symbols.
1946 if (TT.isOSBinFormatXCOFF()) {
1948 Visibility = GlobalValue::DefaultVisibility;
1949 }
1950
1951 bool NeedComdat = needsComdatForCounter(*Fn, M);
1952 bool Renamed;
1953
1954 // The Data Variable section is anchored to profile counters.
1955 std::string CntsVarName =
1956 getVarName(Opts, Inc, getInstrProfCountersVarPrefix(), Renamed);
1957 std::string DataVarName =
1958 getVarName(Opts, Inc, getInstrProfDataVarPrefix(), Renamed);
1959
1960 auto *Int8PtrTy = PointerType::getUnqual(Ctx);
1961 // Allocate statically the array of pointers to value profile nodes for
1962 // the current function.
1963 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1964 uint64_t NS = 0;
1965 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1966 NS += PD.NumValueSites[Kind];
1967 if (NS > 0 && Opts.vp_static_alloc &&
1969 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1970 auto *ValuesVar = new GlobalVariable(
1971 M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1972 getVarName(Opts, Inc, getInstrProfValuesVarPrefix(), Renamed));
1973 ValuesVar->setVisibility(Visibility);
1974 setGlobalVariableLargeSection(TT, *ValuesVar);
1975 ValuesVar->setSection(
1976 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1977 ValuesVar->setAlignment(Align(8));
1978 maybeSetComdat(ValuesVar, Fn, CntsVarName);
1980 ValuesVar, PointerType::get(Fn->getContext(), 0));
1981 }
1982
1983 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1984
1985 Constant *CounterPtr = PD.RegionCounters;
1986 Constant *UniformCounterPtr = PD.UniformCounters;
1987
1988 uint64_t NumBitmapBytes = PD.NumBitmapBytes;
1989
1990 // Create data variable.
1991 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
1992 auto *Int16Ty = Type::getInt16Ty(Ctx);
1993 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1994 auto *DataTy = getProfileDataTy();
1995
1996 Constant *FunctionAddr = getFuncAddrForProfData(Fn);
1997
1998 Constant *Int16ArrayVals[IPVK_Last + 1];
1999 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
2000 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
2001
2002 uint16_t OffloadDeviceWaveSizeVal = 0;
2003
2004 if (isGPUProfTarget(M)) {
2005 // For GPU targets, weak functions need weak linkage for their profile data
2006 // aliases to allow linker deduplication across TUs
2008 Linkage = Fn->getLinkage();
2009 else
2012 }
2013 // If the data variable is not referenced by code (if we don't emit
2014 // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
2015 // data variable live under linker GC, the data variable can be private. This
2016 // optimization applies to ELF.
2017 //
2018 // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
2019 // to be false.
2020 //
2021 // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
2022 // that other copies must have the same CFG and cannot have value profiling.
2023 // If no hash suffix, other profd copies may be referenced by code.
2024 if (!isGPUProfTarget(M) && NS == 0 &&
2025 !(DataReferencedByCode && NeedComdat && !Renamed) &&
2026 (TT.isOSBinFormatELF() ||
2027 (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
2029 Visibility = GlobalValue::DefaultVisibility;
2030 }
2031 // GPU-target ELF objects are always ET_DYN, so non-local symbols with
2032 // default visibility are preemptible. The CounterPtr label difference
2033 // emits a REL32 relocation that lld rejects against preemptible targets.
2034 if (TT.isGPU() && TT.isOSBinFormatELF() &&
2037 auto *Data =
2038 new GlobalVariable(M, DataTy, false, Linkage, nullptr, DataVarName);
2039
2040 Constant *RelativeCounterPtr;
2041 Constant *RelativeUniformCounterPtr = ConstantInt::get(IntPtrTy, 0);
2042 GlobalVariable *BitmapPtr = PD.RegionBitmaps;
2043 Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
2044 InstrProfSectKind DataSectionKind;
2045 // With binary profile correlation, profile data is not loaded into memory.
2046 // profile data must reference profile counter with an absolute relocation.
2047 if (Opts.profile_correlate == ProfCorrelatorKind::Binary) {
2048 DataSectionKind = IPSK_covdata;
2049 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
2050 if (BitmapPtr != nullptr)
2051 RelativeBitmapPtr = ConstantExpr::getPtrToInt(BitmapPtr, IntPtrTy);
2052 if (UniformCounterPtr != nullptr)
2053 RelativeUniformCounterPtr =
2055 } else if (TT.isNVPTX()) {
2056 // The NVPTX target cannot handle self-referencing constant expressions in
2057 // global initializers at all. Use absolute pointers and have the runtime
2058 // registration convert them to relative offsets.
2059 DataSectionKind = IPSK_data;
2060 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
2061 } else {
2062 // Reference the counter variable with a label difference (link-time
2063 // constant).
2064 DataSectionKind = IPSK_data;
2065 RelativeCounterPtr =
2068 if (BitmapPtr != nullptr)
2069 RelativeBitmapPtr =
2072 if (UniformCounterPtr != nullptr)
2073 RelativeUniformCounterPtr = ConstantExpr::getSub(
2076 }
2077
2078 Constant *DataVals[] = {
2079#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
2081 };
2082 Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
2083
2084 Data->setVisibility(Visibility);
2085 Data->setSection(
2086 getInstrProfSectionName(DataSectionKind, TT.getObjectFormat()));
2087 Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
2088 if (isGPUProfTarget(M) && !Data->hasComdat()) {
2089 Data->setComdat(M.getOrInsertComdat(CntsVarName));
2091 } else {
2092 maybeSetComdat(Data, Fn, CntsVarName);
2093 }
2094
2095 PD.DataVar = Data;
2096
2097 // Mark the data variable as used so that it isn't stripped out.
2098 CompilerUsedVars.push_back(Data);
2099 // Now that the linkage set by the FE has been passed to the data and counter
2100 // variables, reset Name variable's linkage and visibility to private so that
2101 // it can be removed later by the compiler.
2103 // Collect the referenced names to be used by emitNameData.
2104 ReferencedNames.push_back(NamePtr);
2105}
2106
2107void InstrLowerer::emitVNodes() {
2108 if (!Opts.vp_static_alloc)
2109 return;
2110
2111 // For now only support this on platforms that do
2112 // not require runtime registration to discover
2113 // named section start/end.
2115 return;
2116
2117 size_t TotalNS = 0;
2118 for (auto &PD : ProfileDataMap) {
2119 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
2120 TotalNS += PD.second.NumValueSites[Kind];
2121 }
2122
2123 if (!TotalNS)
2124 return;
2125
2126 uint64_t NumCounters = TotalNS * Opts.vp_counters_per_site;
2127// Heuristic for small programs with very few total value sites.
2128// The default value of vp-counters-per-site is chosen based on
2129// the observation that large apps usually have a low percentage
2130// of value sites that actually have any profile data, and thus
2131// the average number of counters per site is low. For small
2132// apps with very few sites, this may not be true. Bump up the
2133// number of counters in this case.
2134#define INSTR_PROF_MIN_VAL_COUNTS 10
2135 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
2136 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
2137
2138 auto &Ctx = M.getContext();
2139 Type *VNodeTypes[] = {
2140#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
2142 };
2143 auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
2144
2145 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
2146 auto *VNodesVar = new GlobalVariable(
2147 M, VNodesTy, false, GlobalValue::PrivateLinkage,
2149 setGlobalVariableLargeSection(TT, *VNodesVar);
2150 VNodesVar->setSection(
2151 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
2152 VNodesVar->setAlignment(M.getDataLayout().getABITypeAlign(VNodesTy));
2153 // VNodesVar is used by runtime but not referenced via relocation by other
2154 // sections. Conservatively make it linker retained.
2155 UsedVars.push_back(VNodesVar);
2156}
2157
2158// Build the per-TU device-PGO sections struct: section start/stop bounds for
2159// names/counters/data/uniform-counters plus the raw version. Returns null if it
2160// already exists.
2162 StringRef CUIDPostfix) {
2163 std::string Name = ("__llvm_profile_sections" + CUIDPostfix).str();
2164 if (M.getNamedValue(Name))
2165 return nullptr;
2166
2167 LLVMContext &Ctx = M.getContext();
2168 unsigned AS = M.getDataLayout().getDefaultGlobalsAddressSpace();
2169 auto Extern = [&](StringRef Sym, Type *Ty, bool IsConst,
2171 GlobalVariable *GV = M.getNamedGlobal(Sym);
2172 if (!GV) {
2173 GV = new GlobalVariable(M, Ty, IsConst, GlobalValue::ExternalLinkage,
2174 nullptr, Sym, nullptr,
2176 GV->setVisibility(Vis);
2177 }
2178 return GV;
2179 };
2180 // Section bounds are hidden i8 markers; raw_version is an i64 constant.
2181 auto *I8 = Type::getInt8Ty(Ctx);
2182 auto Hidden = GlobalValue::HiddenVisibility;
2183 Constant *Fields[] = {Extern("__start___llvm_prf_names", I8, false, Hidden),
2184 Extern("__stop___llvm_prf_names", I8, false, Hidden),
2185 Extern("__start___llvm_prf_cnts", I8, false, Hidden),
2186 Extern("__stop___llvm_prf_cnts", I8, false, Hidden),
2187 Extern("__start___llvm_prf_data", I8, false, Hidden),
2188 Extern("__stop___llvm_prf_data", I8, false, Hidden),
2189 Extern("__start___llvm_prf_ucnts", I8, false, Hidden),
2190 Extern("__stop___llvm_prf_ucnts", I8, false, Hidden),
2191 Extern("__llvm_profile_raw_version",
2192 Type::getInt64Ty(Ctx), true,
2194 auto *PtrTy = PointerType::get(Ctx, AS);
2195 auto *STy = StructType::get(
2196 Ctx, {PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy});
2197 auto *GV = new GlobalVariable(M, STy, /*isConstant=*/true,
2199 ConstantStruct::get(STy, Fields), Name, nullptr,
2201 GV->setVisibility(GlobalValue::ProtectedVisibility);
2202 return GV;
2203}
2204
2205void InstrLowerer::emitNameData() {
2206 if (ReferencedNames.empty())
2207 return;
2208
2209 std::string CompressedNameStr;
2210 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
2212 report_fatal_error(Twine(toString(std::move(E))), false);
2213 }
2214
2215 auto &Ctx = M.getContext();
2216 auto *NamesVal =
2217 ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
2218 std::string NamesVarName = std::string(getInstrProfNamesVarName());
2221 std::string GPUCUIDPostfix;
2222 if (isGPUProfTarget(M)) {
2223 if (auto *GV = M.getNamedGlobal(getInstrProfNamesVarPostfixVarName())) {
2224 if (auto *Init =
2226 if (Init->isCString()) {
2227 GPUCUIDPostfix = Init->getAsCString().str();
2228 NamesVarName += GPUCUIDPostfix;
2229 NamesLinkage = GlobalValue::ExternalLinkage;
2230 NamesVisibility = GlobalValue::ProtectedVisibility;
2232 M, [GV](Constant *C) { return C->stripPointerCasts() == GV; });
2233 GV->eraseFromParent();
2234 }
2235 }
2236 }
2237 }
2238 NamesVar = new GlobalVariable(M, NamesVal->getType(), true, NamesLinkage,
2239 NamesVal, NamesVarName);
2240 NamesVar->setVisibility(NamesVisibility);
2241
2242 NamesSize = CompressedNameStr.size();
2243 setGlobalVariableLargeSection(TT, *NamesVar);
2244 std::string NamesSectionName =
2245 Opts.profile_correlate == ProfCorrelatorKind::Binary
2246 ? getInstrProfSectionName(IPSK_covname, TT.getObjectFormat())
2247 : getInstrProfSectionName(IPSK_name, TT.getObjectFormat());
2248 NamesVar->setSection(NamesSectionName);
2249 // On COFF, it's important to reduce the alignment down to 1 to prevent the
2250 // linker from inserting padding before the start of the names section or
2251 // between names entries.
2252 NamesVar->setAlignment(Align(1));
2253 // NamesVar is used by runtime but not referenced via relocation by other
2254 // sections. Conservatively make it linker retained.
2255 UsedVars.push_back(NamesVar);
2256
2257 for (auto *NamePtr : ReferencedNames)
2258 NamePtr->eraseFromParent();
2259
2260 // Emit the device sections struct only when this TU produced profile data, so
2261 // its section start/stop references are backed by a real section.
2262 bool HasData = llvm::any_of(ProfileDataMap,
2263 [](const auto &KV) { return KV.second.DataVar; });
2264 if (!GPUCUIDPostfix.empty() && HasData)
2265 if (GlobalVariable *GV = emitGPUOffloadSectionsStruct(M, GPUCUIDPostfix))
2266 CompilerUsedVars.push_back(GV);
2267}
2268
2269void InstrLowerer::emitVTableNames() {
2270 if (!EnableVTableValueProfiling || ReferencedVTables.empty())
2271 return;
2272
2273 // Collect the PGO names of referenced vtables and compress them.
2274 std::string CompressedVTableNames;
2275 if (Error E = collectVTableStrings(ReferencedVTables, CompressedVTableNames,
2277 report_fatal_error(Twine(toString(std::move(E))), false);
2278 }
2279
2280 auto &Ctx = M.getContext();
2281 auto *VTableNamesVal = ConstantDataArray::getString(
2282 Ctx, StringRef(CompressedVTableNames), false /* AddNull */);
2283 GlobalVariable *VTableNamesVar =
2284 new GlobalVariable(M, VTableNamesVal->getType(), true /* constant */,
2285 GlobalValue::PrivateLinkage, VTableNamesVal,
2287 VTableNamesVar->setSection(
2288 getInstrProfSectionName(IPSK_vname, TT.getObjectFormat()));
2289 VTableNamesVar->setAlignment(Align(1));
2290 // Make VTableNames linker retained.
2291 UsedVars.push_back(VTableNamesVar);
2292}
2293
2294void InstrLowerer::emitRegistration() {
2296 return;
2297
2298 // Construct the function.
2299 auto *VoidTy = Type::getVoidTy(M.getContext());
2300 auto *VoidPtrTy = PointerType::getUnqual(M.getContext());
2301 auto *Int64Ty = Type::getInt64Ty(M.getContext());
2302 auto *RegisterFTy = FunctionType::get(VoidTy, false);
2303 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
2305 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2306 if (Options.NoRedZone)
2307 RegisterF->addFnAttr(Attribute::NoRedZone);
2308
2309 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
2310 auto *RuntimeRegisterF =
2313
2314 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", RegisterF));
2315 for (Value *Data : CompilerUsedVars)
2316 if (!isa<Function>(Data))
2317 // Check for addrspace cast when profiling GPU
2318 IRB.CreateCall(RuntimeRegisterF,
2319 IRB.CreatePointerBitCastOrAddrSpaceCast(Data, VoidPtrTy));
2320 for (Value *Data : UsedVars)
2321 if (Data != NamesVar && !isa<Function>(Data))
2322 IRB.CreateCall(RuntimeRegisterF,
2323 IRB.CreatePointerBitCastOrAddrSpaceCast(Data, VoidPtrTy));
2324
2325 if (NamesVar) {
2326 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
2327 auto *NamesRegisterTy =
2328 FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
2329 auto *NamesRegisterF =
2332 IRB.CreateCall(NamesRegisterF, {IRB.CreatePointerBitCastOrAddrSpaceCast(
2333 NamesVar, VoidPtrTy),
2334 IRB.getInt64(NamesSize)});
2335 }
2336
2337 IRB.CreateRetVoid();
2338}
2339
2340bool InstrLowerer::emitRuntimeHook() {
2341 // GPU profiling data is read directly by the host offload runtime. We do not
2342 // need the standard runtime hook.
2343 if (TT.isGPU())
2344 return false;
2345
2346 // We expect the linker to be invoked with -u<hook_var> flag for Linux
2347 // in which case there is no need to emit the external variable.
2348 if (TT.isOSLinux() || TT.isOSAIX())
2349 return false;
2350
2351 // If the module's provided its own runtime, we don't need to do anything.
2352 if (M.getGlobalVariable(getInstrProfRuntimeHookVarName()))
2353 return false;
2354
2355 // Declare an external variable that will pull in the runtime initialization.
2356 auto *Int32Ty = Type::getInt32Ty(M.getContext());
2357 auto *Var =
2358 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
2360 Var->setVisibility(GlobalValue::HiddenVisibility);
2361
2362 if (TT.isOSBinFormatELF() && !TT.isPS()) {
2363 // Mark the user variable as used so that it isn't stripped out.
2364 CompilerUsedVars.push_back(Var);
2365 } else {
2366 // Make a function that uses it.
2367 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
2370 User->addFnAttr(Attribute::NoInline);
2371 if (Options.NoRedZone)
2372 User->addFnAttr(Attribute::NoRedZone);
2373 User->setVisibility(GlobalValue::HiddenVisibility);
2374 if (TT.supportsCOMDAT())
2375 User->setComdat(M.getOrInsertComdat(User->getName()));
2376 // Explicitly mark this function as cold since it is never called.
2377 User->setEntryCount(0);
2378
2379 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", User));
2380 auto *Load = IRB.CreateLoad(Int32Ty, Var);
2381 IRB.CreateRet(Load);
2382
2383 // Mark the function as used so that it isn't stripped out.
2384 CompilerUsedVars.push_back(User);
2385 }
2386 return true;
2387}
2388
2389void InstrLowerer::emitUses() {
2390 // The metadata sections are parallel arrays. Optimizers (e.g.
2391 // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
2392 // we conservatively retain all unconditionally in the compiler.
2393 //
2394 // On ELF and Mach-O, the linker can guarantee the associated sections will be
2395 // retained or discarded as a unit, so llvm.compiler.used is sufficient.
2396 // Similarly on COFF, if prof data is not referenced by code we use one comdat
2397 // and ensure this GC property as well. Otherwise, we have to conservatively
2398 // make all of the sections retained by the linker.
2399 if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
2400 (TT.isOSBinFormatCOFF() && !DataReferencedByCode))
2401 appendToCompilerUsed(M, CompilerUsedVars);
2402 else
2403 appendToUsed(M, CompilerUsedVars);
2404
2405 // We do not add proper references from used metadata sections to NamesVar and
2406 // VNodesVar, so we have to be conservative and place them in llvm.used
2407 // regardless of the target,
2408 appendToUsed(M, UsedVars);
2409}
2410
2411void InstrLowerer::emitInitialization() {
2412 // Create ProfileFileName variable. Don't don't this for the
2413 // context-sensitive instrumentation lowering: This lowering is after
2414 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
2415 // have already create the variable before LTO/ThinLTO linking.
2416 if (!IsCS)
2417 createProfileFileNameVar(M, Options.InstrProfileOutput);
2418 Function *RegisterF = M.getFunction(getInstrProfRegFuncsName());
2419 if (!RegisterF)
2420 return;
2421
2422 // Create the initialization function.
2423 auto *VoidTy = Type::getVoidTy(M.getContext());
2424 auto *F = Function::Create(FunctionType::get(VoidTy, false),
2427 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2428 F->addFnAttr(Attribute::NoInline);
2429 if (Options.NoRedZone)
2430 F->addFnAttr(Attribute::NoRedZone);
2431
2432 // Add the basic block and the necessary calls.
2433 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", F));
2434 IRB.CreateCall(RegisterF, {});
2435 IRB.CreateRetVoid();
2436
2437 appendToGlobalCtors(M, F, 0);
2438}
2439
2440namespace llvm {
2441// Create the variable for profile sampling.
2444 IntegerType *SamplingVarTy;
2445 Constant *ValueZero;
2446 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
2447 if (getSampledInstrumentationConfig(Opts).UseShort) {
2448 SamplingVarTy = Type::getInt16Ty(M.getContext());
2449 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(16, 0));
2450 } else {
2451 SamplingVarTy = Type::getInt32Ty(M.getContext());
2452 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(32, 0));
2453 }
2454 auto SamplingVar = new GlobalVariable(
2455 M, SamplingVarTy, false, GlobalValue::WeakAnyLinkage, ValueZero, VarName);
2456 SamplingVar->setVisibility(GlobalValue::DefaultVisibility);
2457 SamplingVar->setThreadLocal(true);
2458 Triple TT(M.getTargetTriple());
2459 if (TT.supportsCOMDAT()) {
2460 SamplingVar->setLinkage(GlobalValue::ExternalLinkage);
2461 SamplingVar->setComdat(M.getOrInsertComdat(VarName));
2462 }
2463 appendToCompilerUsed(M, SamplingVar);
2464}
2465} // namespace llvm
2466
2467// For GPU targets: Allocate contiguous arrays for all profile data.
2468// This solves the linker reordering problem by using ONE symbol per section
2469// type, so there's nothing for the linker to reorder.
2470StructType *InstrLowerer::getProfileDataTy() {
2471 if (ProfileDataTy)
2472 return ProfileDataTy;
2473
2474 auto &Ctx = M.getContext();
2475 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
2476 auto *Int16Ty = Type::getInt16Ty(Ctx);
2477 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
2478 Type *DataTypes[] = {
2479#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
2481 };
2482 ProfileDataTy = StructType::get(Ctx, ArrayRef(DataTypes));
2483 return ProfileDataTy;
2484}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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
DXIL Finalize Linkage
@ Default
Hexagon Hardware Loops
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.
#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 LVOptions Options
Definition LVOptions.cpp:25
static bool isAtomic(MachineBasicBlock::iterator I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Memory SSA
Definition MemorySSA.cpp:69
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
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:
Definition Annotations.h:67
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.
@ Add
*p = old + v
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
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.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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.
Definition Comdat.h:40
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
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...
Definition Constants.h:168
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.
Definition Constant.h:44
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.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
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)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:794
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
Definition Function.h:167
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
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...
Definition Globals.cpp:692
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
bool hasComdat() const
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
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...
Definition Globals.cpp:408
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.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
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.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
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.
Definition Globals.cpp:640
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
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.
Definition IRBuilder.h:2139
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2238
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1528
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:455
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2092
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:173
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2386
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:465
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1507
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1566
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition IRBuilder.h:2046
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2763
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2561
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2097
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
AtomicRMWInst * CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, bool Elementwise=false)
Definition IRBuilder.h:1981
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
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
This represents the llvm.instrprof.mcdc.tvbitmap.update intrinsic.
ConstantInt * getBitmapIndex() const
This represents the llvm.instrprof.timestamp intrinsic.
This represents the llvm.instrprof.value.profile intrinsic.
ConstantInt * getIndex() 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.
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition SSAUpdater.h:149
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.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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.
Definition Type.cpp:887
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
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.
Definition Type.cpp:467
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.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:298
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:824
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
#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.
Definition ISDOpcodes.h:83
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.
constexpr MCPhysReg SP
@ 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.
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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.
Definition InstrProf.h:131
LLVM_ABI bool isProfileCorrelationEnabled(const cl::LibraryOptionsContext &LibraryOptions)
Return true if -profile-correlate is set.
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
Definition InstrProf.h:101
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition InstrProf.h:206
UniformCounterPtr
Definition InstrProf.h:82
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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.
Definition InstrProf.h:143
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...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
StringRef getInstrProfVTableNamesVarName()
Definition InstrProf.h:159
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition InstrProf.h:137
RelativeUniformCounterPtr ValuesPtrExpr Int16ArrayTy
Definition InstrProf.h:95
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition InstrProf.h:172
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
Definition InstrProf.h:143
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)
Definition Casting.h:753
FuncHash
Definition InstrProf.h:78
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition InstrProf.h:201
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition InstrProf.h:146
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
StringRef getInstrProfCounterBiasVarName()
Definition InstrProf.h:216
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition InstrProf.h:212
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition InstrProf.h:181
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
InstrProfSectKind
Definition InstrProf.h:91
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.
Definition InstrProf.h:140
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
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)
Definition Error.cpp:163
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
Definition InstrProf.h:220
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.
Definition InstrProf.h:118
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...
Definition Casting.h:547
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.
Definition InstrProf.h:193
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
@ Add
Sum of integers.
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
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
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()
Definition InstrProf.h:155
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)
Definition CFG.cpp:424
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition InstrProf.h:112
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition InstrProf.h:187
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...
Definition InstrProf.h:153
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:
Definition InstrProf.h:149
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.
Definition CodeGen.h:371
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition InstrProf.h:134
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.