LLVM 19.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
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
25#include "llvm/IR/Attributes.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/Constant.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/DIBuilder.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalValue.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/Instruction.h"
41#include "llvm/IR/MDBuilder.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
45#include "llvm/Pass.h"
50#include "llvm/Support/Error.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <string>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "instrprof"
66
67namespace llvm {
68// Command line option to enable vtable value profiling. Defined in
69// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
71// TODO: Remove -debug-info-correlate in next LLVM release, in favor of
72// -profile-correlate=debug-info.
74 "debug-info-correlate",
75 cl::desc("Use debug info to correlate profiles. (Deprecated, use "
76 "-profile-correlate=debug-info)"),
77 cl::init(false));
78
80 "profile-correlate",
81 cl::desc("Use debug info or binary file to correlate profiles."),
84 "No profile correlation"),
86 "Use debug info to correlate"),
88 "Use binary to correlate")));
89} // namespace llvm
90
91namespace {
92
93cl::opt<bool> DoHashBasedCounterSplit(
94 "hash-based-counter-split",
95 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
96 cl::init(true));
97
99 RuntimeCounterRelocation("runtime-counter-relocation",
100 cl::desc("Enable relocating counters at runtime."),
101 cl::init(false));
102
103cl::opt<bool> ValueProfileStaticAlloc(
104 "vp-static-alloc",
105 cl::desc("Do static counter allocation for value profiler"),
106 cl::init(true));
107
108cl::opt<double> NumCountersPerValueSite(
109 "vp-counters-per-site",
110 cl::desc("The average number of profile counters allocated "
111 "per value profiling site."),
112 // This is set to a very small value because in real programs, only
113 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
114 // For those sites with non-zero profile, the average number of targets
115 // is usually smaller than 2.
116 cl::init(1.0));
117
118cl::opt<bool> AtomicCounterUpdateAll(
119 "instrprof-atomic-counter-update-all",
120 cl::desc("Make all profile counter updates atomic (for testing only)"),
121 cl::init(false));
122
123cl::opt<bool> AtomicCounterUpdatePromoted(
124 "atomic-counter-update-promoted",
125 cl::desc("Do counter update using atomic fetch add "
126 " for promoted counters only"),
127 cl::init(false));
128
129cl::opt<bool> AtomicFirstCounter(
130 "atomic-first-counter",
131 cl::desc("Use atomic fetch add for first counter in a function (usually "
132 "the entry counter)"),
133 cl::init(false));
134
135// If the option is not specified, the default behavior about whether
136// counter promotion is done depends on how instrumentaiton lowering
137// pipeline is setup, i.e., the default value of true of this option
138// does not mean the promotion will be done by default. Explicitly
139// setting this option can override the default behavior.
140cl::opt<bool> DoCounterPromotion("do-counter-promotion",
141 cl::desc("Do counter register promotion"),
142 cl::init(false));
143cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
144 "max-counter-promotions-per-loop", cl::init(20),
145 cl::desc("Max number counter promotions per loop to avoid"
146 " increasing register pressure too much"));
147
148// A debug option
150 MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
151 cl::desc("Max number of allowed counter promotions"));
152
153cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
154 "speculative-counter-promotion-max-exiting", cl::init(3),
155 cl::desc("The max number of exiting blocks of a loop to allow "
156 " speculative counter promotion"));
157
158cl::opt<bool> SpeculativeCounterPromotionToLoop(
159 "speculative-counter-promotion-to-loop",
160 cl::desc("When the option is false, if the target block is in a loop, "
161 "the promotion will be disallowed unless the promoted counter "
162 " update can be further/iteratively promoted into an acyclic "
163 " region."));
164
165cl::opt<bool> IterativeCounterPromotion(
166 "iterative-counter-promotion", cl::init(true),
167 cl::desc("Allow counter promotion across the whole loop nest."));
168
169cl::opt<bool> SkipRetExitBlock(
170 "skip-ret-exit-block", cl::init(true),
171 cl::desc("Suppress counter promotion if exit blocks contain ret."));
172
173using LoadStorePair = std::pair<Instruction *, Instruction *>;
174
175static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
176 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
177 if (!MD)
178 return 0;
179
180 // If the flag is a ConstantAsMetadata, it should be an integer representable
181 // in 64-bits.
182 return cast<ConstantInt>(MD->getValue())->getZExtValue();
183}
184
185static bool enablesValueProfiling(const Module &M) {
186 return isIRPGOFlagSet(&M) ||
187 getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
188}
189
190// Conservatively returns true if value profiling is enabled.
191static bool profDataReferencedByCode(const Module &M) {
192 return enablesValueProfiling(M);
193}
194
195class InstrLowerer final {
196public:
197 InstrLowerer(Module &M, const InstrProfOptions &Options,
198 std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
199 bool IsCS)
200 : M(M), Options(Options), TT(Triple(M.getTargetTriple())), IsCS(IsCS),
201 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
202
203 bool lower();
204
205private:
206 Module &M;
208 const Triple TT;
209 // Is this lowering for the context-sensitive instrumentation.
210 const bool IsCS;
211
212 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
213
214 const bool DataReferencedByCode;
215
216 struct PerFunctionProfileData {
217 uint32_t NumValueSites[IPVK_Last + 1] = {};
218 GlobalVariable *RegionCounters = nullptr;
219 GlobalVariable *DataVar = nullptr;
220 GlobalVariable *RegionBitmaps = nullptr;
221 uint32_t NumBitmapBytes = 0;
222
223 PerFunctionProfileData() = default;
224 };
226 // Key is virtual table variable, value is 'VTableProfData' in the form of
227 // GlobalVariable.
229 /// If runtime relocation is enabled, this maps functions to the load
230 /// instruction that produces the profile relocation bias.
231 DenseMap<const Function *, LoadInst *> FunctionToProfileBiasMap;
232 std::vector<GlobalValue *> CompilerUsedVars;
233 std::vector<GlobalValue *> UsedVars;
234 std::vector<GlobalVariable *> ReferencedNames;
235 // The list of virtual table variables of which the VTableProfData is
236 // collected.
237 std::vector<GlobalVariable *> ReferencedVTables;
238 GlobalVariable *NamesVar = nullptr;
239 size_t NamesSize = 0;
240
241 /// The instance of [[alwaysinline]] rmw_or(ptr, i8).
242 /// This is name-insensitive.
243 Function *RMWOrFunc = nullptr;
244
245 // vector of counter load/store pairs to be register promoted.
246 std::vector<LoadStorePair> PromotionCandidates;
247
248 int64_t TotalCountersPromoted = 0;
249
250 /// Lower instrumentation intrinsics in the function. Returns true if there
251 /// any lowering.
253
254 /// Register-promote counter loads and stores in loops.
255 void promoteCounterLoadStores(Function *F);
256
257 /// Returns true if relocating counters at runtime is enabled.
258 bool isRuntimeCounterRelocationEnabled() const;
259
260 /// Returns true if profile counter update register promotion is enabled.
261 bool isCounterPromotionEnabled() const;
262
263 /// Count the number of instrumented value sites for the function.
264 void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
265
266 /// Replace instrprof.value.profile with a call to runtime library.
267 void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
268
269 /// Replace instrprof.cover with a store instruction to the coverage byte.
270 void lowerCover(InstrProfCoverInst *Inc);
271
272 /// Replace instrprof.timestamp with a call to
273 /// INSTR_PROF_PROFILE_SET_TIMESTAMP.
274 void lowerTimestamp(InstrProfTimestampInst *TimestampInstruction);
275
276 /// Replace instrprof.increment with an increment of the appropriate value.
277 void lowerIncrement(InstrProfIncrementInst *Inc);
278
279 /// Force emitting of name vars for unused functions.
280 void lowerCoverageData(GlobalVariable *CoverageNamesVar);
281
282 /// Replace instrprof.mcdc.tvbitmask.update with a shift and or instruction
283 /// using the index represented by the a temp value into a bitmap.
284 void lowerMCDCTestVectorBitmapUpdate(InstrProfMCDCTVBitmapUpdate *Ins);
285
286 /// Get the Bias value for data to access mmap-ed area.
287 /// Create it if it hasn't been seen.
288 GlobalVariable *getOrCreateBiasVar(StringRef VarName);
289
290 /// Compute the address of the counter value that this profiling instruction
291 /// acts on.
292 Value *getCounterAddress(InstrProfCntrInstBase *I);
293
294 /// Get the region counters for an increment, creating them if necessary.
295 ///
296 /// If the counter array doesn't yet exist, the profile data variables
297 /// referring to them will also be created.
298 GlobalVariable *getOrCreateRegionCounters(InstrProfCntrInstBase *Inc);
299
300 /// Create the region counters.
301 GlobalVariable *createRegionCounters(InstrProfCntrInstBase *Inc,
304
305 /// Create [[alwaysinline]] rmw_or(ptr, i8).
306 /// This doesn't update `RMWOrFunc`.
307 Function *createRMWOrFunc();
308
309 /// Get the call to `rmw_or`.
310 /// Create the instance if it is unknown.
311 CallInst *getRMWOrCall(Value *Addr, Value *Val);
312
313 /// Compute the address of the test vector bitmap that this profiling
314 /// instruction acts on.
315 Value *getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I);
316
317 /// Get the region bitmaps for an increment, creating them if necessary.
318 ///
319 /// If the bitmap array doesn't yet exist, the profile data variables
320 /// referring to them will also be created.
321 GlobalVariable *getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc);
322
323 /// Create the MC/DC bitmap as a byte-aligned array of bytes associated with
324 /// an MC/DC Decision region. The number of bytes required is indicated by
325 /// the intrinsic used (type InstrProfMCDCBitmapInstBase). This is called
326 /// as part of setupProfileSection() and is conceptually very similar to
327 /// what is done for profile data counters in createRegionCounters().
328 GlobalVariable *createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
331
332 /// Set Comdat property of GV, if required.
333 void maybeSetComdat(GlobalVariable *GV, GlobalObject *GO, StringRef VarName);
334
335 /// Setup the sections into which counters and bitmaps are allocated.
336 GlobalVariable *setupProfileSection(InstrProfInstBase *Inc,
337 InstrProfSectKind IPSK);
338
339 /// Create INSTR_PROF_DATA variable for counters and bitmaps.
340 void createDataVariable(InstrProfCntrInstBase *Inc);
341
342 /// Get the counters for virtual table values, creating them if necessary.
343 void getOrCreateVTableProfData(GlobalVariable *GV);
344
345 /// Emit the section with compressed function names.
346 void emitNameData();
347
348 /// Emit the section with compressed vtable names.
349 void emitVTableNames();
350
351 /// Emit value nodes section for value profiling.
352 void emitVNodes();
353
354 /// Emit runtime registration functions for each profile data variable.
355 void emitRegistration();
356
357 /// Emit the necessary plumbing to pull in the runtime initialization.
358 /// Returns true if a change was made.
359 bool emitRuntimeHook();
360
361 /// Add uses of our data variables and runtime hook.
362 void emitUses();
363
364 /// Create a static initializer for our data, on platforms that need it,
365 /// and for any profile output file that was specified.
366 void emitInitialization();
367};
368
369///
370/// A helper class to promote one counter RMW operation in the loop
371/// into register update.
372///
373/// RWM update for the counter will be sinked out of the loop after
374/// the transformation.
375///
376class PGOCounterPromoterHelper : public LoadAndStorePromoter {
377public:
378 PGOCounterPromoterHelper(
380 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
381 ArrayRef<Instruction *> InsertPts,
383 LoopInfo &LI)
384 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
385 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
386 assert(isa<LoadInst>(L));
387 assert(isa<StoreInst>(S));
388 SSA.AddAvailableValue(PH, Init);
389 }
390
391 void doExtraRewritesBeforeFinalDeletion() override {
392 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
393 BasicBlock *ExitBlock = ExitBlocks[i];
394 Instruction *InsertPos = InsertPts[i];
395 // Get LiveIn value into the ExitBlock. If there are multiple
396 // predecessors, the value is defined by a PHI node in this
397 // block.
398 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
399 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
400 Type *Ty = LiveInValue->getType();
401 IRBuilder<> Builder(InsertPos);
402 if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
403 // If isRuntimeCounterRelocationEnabled() is true then the address of
404 // the store instruction is computed with two instructions in
405 // InstrProfiling::getCounterAddress(). We need to copy those
406 // instructions to this block to compute Addr correctly.
407 // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
408 // %Addr = inttoptr i64 %BiasAdd to i64*
409 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
410 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
411 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
412 Addr = Builder.CreateIntToPtr(BiasInst,
413 PointerType::getUnqual(Ty->getContext()));
414 }
415 if (AtomicCounterUpdatePromoted)
416 // automic update currently can only be promoted across the current
417 // loop, not the whole loop nest.
418 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
419 MaybeAlign(),
420 AtomicOrdering::SequentiallyConsistent);
421 else {
422 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
423 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
424 auto *NewStore = Builder.CreateStore(NewVal, Addr);
425
426 // Now update the parent loop's candidate list:
427 if (IterativeCounterPromotion) {
428 auto *TargetLoop = LI.getLoopFor(ExitBlock);
429 if (TargetLoop)
430 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
431 }
432 }
433 }
434 }
435
436private:
438 ArrayRef<BasicBlock *> ExitBlocks;
439 ArrayRef<Instruction *> InsertPts;
441 LoopInfo &LI;
442};
443
444/// A helper class to do register promotion for all profile counter
445/// updates in a loop.
446///
447class PGOCounterPromoter {
448public:
449 PGOCounterPromoter(
451 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
452 : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
453
454 // Skip collection of ExitBlocks and InsertPts for loops that will not be
455 // able to have counters promoted.
456 SmallVector<BasicBlock *, 8> LoopExitBlocks;
458
459 L.getExitBlocks(LoopExitBlocks);
460 if (!isPromotionPossible(&L, LoopExitBlocks))
461 return;
462
463 for (BasicBlock *ExitBlock : LoopExitBlocks) {
464 if (BlockSet.insert(ExitBlock).second &&
465 llvm::none_of(predecessors(ExitBlock), [&](const BasicBlock *Pred) {
466 return llvm::isPresplitCoroSuspendExitEdge(*Pred, *ExitBlock);
467 })) {
468 ExitBlocks.push_back(ExitBlock);
469 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
470 }
471 }
472 }
473
474 bool run(int64_t *NumPromoted) {
475 // Skip 'infinite' loops:
476 if (ExitBlocks.size() == 0)
477 return false;
478
479 // Skip if any of the ExitBlocks contains a ret instruction.
480 // This is to prevent dumping of incomplete profile -- if the
481 // the loop is a long running loop and dump is called in the middle
482 // of the loop, the result profile is incomplete.
483 // FIXME: add other heuristics to detect long running loops.
484 if (SkipRetExitBlock) {
485 for (auto *BB : ExitBlocks)
486 if (isa<ReturnInst>(BB->getTerminator()))
487 return false;
488 }
489
490 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
491 if (MaxProm == 0)
492 return false;
493
494 unsigned Promoted = 0;
495 for (auto &Cand : LoopToCandidates[&L]) {
496
498 SSAUpdater SSA(&NewPHIs);
499 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
500
501 // If BFI is set, we will use it to guide the promotions.
502 if (BFI) {
503 auto *BB = Cand.first->getParent();
504 auto InstrCount = BFI->getBlockProfileCount(BB);
505 if (!InstrCount)
506 continue;
507 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
508 // If the average loop trip count is not greater than 1.5, we skip
509 // promotion.
510 if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
511 continue;
512 }
513
514 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
515 L.getLoopPreheader(), ExitBlocks,
516 InsertPts, LoopToCandidates, LI);
517 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
518 Promoted++;
519 if (Promoted >= MaxProm)
520 break;
521
522 (*NumPromoted)++;
523 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
524 break;
525 }
526
527 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
528 << L.getLoopDepth() << ")\n");
529 return Promoted != 0;
530 }
531
532private:
533 bool allowSpeculativeCounterPromotion(Loop *LP) {
534 SmallVector<BasicBlock *, 8> ExitingBlocks;
535 L.getExitingBlocks(ExitingBlocks);
536 // Not considierered speculative.
537 if (ExitingBlocks.size() == 1)
538 return true;
539 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
540 return false;
541 return true;
542 }
543
544 // Check whether the loop satisfies the basic conditions needed to perform
545 // Counter Promotions.
546 bool
547 isPromotionPossible(Loop *LP,
548 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
549 // We can't insert into a catchswitch.
550 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
551 return isa<CatchSwitchInst>(Exit->getTerminator());
552 }))
553 return false;
554
555 if (!LP->hasDedicatedExits())
556 return false;
557
558 BasicBlock *PH = LP->getLoopPreheader();
559 if (!PH)
560 return false;
561
562 return true;
563 }
564
565 // Returns the max number of Counter Promotions for LP.
566 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
567 SmallVector<BasicBlock *, 8> LoopExitBlocks;
568 LP->getExitBlocks(LoopExitBlocks);
569 if (!isPromotionPossible(LP, LoopExitBlocks))
570 return 0;
571
572 SmallVector<BasicBlock *, 8> ExitingBlocks;
573 LP->getExitingBlocks(ExitingBlocks);
574
575 // If BFI is set, we do more aggressive promotions based on BFI.
576 if (BFI)
577 return (unsigned)-1;
578
579 // Not considierered speculative.
580 if (ExitingBlocks.size() == 1)
581 return MaxNumOfPromotionsPerLoop;
582
583 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
584 return 0;
585
586 // Whether the target block is in a loop does not matter:
587 if (SpeculativeCounterPromotionToLoop)
588 return MaxNumOfPromotionsPerLoop;
589
590 // Now check the target block:
591 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
592 for (auto *TargetBlock : LoopExitBlocks) {
593 auto *TargetLoop = LI.getLoopFor(TargetBlock);
594 if (!TargetLoop)
595 continue;
596 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
597 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
598 MaxProm =
599 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
600 PendingCandsInTarget);
601 }
602 return MaxProm;
603 }
604
608 Loop &L;
609 LoopInfo &LI;
611};
612
613enum class ValueProfilingCallType {
614 // Individual values are tracked. Currently used for indiret call target
615 // profiling.
616 Default,
617
618 // MemOp: the memop size value profiling.
619 MemOp
620};
621
622} // end anonymous namespace
623
628 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
630 };
631 InstrLowerer Lowerer(M, Options, GetTLI, IsCS);
632 if (!Lowerer.lower())
633 return PreservedAnalyses::all();
634
636}
637
638bool InstrLowerer::lowerIntrinsics(Function *F) {
639 bool MadeChange = false;
640 PromotionCandidates.clear();
641 for (BasicBlock &BB : *F) {
642 for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
643 if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
644 lowerIncrement(IPIS);
645 MadeChange = true;
646 } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
647 lowerIncrement(IPI);
648 MadeChange = true;
649 } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(&Instr)) {
650 lowerTimestamp(IPC);
651 MadeChange = true;
652 } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
653 lowerCover(IPC);
654 MadeChange = true;
655 } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
656 lowerValueProfileInst(IPVP);
657 MadeChange = true;
658 } else if (auto *IPMP = dyn_cast<InstrProfMCDCBitmapParameters>(&Instr)) {
659 IPMP->eraseFromParent();
660 MadeChange = true;
661 } else if (auto *IPBU = dyn_cast<InstrProfMCDCTVBitmapUpdate>(&Instr)) {
662 lowerMCDCTestVectorBitmapUpdate(IPBU);
663 MadeChange = true;
664 }
665 }
666 }
667
668 if (!MadeChange)
669 return false;
670
671 promoteCounterLoadStores(F);
672 return true;
673}
674
675bool InstrLowerer::isRuntimeCounterRelocationEnabled() const {
676 // Mach-O don't support weak external references.
677 if (TT.isOSBinFormatMachO())
678 return false;
679
680 if (RuntimeCounterRelocation.getNumOccurrences() > 0)
681 return RuntimeCounterRelocation;
682
683 // Fuchsia uses runtime counter relocation by default.
684 return TT.isOSFuchsia();
685}
686
687bool InstrLowerer::isCounterPromotionEnabled() const {
688 if (DoCounterPromotion.getNumOccurrences() > 0)
689 return DoCounterPromotion;
690
691 return Options.DoCounterPromotion;
692}
693
694void InstrLowerer::promoteCounterLoadStores(Function *F) {
695 if (!isCounterPromotionEnabled())
696 return;
697
698 DominatorTree DT(*F);
699 LoopInfo LI(DT);
700 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
701
702 std::unique_ptr<BlockFrequencyInfo> BFI;
703 if (Options.UseBFIInPromotion) {
704 std::unique_ptr<BranchProbabilityInfo> BPI;
705 BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
706 BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
707 }
708
709 for (const auto &LoadStore : PromotionCandidates) {
710 auto *CounterLoad = LoadStore.first;
711 auto *CounterStore = LoadStore.second;
712 BasicBlock *BB = CounterLoad->getParent();
713 Loop *ParentLoop = LI.getLoopFor(BB);
714 if (!ParentLoop)
715 continue;
716 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
717 }
718
720
721 // Do a post-order traversal of the loops so that counter updates can be
722 // iteratively hoisted outside the loop nest.
723 for (auto *Loop : llvm::reverse(Loops)) {
724 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
725 Promoter.run(&TotalCountersPromoted);
726 }
727}
728
730 // On Fuchsia, we only need runtime hook if any counters are present.
731 if (TT.isOSFuchsia())
732 return false;
733
734 return true;
735}
736
737/// Check if the module contains uses of any profiling intrinsics.
739 auto containsIntrinsic = [&](int ID) {
740 if (auto *F = M.getFunction(Intrinsic::getName(ID)))
741 return !F->use_empty();
742 return false;
743 };
744 return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
745 containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
746 containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
747 containsIntrinsic(llvm::Intrinsic::instrprof_timestamp) ||
748 containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
749}
750
751bool InstrLowerer::lower() {
752 bool MadeChange = false;
753 bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
754 if (NeedsRuntimeHook)
755 MadeChange = emitRuntimeHook();
756
757 bool ContainsProfiling = containsProfilingIntrinsics(M);
758 GlobalVariable *CoverageNamesVar =
759 M.getNamedGlobal(getCoverageUnusedNamesVarName());
760 // Improve compile time by avoiding linear scans when there is no work.
761 if (!ContainsProfiling && !CoverageNamesVar)
762 return MadeChange;
763
764 // We did not know how many value sites there would be inside
765 // the instrumented function. This is counting the number of instrumented
766 // target value sites to enter it as field in the profile data variable.
767 for (Function &F : M) {
768 InstrProfCntrInstBase *FirstProfInst = nullptr;
769 for (BasicBlock &BB : F) {
770 for (auto I = BB.begin(), E = BB.end(); I != E; I++) {
771 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
772 computeNumValueSiteCounts(Ind);
773 else {
774 if (FirstProfInst == nullptr &&
775 (isa<InstrProfIncrementInst>(I) || isa<InstrProfCoverInst>(I)))
776 FirstProfInst = dyn_cast<InstrProfCntrInstBase>(I);
777 // If the MCDCBitmapParameters intrinsic seen, create the bitmaps.
778 if (const auto &Params = dyn_cast<InstrProfMCDCBitmapParameters>(I))
779 static_cast<void>(getOrCreateRegionBitmaps(Params));
780 }
781 }
782 }
783
784 // Use a profile intrinsic to create the region counters and data variable.
785 // Also create the data variable based on the MCDCParams.
786 if (FirstProfInst != nullptr) {
787 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
788 }
789 }
790
792 for (GlobalVariable &GV : M.globals())
793 // Global variables with type metadata are virtual table variables.
794 if (GV.hasMetadata(LLVMContext::MD_type))
795 getOrCreateVTableProfData(&GV);
796
797 for (Function &F : M)
798 MadeChange |= lowerIntrinsics(&F);
799
800 if (CoverageNamesVar) {
801 lowerCoverageData(CoverageNamesVar);
802 MadeChange = true;
803 }
804
805 if (!MadeChange)
806 return false;
807
808 emitVNodes();
809 emitNameData();
810 emitVTableNames();
811
812 // Emit runtime hook for the cases where the target does not unconditionally
813 // require pulling in profile runtime, and coverage is enabled on code that is
814 // not eliminated by the front-end, e.g. unused functions with internal
815 // linkage.
816 if (!NeedsRuntimeHook && ContainsProfiling)
817 emitRuntimeHook();
818
819 emitRegistration();
820 emitUses();
821 emitInitialization();
822 return true;
823}
824
826 Module &M, const TargetLibraryInfo &TLI,
827 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
828 LLVMContext &Ctx = M.getContext();
829 auto *ReturnTy = Type::getVoidTy(M.getContext());
830
831 AttributeList AL;
832 if (auto AK = TLI.getExtAttrForI32Param(false))
833 AL = AL.addParamAttribute(M.getContext(), 2, AK);
834
835 assert((CallType == ValueProfilingCallType::Default ||
836 CallType == ValueProfilingCallType::MemOp) &&
837 "Must be Default or MemOp");
838 Type *ParamTypes[] = {
839#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
841 };
842 auto *ValueProfilingCallTy =
843 FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
844 StringRef FuncName = CallType == ValueProfilingCallType::Default
847 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
848}
849
850void InstrLowerer::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
851 GlobalVariable *Name = Ind->getName();
854 auto &PD = ProfileDataMap[Name];
855 PD.NumValueSites[ValueKind] =
856 std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
857}
858
859void InstrLowerer::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
860 // TODO: Value profiling heavily depends on the data section which is omitted
861 // in lightweight mode. We need to move the value profile pointer to the
862 // Counter struct to get this working.
863 assert(
865 "Value profiling is not yet supported with lightweight instrumentation");
866 GlobalVariable *Name = Ind->getName();
867 auto It = ProfileDataMap.find(Name);
868 assert(It != ProfileDataMap.end() && It->second.DataVar &&
869 "value profiling detected in function with no counter incerement");
870
871 GlobalVariable *DataVar = It->second.DataVar;
874 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
875 Index += It->second.NumValueSites[Kind];
876
877 IRBuilder<> Builder(Ind);
878 bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
879 llvm::InstrProfValueKind::IPVK_MemOPSize);
880 CallInst *Call = nullptr;
881 auto *TLI = &GetTLI(*Ind->getFunction());
882
883 // To support value profiling calls within Windows exception handlers, funclet
884 // information contained within operand bundles needs to be copied over to
885 // the library call. This is required for the IR to be processed by the
886 // WinEHPrepare pass.
888 Ind->getOperandBundlesAsDefs(OpBundles);
889 if (!IsMemOpSize) {
890 Value *Args[3] = {Ind->getTargetValue(), DataVar, Builder.getInt32(Index)};
891 Call = Builder.CreateCall(getOrInsertValueProfilingCall(M, *TLI), Args,
892 OpBundles);
893 } else {
894 Value *Args[3] = {Ind->getTargetValue(), DataVar, Builder.getInt32(Index)};
895 Call = Builder.CreateCall(
896 getOrInsertValueProfilingCall(M, *TLI, ValueProfilingCallType::MemOp),
897 Args, OpBundles);
898 }
899 if (auto AK = TLI->getExtAttrForI32Param(false))
900 Call->addParamAttr(2, AK);
901 Ind->replaceAllUsesWith(Call);
902 Ind->eraseFromParent();
903}
904
905GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
906 GlobalVariable *Bias = M.getGlobalVariable(VarName);
907 if (Bias)
908 return Bias;
909
910 Type *Int64Ty = Type::getInt64Ty(M.getContext());
911
912 // Compiler must define this variable when runtime counter relocation
913 // is being used. Runtime has a weak external reference that is used
914 // to check whether that's the case or not.
915 Bias = new GlobalVariable(M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
916 Constant::getNullValue(Int64Ty), VarName);
918 // A definition that's weak (linkonce_odr) without being in a COMDAT
919 // section wouldn't lead to link errors, but it would lead to a dead
920 // data word from every TU but one. Putting it in COMDAT ensures there
921 // will be exactly one data slot in the link.
922 if (TT.supportsCOMDAT())
923 Bias->setComdat(M.getOrInsertComdat(VarName));
924
925 return Bias;
926}
927
928Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
929 auto *Counters = getOrCreateRegionCounters(I);
930 IRBuilder<> Builder(I);
931
932 if (isa<InstrProfTimestampInst>(I))
933 Counters->setAlignment(Align(8));
934
935 auto *Addr = Builder.CreateConstInBoundsGEP2_32(
936 Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
937
938 if (!isRuntimeCounterRelocationEnabled())
939 return Addr;
940
941 Type *Int64Ty = Type::getInt64Ty(M.getContext());
942 Function *Fn = I->getParent()->getParent();
943 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
944 if (!BiasLI) {
945 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
946 auto *Bias = getOrCreateBiasVar(getInstrProfCounterBiasVarName());
947 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profc_bias");
948 }
949 auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
950 return Builder.CreateIntToPtr(Add, Addr->getType());
951}
952
953/// Create `void [[alwaysinline]] rmw_or(uint8_t *ArgAddr, uint8_t ArgVal)`
954/// "Basic" sequence is `*ArgAddr |= ArgVal`
955Function *InstrLowerer::createRMWOrFunc() {
956 auto &Ctx = M.getContext();
957 auto *Int8Ty = Type::getInt8Ty(Ctx);
960 {PointerType::getUnqual(Ctx), Int8Ty}, false),
962 Fn->addFnAttr(Attribute::AlwaysInline);
963 auto *ArgAddr = Fn->getArg(0);
964 auto *ArgVal = Fn->getArg(1);
965 IRBuilder<> Builder(BasicBlock::Create(Ctx, "", Fn));
966
967 // Load profile bitmap byte.
968 // %mcdc.bits = load i8, ptr %4, align 1
969 auto *Bitmap = Builder.CreateLoad(Int8Ty, ArgAddr, "mcdc.bits");
970
971 if (Options.Atomic || AtomicCounterUpdateAll) {
972 // If ((Bitmap & Val) != Val), then execute atomic (Bitmap |= Val).
973 // Note, just-loaded Bitmap might not be up-to-date. Use it just for
974 // early testing.
975 auto *Masked = Builder.CreateAnd(Bitmap, ArgVal);
976 auto *ShouldStore = Builder.CreateICmpNE(Masked, ArgVal);
977 auto *ThenTerm = BasicBlock::Create(Ctx, "", Fn);
978 auto *ElseTerm = BasicBlock::Create(Ctx, "", Fn);
979 // Assume updating will be rare.
980 auto *Unlikely = MDBuilder(Ctx).createUnlikelyBranchWeights();
981 Builder.CreateCondBr(ShouldStore, ThenTerm, ElseTerm, Unlikely);
982
983 IRBuilder<> ThenBuilder(ThenTerm);
984 ThenBuilder.CreateAtomicRMW(AtomicRMWInst::Or, ArgAddr, ArgVal,
986 ThenBuilder.CreateRetVoid();
987
988 IRBuilder<> ElseBuilder(ElseTerm);
989 ElseBuilder.CreateRetVoid();
990
991 return Fn;
992 }
993
994 // Perform logical OR of profile bitmap byte and shifted bit offset.
995 // %8 = or i8 %mcdc.bits, %7
996 auto *Result = Builder.CreateOr(Bitmap, ArgVal);
997
998 // Store the updated profile bitmap byte.
999 // store i8 %8, ptr %3, align 1
1000 Builder.CreateStore(Result, ArgAddr);
1001
1002 // Terminator
1003 Builder.CreateRetVoid();
1004
1005 return Fn;
1006}
1007
1008CallInst *InstrLowerer::getRMWOrCall(Value *Addr, Value *Val) {
1009 if (!RMWOrFunc)
1010 RMWOrFunc = createRMWOrFunc();
1011
1012 return CallInst::Create(RMWOrFunc, {Addr, Val});
1013}
1014
1015Value *InstrLowerer::getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I) {
1016 auto *Bitmaps = getOrCreateRegionBitmaps(I);
1017 IRBuilder<> Builder(I);
1018
1019 if (isRuntimeCounterRelocationEnabled()) {
1020 LLVMContext &Ctx = M.getContext();
1022 M.getName().data(),
1023 Twine("Runtime counter relocation is presently not supported for MC/DC "
1024 "bitmaps."),
1025 DS_Warning));
1026 }
1027
1028 return Bitmaps;
1029}
1030
1031void InstrLowerer::lowerCover(InstrProfCoverInst *CoverInstruction) {
1032 auto *Addr = getCounterAddress(CoverInstruction);
1033 IRBuilder<> Builder(CoverInstruction);
1034 // We store zero to represent that this block is covered.
1035 Builder.CreateStore(Builder.getInt8(0), Addr);
1036 CoverInstruction->eraseFromParent();
1037}
1038
1039void InstrLowerer::lowerTimestamp(
1040 InstrProfTimestampInst *TimestampInstruction) {
1041 assert(TimestampInstruction->getIndex()->isZeroValue() &&
1042 "timestamp probes are always the first probe for a function");
1043 auto &Ctx = M.getContext();
1044 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1045 IRBuilder<> Builder(TimestampInstruction);
1046 auto *CalleeTy =
1047 FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
1048 auto Callee = M.getOrInsertFunction(
1049 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SET_TIMESTAMP), CalleeTy);
1050 Builder.CreateCall(Callee, {TimestampAddr});
1051 TimestampInstruction->eraseFromParent();
1052}
1053
1054void InstrLowerer::lowerIncrement(InstrProfIncrementInst *Inc) {
1055 auto *Addr = getCounterAddress(Inc);
1056
1057 IRBuilder<> Builder(Inc);
1058 if (Options.Atomic || AtomicCounterUpdateAll ||
1059 (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
1060 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
1062 } else {
1063 Value *IncStep = Inc->getStep();
1064 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
1065 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
1066 auto *Store = Builder.CreateStore(Count, Addr);
1067 if (isCounterPromotionEnabled())
1068 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
1069 }
1070 Inc->eraseFromParent();
1071}
1072
1073void InstrLowerer::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
1074 ConstantArray *Names =
1075 cast<ConstantArray>(CoverageNamesVar->getInitializer());
1076 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
1077 Constant *NC = Names->getOperand(I);
1078 Value *V = NC->stripPointerCasts();
1079 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
1080 GlobalVariable *Name = cast<GlobalVariable>(V);
1081
1082 Name->setLinkage(GlobalValue::PrivateLinkage);
1083 ReferencedNames.push_back(Name);
1084 if (isa<ConstantExpr>(NC))
1085 NC->dropAllReferences();
1086 }
1087 CoverageNamesVar->eraseFromParent();
1088}
1089
1090void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1092 IRBuilder<> Builder(Update);
1093 auto *Int8Ty = Type::getInt8Ty(M.getContext());
1094 auto *Int32Ty = Type::getInt32Ty(M.getContext());
1095 auto *MCDCCondBitmapAddr = Update->getMCDCCondBitmapAddr();
1096 auto *BitmapAddr = getBitmapAddress(Update);
1097
1098 // Load Temp Val + BitmapIdx.
1099 // %mcdc.temp = load i32, ptr %mcdc.addr, align 4
1100 auto *Temp = Builder.CreateAdd(
1101 Builder.CreateLoad(Int32Ty, MCDCCondBitmapAddr, "mcdc.temp"),
1102 Update->getBitmapIndex());
1103
1104 // Calculate byte offset using div8.
1105 // %1 = lshr i32 %mcdc.temp, 3
1106 auto *BitmapByteOffset = Builder.CreateLShr(Temp, 0x3);
1107
1108 // Add byte offset to section base byte address.
1109 // %4 = getelementptr inbounds i8, ptr @__profbm_test, i32 %1
1110 auto *BitmapByteAddr =
1111 Builder.CreateInBoundsPtrAdd(BitmapAddr, BitmapByteOffset);
1112
1113 // Calculate bit offset into bitmap byte by using div8 remainder (AND ~8)
1114 // %5 = and i32 %mcdc.temp, 7
1115 // %6 = trunc i32 %5 to i8
1116 auto *BitToSet = Builder.CreateTrunc(Builder.CreateAnd(Temp, 0x7), Int8Ty);
1117
1118 // Shift bit offset left to form a bitmap.
1119 // %7 = shl i8 1, %6
1120 auto *ShiftedVal = Builder.CreateShl(Builder.getInt8(0x1), BitToSet);
1121
1122 Builder.Insert(getRMWOrCall(BitmapByteAddr, ShiftedVal));
1123 Update->eraseFromParent();
1124}
1125
1126/// Get the name of a profiling variable for a particular function.
1127static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
1128 bool &Renamed) {
1129 StringRef NamePrefix = getInstrProfNameVarPrefix();
1130 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
1131 Function *F = Inc->getParent()->getParent();
1132 Module *M = F->getParent();
1133 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
1135 Renamed = false;
1136 return (Prefix + Name).str();
1137 }
1138 Renamed = true;
1139 uint64_t FuncHash = Inc->getHash()->getZExtValue();
1140 SmallVector<char, 24> HashPostfix;
1141 if (Name.ends_with((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
1142 return (Prefix + Name).str();
1143 return (Prefix + Name + "." + Twine(FuncHash)).str();
1144}
1145
1147 // Only record function addresses if IR PGO is enabled or if clang value
1148 // profiling is enabled. Recording function addresses greatly increases object
1149 // file size, because it prevents the inliner from deleting functions that
1150 // have been inlined everywhere.
1151 if (!profDataReferencedByCode(*F->getParent()))
1152 return false;
1153
1154 // Check the linkage
1155 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
1156 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
1157 !HasAvailableExternallyLinkage)
1158 return true;
1159
1160 // A function marked 'alwaysinline' with available_externally linkage can't
1161 // have its address taken. Doing so would create an undefined external ref to
1162 // the function, which would fail to link.
1163 if (HasAvailableExternallyLinkage &&
1164 F->hasFnAttribute(Attribute::AlwaysInline))
1165 return false;
1166
1167 // Prohibit function address recording if the function is both internal and
1168 // COMDAT. This avoids the profile data variable referencing internal symbols
1169 // in COMDAT.
1170 if (F->hasLocalLinkage() && F->hasComdat())
1171 return false;
1172
1173 // Check uses of this function for other than direct calls or invokes to it.
1174 // Inline virtual functions have linkeOnceODR linkage. When a key method
1175 // exists, the vtable will only be emitted in the TU where the key method
1176 // is defined. In a TU where vtable is not available, the function won't
1177 // be 'addresstaken'. If its address is not recorded here, the profile data
1178 // with missing address may be picked by the linker leading to missing
1179 // indirect call target info.
1180 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
1181}
1182
1183static inline bool shouldUsePublicSymbol(Function *Fn) {
1184 // It isn't legal to make an alias of this function at all
1185 if (Fn->isDeclarationForLinker())
1186 return true;
1187
1188 // Symbols with local linkage can just use the symbol directly without
1189 // introducing relocations
1190 if (Fn->hasLocalLinkage())
1191 return true;
1192
1193 // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
1194 // unfavorable interaction between the new alias and the alias renaming done
1195 // in LowerTypeTests under ThinLTO. For comdat functions that would normally
1196 // be deduplicated, but the renaming scheme ends up preventing renaming, since
1197 // it creates unique names for each alias, resulting in duplicated symbols. In
1198 // the future, we should update the CFI related passes to migrate these
1199 // aliases to the same module as the jump-table they refer to will be defined.
1200 if (Fn->hasMetadata(LLVMContext::MD_type))
1201 return true;
1202
1203 // For comdat functions, an alias would need the same linkage as the original
1204 // function and hidden visibility. There is no point in adding an alias with
1205 // identical linkage an visibility to avoid introducing symbolic relocations.
1206 if (Fn->hasComdat() &&
1208 return true;
1209
1210 // its OK to use an alias
1211 return false;
1212}
1213
1215 auto *Int8PtrTy = PointerType::getUnqual(Fn->getContext());
1216 // Store a nullptr in __llvm_profd, if we shouldn't use a real address
1217 if (!shouldRecordFunctionAddr(Fn))
1218 return ConstantPointerNull::get(Int8PtrTy);
1219
1220 // If we can't use an alias, we must use the public symbol, even though this
1221 // may require a symbolic relocation.
1222 if (shouldUsePublicSymbol(Fn))
1223 return Fn;
1224
1225 // When possible use a private alias to avoid symbolic relocations.
1227 Fn->getName() + ".local", Fn);
1228
1229 // When the instrumented function is a COMDAT function, we cannot use a
1230 // private alias. If we did, we would create reference to a local label in
1231 // this function's section. If this version of the function isn't selected by
1232 // the linker, then the metadata would introduce a reference to a discarded
1233 // section. So, for COMDAT functions, we need to adjust the linkage of the
1234 // alias. Using hidden visibility avoids a dynamic relocation and an entry in
1235 // the dynamic symbol table.
1236 //
1237 // Note that this handles COMDAT functions with visibility other than Hidden,
1238 // since that case is covered in shouldUsePublicSymbol()
1239 if (Fn->hasComdat()) {
1240 GA->setLinkage(Fn->getLinkage());
1242 }
1243
1244 // appendToCompilerUsed(*Fn->getParent(), {GA});
1245
1246 return GA;
1247}
1248
1250 // compiler-rt uses linker support to get data/counters/name start/end for
1251 // ELF, COFF, Mach-O and XCOFF.
1252 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1253 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF())
1254 return false;
1255
1256 return true;
1257}
1258
1259void InstrLowerer::maybeSetComdat(GlobalVariable *GV, GlobalObject *GO,
1260 StringRef CounterGroupName) {
1261 // Place lowered global variables in a comdat group if the associated function
1262 // or global variable is a COMDAT. This will make sure that only one copy of
1263 // global variable (e.g. function counters) of the COMDAT function will be
1264 // emitted after linking.
1265 bool NeedComdat = needsComdatForCounter(*GO, M);
1266 bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1267
1268 if (!UseComdat)
1269 return;
1270
1271 // Keep in mind that this pass may run before the inliner, so we need to
1272 // create a new comdat group (for counters, profiling data, etc). If we use
1273 // the comdat of the parent function, that will result in relocations against
1274 // discarded sections.
1275 //
1276 // If the data variable is referenced by code, non-counter variables (notably
1277 // profiling data) and counters have to be in different comdats for COFF
1278 // because the Visual C++ linker will report duplicate symbol errors if there
1279 // are multiple external symbols with the same name marked
1280 // IMAGE_COMDAT_SELECT_ASSOCIATIVE.
1281 StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1282 ? GV->getName()
1283 : CounterGroupName;
1284 Comdat *C = M.getOrInsertComdat(GroupName);
1285
1286 if (!NeedComdat) {
1287 // Object file format must be ELF since `UseComdat && !NeedComdat` is true.
1288 //
1289 // For ELF, when not using COMDAT, put counters, data and values into a
1290 // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
1291 // allows -z start-stop-gc to discard the entire group when the function is
1292 // discarded.
1293 C->setSelectionKind(Comdat::NoDeduplicate);
1294 }
1295 GV->setComdat(C);
1296 // COFF doesn't allow the comdat group leader to have private linkage, so
1297 // upgrade private linkage to internal linkage to produce a symbol table
1298 // entry.
1299 if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1301}
1302
1304 if (!profDataReferencedByCode(*GV->getParent()))
1305 return false;
1306
1307 if (!GV->hasLinkOnceLinkage() && !GV->hasLocalLinkage() &&
1309 return true;
1310
1311 // This avoids the profile data from referencing internal symbols in
1312 // COMDAT.
1313 if (GV->hasLocalLinkage() && GV->hasComdat())
1314 return false;
1315
1316 return true;
1317}
1318
1319// FIXME: Introduce an internal alias like what's done for functions to reduce
1320// the number of relocation entries.
1322 auto *Int8PtrTy = PointerType::getUnqual(GV->getContext());
1323
1324 // Store a nullptr in __profvt_ if a real address shouldn't be used.
1325 if (!shouldRecordVTableAddr(GV))
1326 return ConstantPointerNull::get(Int8PtrTy);
1327
1328 return ConstantExpr::getBitCast(GV, Int8PtrTy);
1329}
1330
1331void InstrLowerer::getOrCreateVTableProfData(GlobalVariable *GV) {
1333 "Value profiling is not supported with lightweight instrumentation");
1335 return;
1336
1337 // Skip llvm internal global variable or __prof variables.
1338 if (GV->getName().starts_with("llvm.") ||
1339 GV->getName().starts_with("__llvm") ||
1340 GV->getName().starts_with("__prof"))
1341 return;
1342
1343 // VTableProfData already created
1344 auto It = VTableDataMap.find(GV);
1345 if (It != VTableDataMap.end() && It->second)
1346 return;
1347
1350
1351 // This is to keep consistent with per-function profile data
1352 // for correctness.
1353 if (TT.isOSBinFormatXCOFF()) {
1355 Visibility = GlobalValue::DefaultVisibility;
1356 }
1357
1358 LLVMContext &Ctx = M.getContext();
1359 Type *DataTypes[] = {
1360#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1362#undef INSTR_PROF_VTABLE_DATA
1363 };
1364
1365 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1366
1367 // Used by INSTR_PROF_VTABLE_DATA MACRO
1368 Constant *VTableAddr = getVTableAddrForProfData(GV);
1369 const std::string PGOVTableName = getPGOName(*GV);
1370 // Record the length of the vtable. This is needed since vtable pointers
1371 // loaded from C++ objects might be from the middle of a vtable definition.
1372 uint32_t VTableSizeVal =
1373 M.getDataLayout().getTypeAllocSize(GV->getValueType());
1374
1375 Constant *DataVals[] = {
1376#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1378#undef INSTR_PROF_VTABLE_DATA
1379 };
1380
1381 auto *Data =
1382 new GlobalVariable(M, DataTy, /*constant=*/false, Linkage,
1383 ConstantStruct::get(DataTy, DataVals),
1384 getInstrProfVTableVarPrefix() + PGOVTableName);
1385
1386 Data->setVisibility(Visibility);
1387 Data->setSection(getInstrProfSectionName(IPSK_vtab, TT.getObjectFormat()));
1388 Data->setAlignment(Align(8));
1389
1390 maybeSetComdat(Data, GV, Data->getName());
1391
1392 VTableDataMap[GV] = Data;
1393
1394 ReferencedVTables.push_back(GV);
1395
1396 // VTable <Hash, Addr> is used by runtime but not referenced by other
1397 // sections. Conservatively mark it linker retained.
1398 UsedVars.push_back(Data);
1399}
1400
1401GlobalVariable *InstrLowerer::setupProfileSection(InstrProfInstBase *Inc,
1402 InstrProfSectKind IPSK) {
1403 GlobalVariable *NamePtr = Inc->getName();
1404
1405 // Match the linkage and visibility of the name global.
1406 Function *Fn = Inc->getParent()->getParent();
1408 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1409
1410 // Use internal rather than private linkage so the counter variable shows up
1411 // in the symbol table when using debug info for correlation.
1412 if ((DebugInfoCorrelate ||
1414 TT.isOSBinFormatMachO() && Linkage == GlobalValue::PrivateLinkage)
1416
1417 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1418 // symbols in the same csect won't be discarded. When there are duplicate weak
1419 // symbols, we can NOT guarantee that the relocations get resolved to the
1420 // intended weak symbol, so we can not ensure the correctness of the relative
1421 // CounterPtr, so we have to use private linkage for counter and data symbols.
1422 if (TT.isOSBinFormatXCOFF()) {
1424 Visibility = GlobalValue::DefaultVisibility;
1425 }
1426 // Move the name variable to the right section.
1427 bool Renamed;
1429 StringRef VarPrefix;
1430 std::string VarName;
1431 if (IPSK == IPSK_cnts) {
1432 VarPrefix = getInstrProfCountersVarPrefix();
1433 VarName = getVarName(Inc, VarPrefix, Renamed);
1434 InstrProfCntrInstBase *CntrIncrement = dyn_cast<InstrProfCntrInstBase>(Inc);
1435 Ptr = createRegionCounters(CntrIncrement, VarName, Linkage);
1436 } else if (IPSK == IPSK_bitmap) {
1437 VarPrefix = getInstrProfBitmapVarPrefix();
1438 VarName = getVarName(Inc, VarPrefix, Renamed);
1439 InstrProfMCDCBitmapInstBase *BitmapUpdate =
1440 dyn_cast<InstrProfMCDCBitmapInstBase>(Inc);
1441 Ptr = createRegionBitmaps(BitmapUpdate, VarName, Linkage);
1442 } else {
1443 llvm_unreachable("Profile Section must be for Counters or Bitmaps");
1444 }
1445
1446 Ptr->setVisibility(Visibility);
1447 // Put the counters and bitmaps in their own sections so linkers can
1448 // remove unneeded sections.
1449 Ptr->setSection(getInstrProfSectionName(IPSK, TT.getObjectFormat()));
1450 Ptr->setLinkage(Linkage);
1451 maybeSetComdat(Ptr, Fn, VarName);
1452 return Ptr;
1453}
1454
1456InstrLowerer::createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
1458 GlobalValue::LinkageTypes Linkage) {
1459 uint64_t NumBytes = Inc->getNumBitmapBytes();
1460 auto *BitmapTy = ArrayType::get(Type::getInt8Ty(M.getContext()), NumBytes);
1461 auto GV = new GlobalVariable(M, BitmapTy, false, Linkage,
1462 Constant::getNullValue(BitmapTy), Name);
1463 GV->setAlignment(Align(1));
1464 return GV;
1465}
1466
1468InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
1469 GlobalVariable *NamePtr = Inc->getName();
1470 auto &PD = ProfileDataMap[NamePtr];
1471 if (PD.RegionBitmaps)
1472 return PD.RegionBitmaps;
1473
1474 // If RegionBitmaps doesn't already exist, create it by first setting up
1475 // the corresponding profile section.
1476 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1477 PD.RegionBitmaps = BitmapPtr;
1478 PD.NumBitmapBytes = Inc->getNumBitmapBytes();
1479 return PD.RegionBitmaps;
1480}
1481
1483InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
1484 GlobalValue::LinkageTypes Linkage) {
1485 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1486 auto &Ctx = M.getContext();
1487 GlobalVariable *GV;
1488 if (isa<InstrProfCoverInst>(Inc)) {
1489 auto *CounterTy = Type::getInt8Ty(Ctx);
1490 auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
1491 // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
1492 std::vector<Constant *> InitialValues(NumCounters,
1493 Constant::getAllOnesValue(CounterTy));
1494 GV = new GlobalVariable(M, CounterArrTy, false, Linkage,
1495 ConstantArray::get(CounterArrTy, InitialValues),
1496 Name);
1497 GV->setAlignment(Align(1));
1498 } else {
1499 auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
1500 GV = new GlobalVariable(M, CounterTy, false, Linkage,
1501 Constant::getNullValue(CounterTy), Name);
1502 GV->setAlignment(Align(8));
1503 }
1504 return GV;
1505}
1506
1508InstrLowerer::getOrCreateRegionCounters(InstrProfCntrInstBase *Inc) {
1509 GlobalVariable *NamePtr = Inc->getName();
1510 auto &PD = ProfileDataMap[NamePtr];
1511 if (PD.RegionCounters)
1512 return PD.RegionCounters;
1513
1514 // If RegionCounters doesn't already exist, create it by first setting up
1515 // the corresponding profile section.
1516 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1517 PD.RegionCounters = CounterPtr;
1518
1519 if (DebugInfoCorrelate ||
1521 LLVMContext &Ctx = M.getContext();
1522 Function *Fn = Inc->getParent()->getParent();
1523 if (auto *SP = Fn->getSubprogram()) {
1524 DIBuilder DB(M, true, SP->getUnit());
1525 Metadata *FunctionNameAnnotation[] = {
1528 };
1529 Metadata *CFGHashAnnotation[] = {
1532 };
1533 Metadata *NumCountersAnnotation[] = {
1536 };
1537 auto Annotations = DB.getOrCreateArray({
1538 MDNode::get(Ctx, FunctionNameAnnotation),
1539 MDNode::get(Ctx, CFGHashAnnotation),
1540 MDNode::get(Ctx, NumCountersAnnotation),
1541 });
1542 auto *DICounter = DB.createGlobalVariableExpression(
1543 SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1544 /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
1545 CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1546 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1547 Annotations);
1548 CounterPtr->addDebugInfo(DICounter);
1549 DB.finalize();
1550 }
1551
1552 // Mark the counter variable as used so that it isn't optimized out.
1553 CompilerUsedVars.push_back(PD.RegionCounters);
1554 }
1555
1556 // Create the data variable (if it doesn't already exist).
1557 createDataVariable(Inc);
1558
1559 return PD.RegionCounters;
1560}
1561
1562void InstrLowerer::createDataVariable(InstrProfCntrInstBase *Inc) {
1563 // When debug information is correlated to profile data, a data variable
1564 // is not needed.
1566 return;
1567
1568 GlobalVariable *NamePtr = Inc->getName();
1569 auto &PD = ProfileDataMap[NamePtr];
1570
1571 // Return if data variable was already created.
1572 if (PD.DataVar)
1573 return;
1574
1575 LLVMContext &Ctx = M.getContext();
1576
1577 Function *Fn = Inc->getParent()->getParent();
1579 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1580
1581 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1582 // symbols in the same csect won't be discarded. When there are duplicate weak
1583 // symbols, we can NOT guarantee that the relocations get resolved to the
1584 // intended weak symbol, so we can not ensure the correctness of the relative
1585 // CounterPtr, so we have to use private linkage for counter and data symbols.
1586 if (TT.isOSBinFormatXCOFF()) {
1588 Visibility = GlobalValue::DefaultVisibility;
1589 }
1590
1591 bool NeedComdat = needsComdatForCounter(*Fn, M);
1592 bool Renamed;
1593
1594 // The Data Variable section is anchored to profile counters.
1595 std::string CntsVarName =
1597 std::string DataVarName =
1598 getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
1599
1600 auto *Int8PtrTy = PointerType::getUnqual(Ctx);
1601 // Allocate statically the array of pointers to value profile nodes for
1602 // the current function.
1603 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1604 uint64_t NS = 0;
1605 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1606 NS += PD.NumValueSites[Kind];
1607 if (NS > 0 && ValueProfileStaticAlloc &&
1609 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1610 auto *ValuesVar = new GlobalVariable(
1611 M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1612 getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
1613 ValuesVar->setVisibility(Visibility);
1614 setGlobalVariableLargeSection(TT, *ValuesVar);
1615 ValuesVar->setSection(
1616 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1617 ValuesVar->setAlignment(Align(8));
1618 maybeSetComdat(ValuesVar, Fn, CntsVarName);
1619 ValuesPtrExpr = ValuesVar;
1620 }
1621
1622 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1623 auto *CounterPtr = PD.RegionCounters;
1624
1625 uint64_t NumBitmapBytes = PD.NumBitmapBytes;
1626
1627 // Create data variable.
1628 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
1629 auto *Int16Ty = Type::getInt16Ty(Ctx);
1630 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1631 Type *DataTypes[] = {
1632#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1634 };
1635 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1636
1637 Constant *FunctionAddr = getFuncAddrForProfData(Fn);
1638
1639 Constant *Int16ArrayVals[IPVK_Last + 1];
1640 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1641 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1642
1643 // If the data variable is not referenced by code (if we don't emit
1644 // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1645 // data variable live under linker GC, the data variable can be private. This
1646 // optimization applies to ELF.
1647 //
1648 // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1649 // to be false.
1650 //
1651 // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1652 // that other copies must have the same CFG and cannot have value profiling.
1653 // If no hash suffix, other profd copies may be referenced by code.
1654 if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1655 (TT.isOSBinFormatELF() ||
1656 (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1658 Visibility = GlobalValue::DefaultVisibility;
1659 }
1660 auto *Data =
1661 new GlobalVariable(M, DataTy, false, Linkage, nullptr, DataVarName);
1662 Constant *RelativeCounterPtr;
1663 GlobalVariable *BitmapPtr = PD.RegionBitmaps;
1664 Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
1665 InstrProfSectKind DataSectionKind;
1666 // With binary profile correlation, profile data is not loaded into memory.
1667 // profile data must reference profile counter with an absolute relocation.
1669 DataSectionKind = IPSK_covdata;
1670 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
1671 if (BitmapPtr != nullptr)
1672 RelativeBitmapPtr = ConstantExpr::getPtrToInt(BitmapPtr, IntPtrTy);
1673 } else {
1674 // Reference the counter variable with a label difference (link-time
1675 // constant).
1676 DataSectionKind = IPSK_data;
1677 RelativeCounterPtr =
1678 ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1679 ConstantExpr::getPtrToInt(Data, IntPtrTy));
1680 if (BitmapPtr != nullptr)
1681 RelativeBitmapPtr =
1683 ConstantExpr::getPtrToInt(Data, IntPtrTy));
1684 }
1685
1686 Constant *DataVals[] = {
1687#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1689 };
1690 Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1691
1692 Data->setVisibility(Visibility);
1693 Data->setSection(
1694 getInstrProfSectionName(DataSectionKind, TT.getObjectFormat()));
1695 Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1696 maybeSetComdat(Data, Fn, CntsVarName);
1697
1698 PD.DataVar = Data;
1699
1700 // Mark the data variable as used so that it isn't stripped out.
1701 CompilerUsedVars.push_back(Data);
1702 // Now that the linkage set by the FE has been passed to the data and counter
1703 // variables, reset Name variable's linkage and visibility to private so that
1704 // it can be removed later by the compiler.
1706 // Collect the referenced names to be used by emitNameData.
1707 ReferencedNames.push_back(NamePtr);
1708}
1709
1710void InstrLowerer::emitVNodes() {
1711 if (!ValueProfileStaticAlloc)
1712 return;
1713
1714 // For now only support this on platforms that do
1715 // not require runtime registration to discover
1716 // named section start/end.
1718 return;
1719
1720 size_t TotalNS = 0;
1721 for (auto &PD : ProfileDataMap) {
1722 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1723 TotalNS += PD.second.NumValueSites[Kind];
1724 }
1725
1726 if (!TotalNS)
1727 return;
1728
1729 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1730// Heuristic for small programs with very few total value sites.
1731// The default value of vp-counters-per-site is chosen based on
1732// the observation that large apps usually have a low percentage
1733// of value sites that actually have any profile data, and thus
1734// the average number of counters per site is low. For small
1735// apps with very few sites, this may not be true. Bump up the
1736// number of counters in this case.
1737#define INSTR_PROF_MIN_VAL_COUNTS 10
1738 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1739 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1740
1741 auto &Ctx = M.getContext();
1742 Type *VNodeTypes[] = {
1743#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1745 };
1746 auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
1747
1748 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1749 auto *VNodesVar = new GlobalVariable(
1750 M, VNodesTy, false, GlobalValue::PrivateLinkage,
1752 setGlobalVariableLargeSection(TT, *VNodesVar);
1753 VNodesVar->setSection(
1754 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1755 VNodesVar->setAlignment(M.getDataLayout().getABITypeAlign(VNodesTy));
1756 // VNodesVar is used by runtime but not referenced via relocation by other
1757 // sections. Conservatively make it linker retained.
1758 UsedVars.push_back(VNodesVar);
1759}
1760
1761void InstrLowerer::emitNameData() {
1762 std::string UncompressedData;
1763
1764 if (ReferencedNames.empty())
1765 return;
1766
1767 std::string CompressedNameStr;
1768 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
1770 report_fatal_error(Twine(toString(std::move(E))), false);
1771 }
1772
1773 auto &Ctx = M.getContext();
1774 auto *NamesVal =
1775 ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1776 NamesVar = new GlobalVariable(M, NamesVal->getType(), true,
1779 NamesSize = CompressedNameStr.size();
1780 setGlobalVariableLargeSection(TT, *NamesVar);
1781 NamesVar->setSection(
1783 ? getInstrProfSectionName(IPSK_covname, TT.getObjectFormat())
1784 : getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1785 // On COFF, it's important to reduce the alignment down to 1 to prevent the
1786 // linker from inserting padding before the start of the names section or
1787 // between names entries.
1788 NamesVar->setAlignment(Align(1));
1789 // NamesVar is used by runtime but not referenced via relocation by other
1790 // sections. Conservatively make it linker retained.
1791 UsedVars.push_back(NamesVar);
1792
1793 for (auto *NamePtr : ReferencedNames)
1794 NamePtr->eraseFromParent();
1795}
1796
1797void InstrLowerer::emitVTableNames() {
1798 if (!EnableVTableValueProfiling || ReferencedVTables.empty())
1799 return;
1800
1801 // Collect the PGO names of referenced vtables and compress them.
1802 std::string CompressedVTableNames;
1803 if (Error E = collectVTableStrings(ReferencedVTables, CompressedVTableNames,
1805 report_fatal_error(Twine(toString(std::move(E))), false);
1806 }
1807
1808 auto &Ctx = M.getContext();
1809 auto *VTableNamesVal = ConstantDataArray::getString(
1810 Ctx, StringRef(CompressedVTableNames), false /* AddNull */);
1811 GlobalVariable *VTableNamesVar =
1812 new GlobalVariable(M, VTableNamesVal->getType(), true /* constant */,
1813 GlobalValue::PrivateLinkage, VTableNamesVal,
1815 VTableNamesVar->setSection(
1816 getInstrProfSectionName(IPSK_vname, TT.getObjectFormat()));
1817 VTableNamesVar->setAlignment(Align(1));
1818 // Make VTableNames linker retained.
1819 UsedVars.push_back(VTableNamesVar);
1820}
1821
1822void InstrLowerer::emitRegistration() {
1824 return;
1825
1826 // Construct the function.
1827 auto *VoidTy = Type::getVoidTy(M.getContext());
1828 auto *VoidPtrTy = PointerType::getUnqual(M.getContext());
1829 auto *Int64Ty = Type::getInt64Ty(M.getContext());
1830 auto *RegisterFTy = FunctionType::get(VoidTy, false);
1831 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1833 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1834 if (Options.NoRedZone)
1835 RegisterF->addFnAttr(Attribute::NoRedZone);
1836
1837 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1838 auto *RuntimeRegisterF =
1841
1842 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", RegisterF));
1843 for (Value *Data : CompilerUsedVars)
1844 if (!isa<Function>(Data))
1845 IRB.CreateCall(RuntimeRegisterF, Data);
1846 for (Value *Data : UsedVars)
1847 if (Data != NamesVar && !isa<Function>(Data))
1848 IRB.CreateCall(RuntimeRegisterF, Data);
1849
1850 if (NamesVar) {
1851 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1852 auto *NamesRegisterTy =
1853 FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
1854 auto *NamesRegisterF =
1857 IRB.CreateCall(NamesRegisterF, {NamesVar, IRB.getInt64(NamesSize)});
1858 }
1859
1860 IRB.CreateRetVoid();
1861}
1862
1863bool InstrLowerer::emitRuntimeHook() {
1864 // We expect the linker to be invoked with -u<hook_var> flag for Linux
1865 // in which case there is no need to emit the external variable.
1866 if (TT.isOSLinux() || TT.isOSAIX())
1867 return false;
1868
1869 // If the module's provided its own runtime, we don't need to do anything.
1870 if (M.getGlobalVariable(getInstrProfRuntimeHookVarName()))
1871 return false;
1872
1873 // Declare an external variable that will pull in the runtime initialization.
1874 auto *Int32Ty = Type::getInt32Ty(M.getContext());
1875 auto *Var =
1876 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
1878 Var->setVisibility(GlobalValue::HiddenVisibility);
1879
1880 if (TT.isOSBinFormatELF() && !TT.isPS()) {
1881 // Mark the user variable as used so that it isn't stripped out.
1882 CompilerUsedVars.push_back(Var);
1883 } else {
1884 // Make a function that uses it.
1885 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1888 User->addFnAttr(Attribute::NoInline);
1889 if (Options.NoRedZone)
1890 User->addFnAttr(Attribute::NoRedZone);
1891 User->setVisibility(GlobalValue::HiddenVisibility);
1892 if (TT.supportsCOMDAT())
1893 User->setComdat(M.getOrInsertComdat(User->getName()));
1894
1895 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", User));
1896 auto *Load = IRB.CreateLoad(Int32Ty, Var);
1897 IRB.CreateRet(Load);
1898
1899 // Mark the function as used so that it isn't stripped out.
1900 CompilerUsedVars.push_back(User);
1901 }
1902 return true;
1903}
1904
1905void InstrLowerer::emitUses() {
1906 // The metadata sections are parallel arrays. Optimizers (e.g.
1907 // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1908 // we conservatively retain all unconditionally in the compiler.
1909 //
1910 // On ELF and Mach-O, the linker can guarantee the associated sections will be
1911 // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1912 // Similarly on COFF, if prof data is not referenced by code we use one comdat
1913 // and ensure this GC property as well. Otherwise, we have to conservatively
1914 // make all of the sections retained by the linker.
1915 if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1916 (TT.isOSBinFormatCOFF() && !DataReferencedByCode))
1917 appendToCompilerUsed(M, CompilerUsedVars);
1918 else
1919 appendToUsed(M, CompilerUsedVars);
1920
1921 // We do not add proper references from used metadata sections to NamesVar and
1922 // VNodesVar, so we have to be conservative and place them in llvm.used
1923 // regardless of the target,
1924 appendToUsed(M, UsedVars);
1925}
1926
1927void InstrLowerer::emitInitialization() {
1928 // Create ProfileFileName variable. Don't don't this for the
1929 // context-sensitive instrumentation lowering: This lowering is after
1930 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1931 // have already create the variable before LTO/ThinLTO linking.
1932 if (!IsCS)
1933 createProfileFileNameVar(M, Options.InstrProfileOutput);
1934 Function *RegisterF = M.getFunction(getInstrProfRegFuncsName());
1935 if (!RegisterF)
1936 return;
1937
1938 // Create the initialization function.
1939 auto *VoidTy = Type::getVoidTy(M.getContext());
1940 auto *F = Function::Create(FunctionType::get(VoidTy, false),
1943 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1944 F->addFnAttr(Attribute::NoInline);
1945 if (Options.NoRedZone)
1946 F->addFnAttr(Attribute::NoRedZone);
1947
1948 // Add the basic block and the necessary calls.
1949 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", F));
1950 IRB.CreateCall(RegisterF, {});
1951 IRB.CreateRetVoid();
1952
1953 appendToGlobalCtors(M, F, 0);
1954}
This file contains the simple types necessary to represent the attributes associated with functions a...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:686
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static unsigned InstrCount
static bool lowerIntrinsics(Module &M)
#define LLVM_DEBUG(X)
Definition: Debug.h:101
@ Default
Definition: DwarfDebug.cpp:87
uint64_t Addr
std::string Name
Hexagon Hardware Loops
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool shouldRecordVTableAddr(GlobalVariable *GV)
static bool shouldRecordFunctionAddr(Function *F)
static bool needsRuntimeHookUnconditionally(const Triple &TT)
static bool containsProfilingIntrinsics(Module &M)
Check if the module contains uses of any profiling intrinsics.
static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix, bool &Renamed)
Get the name of a profiling variable for a particular function.
#define INSTR_PROF_MIN_VAL_COUNTS
static Constant * getFuncAddrForProfData(Function *Fn)
static bool shouldUsePublicSymbol(Function *Fn)
static FunctionCallee getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI, ValueProfilingCallType CallType=ValueProfilingCallType::Default)
static Constant * getVTableAddrForProfData(GlobalVariable *GV)
static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT)
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Memory SSA
Definition: MemorySSA.cpp:72
Module.h This file contains the declarations for the Module class.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
if(VerifyEach)
const char LLVMTargetMachineRef LLVMPassBuilderOptionsRef Options
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
@ Add
*p = old + v
Definition: Instructions.h:711
@ Or
*p = old | v
Definition: Instructions.h:719
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:451
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:438
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:414
const Instruction & front() const
Definition: BasicBlock.h:461
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:202
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:209
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1292
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2900
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2568
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2217
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2245
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:155
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1762
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1357
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:76
Diagnostic information for the PGO profiler.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:600
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:165
const BasicBlock & getEntryBlock() const
Definition: Function.h:800
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1830
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:358
Argument * getArg(unsigned i) const
Definition: Function.h:849
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:544
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:589
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:137
void setComdat(Comdat *C)
Definition: Globals.cpp:206
bool hasComdat() const
Definition: GlobalObject.h:128
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:267
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:515
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:66
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:512
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:481
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2664
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
A base class for all instrprof counter intrinsics.
ConstantInt * getIndex() const
ConstantInt * getNumCounters() const
static const char * FunctionNameAttributeName
static const char * CFGHashAttributeName
static const char * NumCountersAttributeName
This represents the llvm.instrprof.cover intrinsic.
This represents the llvm.instrprof.increment intrinsic.
A base class for all instrprof intrinsics.
GlobalVariable * getName() const
ConstantInt * getHash() const
A base class for instrprof mcdc intrinsics that require global bitmap bytes.
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition: SSAUpdater.h:151
virtual void doExtraRewritesBeforeFinalDeletion()
This hook is invoked after all the stores are found and inserted as available values.
Definition: SSAUpdater.h:176
An instruction for reading from memory.
Definition: Instructions.h:173
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition: MDBuilder.cpp:47
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:600
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:40
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:564
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:258
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
static 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:373
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:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
const ParentTy * getParent() const
Definition: ilist_node.h:32
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
ValueKind
Value kinds.
@ Exit
Definition: COFF.h:812
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:1042
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
Definition: X86BaseInfo.h:737
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:92
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition: InstrProf.h:163
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition: InstrProf.h:104
cl::opt< bool > DoInstrProfNameCompression
cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate("profile-correlate", cl::desc("Use debug info or binary file to correlate profiles."), cl::init(InstrProfCorrelator::NONE), cl::values(clEnumValN(InstrProfCorrelator::NONE, "", "No profile correlation"), clEnumValN(InstrProfCorrelator::DEBUG_INFO, "debug-info", "Use debug info to correlate"), clEnumValN(InstrProfCorrelator::BINARY, "binary", "Use binary to correlate")))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
StringRef getInstrProfVTableNamesVarName()
Definition: InstrProf.h:116
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition: InstrProf.h:98
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition: InstrProf.h:129
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:231
cl::opt< bool > DebugInfoCorrelate
bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1440
std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
Definition: InstrProf.cpp:390
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition: InstrProf.h:158
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition: InstrProf.h:107
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:1729
StringRef getInstrProfCounterBiasVarName()
Definition: InstrProf.h:173
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition: InstrProf.h:169
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition: InstrProf.h:138
Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
Definition: InstrProf.cpp:703
InstrProfSectKind
Definition: InstrProf.h:60
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition: InstrProf.h:101
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:1736
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:696
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition: InstrProf.h:87
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition: InstrProf.h:150
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
@ Add
Sum of integers.
Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
Definition: InstrProf.cpp:713
void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1488
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1511
@ DS_Warning
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.
Definition: ModuleUtils.cpp:74
bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
auto predecessors(const MachineBasicBlock *BB)
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition: InstrProf.h:81
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition: InstrProf.h:144
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:114
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1466
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition: InstrProf.h:110
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition: InstrProf.h:95
#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
Options for the frontend instrumentation based profiling pass.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117