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