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 a frontend for profiling.
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 
15 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constant.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/InitializePasses.h"
43 #include "llvm/Pass.h"
44 #include "llvm/ProfileData/InstrProf.h"
45 #include "llvm/ProfileData/InstrProfCorrelator.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Error.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
51 #include "llvm/Transforms/Utils/SSAUpdater.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <cstdint>
55 #include <string>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "instrprof"
60 
61 namespace llvm {
62 cl::opt<bool>
63     DebugInfoCorrelate("debug-info-correlate",
64                        cl::desc("Use debug info to correlate profiles."),
65                        cl::init(false));
66 } // namespace llvm
67 
68 namespace {
69 
70 cl::opt<bool> DoHashBasedCounterSplit(
71     "hash-based-counter-split",
72     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
73     cl::init(true));
74 
75 cl::opt<bool>
76     RuntimeCounterRelocation("runtime-counter-relocation",
77                              cl::desc("Enable relocating counters at runtime."),
78                              cl::init(false));
79 
80 cl::opt<bool> ValueProfileStaticAlloc(
81     "vp-static-alloc",
82     cl::desc("Do static counter allocation for value profiler"),
83     cl::init(true));
84 
85 cl::opt<double> NumCountersPerValueSite(
86     "vp-counters-per-site",
87     cl::desc("The average number of profile counters allocated "
88              "per value profiling site."),
89     // This is set to a very small value because in real programs, only
90     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
91     // For those sites with non-zero profile, the average number of targets
92     // is usually smaller than 2.
93     cl::init(1.0));
94 
95 cl::opt<bool> AtomicCounterUpdateAll(
96     "instrprof-atomic-counter-update-all",
97     cl::desc("Make all profile counter updates atomic (for testing only)"),
98     cl::init(false));
99 
100 cl::opt<bool> AtomicCounterUpdatePromoted(
101     "atomic-counter-update-promoted",
102     cl::desc("Do counter update using atomic fetch add "
103              " for promoted counters only"),
104     cl::init(false));
105 
106 cl::opt<bool> AtomicFirstCounter(
107     "atomic-first-counter",
108     cl::desc("Use atomic fetch add for first counter in a function (usually "
109              "the entry counter)"),
110     cl::init(false));
111 
112 // If the option is not specified, the default behavior about whether
113 // counter promotion is done depends on how instrumentaiton lowering
114 // pipeline is setup, i.e., the default value of true of this option
115 // does not mean the promotion will be done by default. Explicitly
116 // setting this option can override the default behavior.
117 cl::opt<bool> DoCounterPromotion("do-counter-promotion",
118                                  cl::desc("Do counter register promotion"),
119                                  cl::init(false));
120 cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
121     "max-counter-promotions-per-loop", cl::init(20),
122     cl::desc("Max number counter promotions per loop to avoid"
123              " increasing register pressure too much"));
124 
125 // A debug option
126 cl::opt<int>
127     MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
128                        cl::desc("Max number of allowed counter promotions"));
129 
130 cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
131     "speculative-counter-promotion-max-exiting", cl::init(3),
132     cl::desc("The max number of exiting blocks of a loop to allow "
133              " speculative counter promotion"));
134 
135 cl::opt<bool> SpeculativeCounterPromotionToLoop(
136     "speculative-counter-promotion-to-loop",
137     cl::desc("When the option is false, if the target block is in a loop, "
138              "the promotion will be disallowed unless the promoted counter "
139              " update can be further/iteratively promoted into an acyclic "
140              " region."));
141 
142 cl::opt<bool> IterativeCounterPromotion(
143     "iterative-counter-promotion", cl::init(true),
144     cl::desc("Allow counter promotion across the whole loop nest."));
145 
146 cl::opt<bool> SkipRetExitBlock(
147     "skip-ret-exit-block", cl::init(true),
148     cl::desc("Suppress counter promotion if exit blocks contain ret."));
149 
150 class InstrProfilingLegacyPass : public ModulePass {
151   InstrProfiling InstrProf;
152 
153 public:
154   static char ID;
155 
156   InstrProfilingLegacyPass() : ModulePass(ID) {}
157   InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
158       : ModulePass(ID), InstrProf(Options, IsCS) {
159     initializeInstrProfilingLegacyPassPass(*PassRegistry::getPassRegistry());
160   }
161 
162   StringRef getPassName() const override {
163     return "Frontend instrumentation-based coverage lowering";
164   }
165 
166   bool runOnModule(Module &M) override {
167     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
168       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
169     };
170     return InstrProf.run(M, GetTLI);
171   }
172 
173   void getAnalysisUsage(AnalysisUsage &AU) const override {
174     AU.setPreservesCFG();
175     AU.addRequired<TargetLibraryInfoWrapperPass>();
176   }
177 };
178 
179 ///
180 /// A helper class to promote one counter RMW operation in the loop
181 /// into register update.
182 ///
183 /// RWM update for the counter will be sinked out of the loop after
184 /// the transformation.
185 ///
186 class PGOCounterPromoterHelper : public LoadAndStorePromoter {
187 public:
188   PGOCounterPromoterHelper(
189       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
190       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
191       ArrayRef<Instruction *> InsertPts,
192       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
193       LoopInfo &LI)
194       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
195         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
196     assert(isa<LoadInst>(L));
197     assert(isa<StoreInst>(S));
198     SSA.AddAvailableValue(PH, Init);
199   }
200 
201   void doExtraRewritesBeforeFinalDeletion() override {
202     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
203       BasicBlock *ExitBlock = ExitBlocks[i];
204       Instruction *InsertPos = InsertPts[i];
205       // Get LiveIn value into the ExitBlock. If there are multiple
206       // predecessors, the value is defined by a PHI node in this
207       // block.
208       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
209       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
210       Type *Ty = LiveInValue->getType();
211       IRBuilder<> Builder(InsertPos);
212       if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
213         // If isRuntimeCounterRelocationEnabled() is true then the address of
214         // the store instruction is computed with two instructions in
215         // InstrProfiling::getCounterAddress(). We need to copy those
216         // instructions to this block to compute Addr correctly.
217         // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
218         // %Addr = inttoptr i64 %BiasAdd to i64*
219         auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
220         assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
221         Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
222         Addr = Builder.CreateIntToPtr(BiasInst, Ty->getPointerTo());
223       }
224       if (AtomicCounterUpdatePromoted)
225         // automic update currently can only be promoted across the current
226         // loop, not the whole loop nest.
227         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
228                                 MaybeAlign(),
229                                 AtomicOrdering::SequentiallyConsistent);
230       else {
231         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
232         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
233         auto *NewStore = Builder.CreateStore(NewVal, Addr);
234 
235         // Now update the parent loop's candidate list:
236         if (IterativeCounterPromotion) {
237           auto *TargetLoop = LI.getLoopFor(ExitBlock);
238           if (TargetLoop)
239             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
240         }
241       }
242     }
243   }
244 
245 private:
246   Instruction *Store;
247   ArrayRef<BasicBlock *> ExitBlocks;
248   ArrayRef<Instruction *> InsertPts;
249   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
250   LoopInfo &LI;
251 };
252 
253 /// A helper class to do register promotion for all profile counter
254 /// updates in a loop.
255 ///
256 class PGOCounterPromoter {
257 public:
258   PGOCounterPromoter(
259       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
260       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
261       : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
262 
263     // Skip collection of ExitBlocks and InsertPts for loops that will not be
264     // able to have counters promoted.
265     SmallVector<BasicBlock *, 8> LoopExitBlocks;
266     SmallPtrSet<BasicBlock *, 8> BlockSet;
267 
268     L.getExitBlocks(LoopExitBlocks);
269     if (!isPromotionPossible(&L, LoopExitBlocks))
270       return;
271 
272     for (BasicBlock *ExitBlock : LoopExitBlocks) {
273       if (BlockSet.insert(ExitBlock).second) {
274         ExitBlocks.push_back(ExitBlock);
275         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
276       }
277     }
278   }
279 
280   bool run(int64_t *NumPromoted) {
281     // Skip 'infinite' loops:
282     if (ExitBlocks.size() == 0)
283       return false;
284 
285     // Skip if any of the ExitBlocks contains a ret instruction.
286     // This is to prevent dumping of incomplete profile -- if the
287     // the loop is a long running loop and dump is called in the middle
288     // of the loop, the result profile is incomplete.
289     // FIXME: add other heuristics to detect long running loops.
290     if (SkipRetExitBlock) {
291       for (auto BB : ExitBlocks)
292         if (isa<ReturnInst>(BB->getTerminator()))
293           return false;
294     }
295 
296     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
297     if (MaxProm == 0)
298       return false;
299 
300     unsigned Promoted = 0;
301     for (auto &Cand : LoopToCandidates[&L]) {
302 
303       SmallVector<PHINode *, 4> NewPHIs;
304       SSAUpdater SSA(&NewPHIs);
305       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
306 
307       // If BFI is set, we will use it to guide the promotions.
308       if (BFI) {
309         auto *BB = Cand.first->getParent();
310         auto InstrCount = BFI->getBlockProfileCount(BB);
311         if (!InstrCount)
312           continue;
313         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
314         // If the average loop trip count is not greater than 1.5, we skip
315         // promotion.
316         if (PreheaderCount &&
317             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
318           continue;
319       }
320 
321       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
322                                         L.getLoopPreheader(), ExitBlocks,
323                                         InsertPts, LoopToCandidates, LI);
324       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
325       Promoted++;
326       if (Promoted >= MaxProm)
327         break;
328 
329       (*NumPromoted)++;
330       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
331         break;
332     }
333 
334     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
335                       << L.getLoopDepth() << ")\n");
336     return Promoted != 0;
337   }
338 
339 private:
340   bool allowSpeculativeCounterPromotion(Loop *LP) {
341     SmallVector<BasicBlock *, 8> ExitingBlocks;
342     L.getExitingBlocks(ExitingBlocks);
343     // Not considierered speculative.
344     if (ExitingBlocks.size() == 1)
345       return true;
346     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
347       return false;
348     return true;
349   }
350 
351   // Check whether the loop satisfies the basic conditions needed to perform
352   // Counter Promotions.
353   bool
354   isPromotionPossible(Loop *LP,
355                       const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
356     // We can't insert into a catchswitch.
357     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
358           return isa<CatchSwitchInst>(Exit->getTerminator());
359         }))
360       return false;
361 
362     if (!LP->hasDedicatedExits())
363       return false;
364 
365     BasicBlock *PH = LP->getLoopPreheader();
366     if (!PH)
367       return false;
368 
369     return true;
370   }
371 
372   // Returns the max number of Counter Promotions for LP.
373   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
374     SmallVector<BasicBlock *, 8> LoopExitBlocks;
375     LP->getExitBlocks(LoopExitBlocks);
376     if (!isPromotionPossible(LP, LoopExitBlocks))
377       return 0;
378 
379     SmallVector<BasicBlock *, 8> ExitingBlocks;
380     LP->getExitingBlocks(ExitingBlocks);
381 
382     // If BFI is set, we do more aggressive promotions based on BFI.
383     if (BFI)
384       return (unsigned)-1;
385 
386     // Not considierered speculative.
387     if (ExitingBlocks.size() == 1)
388       return MaxNumOfPromotionsPerLoop;
389 
390     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
391       return 0;
392 
393     // Whether the target block is in a loop does not matter:
394     if (SpeculativeCounterPromotionToLoop)
395       return MaxNumOfPromotionsPerLoop;
396 
397     // Now check the target block:
398     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
399     for (auto *TargetBlock : LoopExitBlocks) {
400       auto *TargetLoop = LI.getLoopFor(TargetBlock);
401       if (!TargetLoop)
402         continue;
403       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
404       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
405       MaxProm =
406           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
407                                 PendingCandsInTarget);
408     }
409     return MaxProm;
410   }
411 
412   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
413   SmallVector<BasicBlock *, 8> ExitBlocks;
414   SmallVector<Instruction *, 8> InsertPts;
415   Loop &L;
416   LoopInfo &LI;
417   BlockFrequencyInfo *BFI;
418 };
419 
420 enum class ValueProfilingCallType {
421   // Individual values are tracked. Currently used for indiret call target
422   // profiling.
423   Default,
424 
425   // MemOp: the memop size value profiling.
426   MemOp
427 };
428 
429 } // end anonymous namespace
430 
431 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
432   FunctionAnalysisManager &FAM =
433       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
434   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
435     return FAM.getResult<TargetLibraryAnalysis>(F);
436   };
437   if (!run(M, GetTLI))
438     return PreservedAnalyses::all();
439 
440   return PreservedAnalyses::none();
441 }
442 
443 char InstrProfilingLegacyPass::ID = 0;
444 INITIALIZE_PASS_BEGIN(InstrProfilingLegacyPass, "instrprof",
445                       "Frontend instrumentation-based coverage lowering.",
446                       false, false)
447 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
448 INITIALIZE_PASS_END(InstrProfilingLegacyPass, "instrprof",
449                     "Frontend instrumentation-based coverage lowering.", false,
450                     false)
451 
452 ModulePass *
453 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
454                                      bool IsCS) {
455   return new InstrProfilingLegacyPass(Options, IsCS);
456 }
457 
458 bool InstrProfiling::lowerIntrinsics(Function *F) {
459   bool MadeChange = false;
460   PromotionCandidates.clear();
461   for (BasicBlock &BB : *F) {
462     for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
463       if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
464         lowerIncrement(IPIS);
465         MadeChange = true;
466       } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
467         lowerIncrement(IPI);
468         MadeChange = true;
469       } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
470         lowerCover(IPC);
471         MadeChange = true;
472       } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
473         lowerValueProfileInst(IPVP);
474         MadeChange = true;
475       }
476     }
477   }
478 
479   if (!MadeChange)
480     return false;
481 
482   promoteCounterLoadStores(F);
483   return true;
484 }
485 
486 bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
487   // Mach-O don't support weak external references.
488   if (TT.isOSBinFormatMachO())
489     return false;
490 
491   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
492     return RuntimeCounterRelocation;
493 
494   // Fuchsia uses runtime counter relocation by default.
495   return TT.isOSFuchsia();
496 }
497 
498 bool InstrProfiling::isCounterPromotionEnabled() const {
499   if (DoCounterPromotion.getNumOccurrences() > 0)
500     return DoCounterPromotion;
501 
502   return Options.DoCounterPromotion;
503 }
504 
505 void InstrProfiling::promoteCounterLoadStores(Function *F) {
506   if (!isCounterPromotionEnabled())
507     return;
508 
509   DominatorTree DT(*F);
510   LoopInfo LI(DT);
511   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
512 
513   std::unique_ptr<BlockFrequencyInfo> BFI;
514   if (Options.UseBFIInPromotion) {
515     std::unique_ptr<BranchProbabilityInfo> BPI;
516     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
517     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
518   }
519 
520   for (const auto &LoadStore : PromotionCandidates) {
521     auto *CounterLoad = LoadStore.first;
522     auto *CounterStore = LoadStore.second;
523     BasicBlock *BB = CounterLoad->getParent();
524     Loop *ParentLoop = LI.getLoopFor(BB);
525     if (!ParentLoop)
526       continue;
527     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
528   }
529 
530   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
531 
532   // Do a post-order traversal of the loops so that counter updates can be
533   // iteratively hoisted outside the loop nest.
534   for (auto *Loop : llvm::reverse(Loops)) {
535     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
536     Promoter.run(&TotalCountersPromoted);
537   }
538 }
539 
540 static bool needsRuntimeHookUnconditionally(const Triple &TT) {
541   // On Fuchsia, we only need runtime hook if any counters are present.
542   if (TT.isOSFuchsia())
543     return false;
544 
545   return true;
546 }
547 
548 /// Check if the module contains uses of any profiling intrinsics.
549 static bool containsProfilingIntrinsics(Module &M) {
550   auto containsIntrinsic = [&](int ID) {
551     if (auto *F = M.getFunction(Intrinsic::getName(ID)))
552       return !F->use_empty();
553     return false;
554   };
555   return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
556          containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
557          containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
558          containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
559 }
560 
561 bool InstrProfiling::run(
562     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
563   this->M = &M;
564   this->GetTLI = std::move(GetTLI);
565   NamesVar = nullptr;
566   NamesSize = 0;
567   ProfileDataMap.clear();
568   CompilerUsedVars.clear();
569   UsedVars.clear();
570   TT = Triple(M.getTargetTriple());
571 
572   bool MadeChange = false;
573 
574   // Emit the runtime hook even if no counters are present.
575   if (needsRuntimeHookUnconditionally(TT))
576     MadeChange = emitRuntimeHook();
577 
578   // Improve compile time by avoiding linear scans when there is no work.
579   GlobalVariable *CoverageNamesVar =
580       M.getNamedGlobal(getCoverageUnusedNamesVarName());
581   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
582     return MadeChange;
583 
584   // We did not know how many value sites there would be inside
585   // the instrumented function. This is counting the number of instrumented
586   // target value sites to enter it as field in the profile data variable.
587   for (Function &F : M) {
588     InstrProfIncrementInst *FirstProfIncInst = nullptr;
589     for (BasicBlock &BB : F)
590       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
591         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
592           computeNumValueSiteCounts(Ind);
593         else if (FirstProfIncInst == nullptr)
594           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
595 
596     // Value profiling intrinsic lowering requires per-function profile data
597     // variable to be created first.
598     if (FirstProfIncInst != nullptr)
599       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
600   }
601 
602   for (Function &F : M)
603     MadeChange |= lowerIntrinsics(&F);
604 
605   if (CoverageNamesVar) {
606     lowerCoverageData(CoverageNamesVar);
607     MadeChange = true;
608   }
609 
610   if (!MadeChange)
611     return false;
612 
613   emitVNodes();
614   emitNameData();
615   emitRuntimeHook();
616   emitRegistration();
617   emitUses();
618   emitInitialization();
619   return true;
620 }
621 
622 static FunctionCallee getOrInsertValueProfilingCall(
623     Module &M, const TargetLibraryInfo &TLI,
624     ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
625   LLVMContext &Ctx = M.getContext();
626   auto *ReturnTy = Type::getVoidTy(M.getContext());
627 
628   AttributeList AL;
629   if (auto AK = TLI.getExtAttrForI32Param(false))
630     AL = AL.addParamAttribute(M.getContext(), 2, AK);
631 
632   assert((CallType == ValueProfilingCallType::Default ||
633           CallType == ValueProfilingCallType::MemOp) &&
634          "Must be Default or MemOp");
635   Type *ParamTypes[] = {
636 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
637 #include "llvm/ProfileData/InstrProfData.inc"
638   };
639   auto *ValueProfilingCallTy =
640       FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
641   StringRef FuncName = CallType == ValueProfilingCallType::Default
642                            ? getInstrProfValueProfFuncName()
643                            : getInstrProfValueProfMemOpFuncName();
644   return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
645 }
646 
647 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
648   GlobalVariable *Name = Ind->getName();
649   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
650   uint64_t Index = Ind->getIndex()->getZExtValue();
651   auto &PD = ProfileDataMap[Name];
652   PD.NumValueSites[ValueKind] =
653       std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
654 }
655 
656 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
657   // TODO: Value profiling heavily depends on the data section which is omitted
658   // in lightweight mode. We need to move the value profile pointer to the
659   // Counter struct to get this working.
660   assert(
661       !DebugInfoCorrelate &&
662       "Value profiling is not yet supported with lightweight instrumentation");
663   GlobalVariable *Name = Ind->getName();
664   auto It = ProfileDataMap.find(Name);
665   assert(It != ProfileDataMap.end() && It->second.DataVar &&
666          "value profiling detected in function with no counter incerement");
667 
668   GlobalVariable *DataVar = It->second.DataVar;
669   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
670   uint64_t Index = Ind->getIndex()->getZExtValue();
671   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
672     Index += It->second.NumValueSites[Kind];
673 
674   IRBuilder<> Builder(Ind);
675   bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
676                       llvm::InstrProfValueKind::IPVK_MemOPSize);
677   CallInst *Call = nullptr;
678   auto *TLI = &GetTLI(*Ind->getFunction());
679 
680   // To support value profiling calls within Windows exception handlers, funclet
681   // information contained within operand bundles needs to be copied over to
682   // the library call. This is required for the IR to be processed by the
683   // WinEHPrepare pass.
684   SmallVector<OperandBundleDef, 1> OpBundles;
685   Ind->getOperandBundlesAsDefs(OpBundles);
686   if (!IsMemOpSize) {
687     Value *Args[3] = {Ind->getTargetValue(),
688                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
689                       Builder.getInt32(Index)};
690     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
691                               OpBundles);
692   } else {
693     Value *Args[3] = {Ind->getTargetValue(),
694                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
695                       Builder.getInt32(Index)};
696     Call = Builder.CreateCall(
697         getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
698         Args, OpBundles);
699   }
700   if (auto AK = TLI->getExtAttrForI32Param(false))
701     Call->addParamAttr(2, AK);
702   Ind->replaceAllUsesWith(Call);
703   Ind->eraseFromParent();
704 }
705 
706 Value *InstrProfiling::getCounterAddress(InstrProfInstBase *I) {
707   auto *Counters = getOrCreateRegionCounters(I);
708   IRBuilder<> Builder(I);
709 
710   auto *Addr = Builder.CreateConstInBoundsGEP2_32(
711       Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
712 
713   if (!isRuntimeCounterRelocationEnabled())
714     return Addr;
715 
716   Type *Int64Ty = Type::getInt64Ty(M->getContext());
717   Function *Fn = I->getParent()->getParent();
718   LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
719   if (!BiasLI) {
720     IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
721     auto *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
722     if (!Bias) {
723       // Compiler must define this variable when runtime counter relocation
724       // is being used. Runtime has a weak external reference that is used
725       // to check whether that's the case or not.
726       Bias = new GlobalVariable(
727           *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
728           Constant::getNullValue(Int64Ty), getInstrProfCounterBiasVarName());
729       Bias->setVisibility(GlobalVariable::HiddenVisibility);
730       // A definition that's weak (linkonce_odr) without being in a COMDAT
731       // section wouldn't lead to link errors, but it would lead to a dead
732       // data word from every TU but one. Putting it in COMDAT ensures there
733       // will be exactly one data slot in the link.
734       if (TT.supportsCOMDAT())
735         Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
736     }
737     BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias);
738   }
739   auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
740   return Builder.CreateIntToPtr(Add, Addr->getType());
741 }
742 
743 void InstrProfiling::lowerCover(InstrProfCoverInst *CoverInstruction) {
744   auto *Addr = getCounterAddress(CoverInstruction);
745   IRBuilder<> Builder(CoverInstruction);
746   // We store zero to represent that this block is covered.
747   Builder.CreateStore(Builder.getInt8(0), Addr);
748   CoverInstruction->eraseFromParent();
749 }
750 
751 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
752   auto *Addr = getCounterAddress(Inc);
753 
754   IRBuilder<> Builder(Inc);
755   if (Options.Atomic || AtomicCounterUpdateAll ||
756       (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
757     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
758                             MaybeAlign(), AtomicOrdering::Monotonic);
759   } else {
760     Value *IncStep = Inc->getStep();
761     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
762     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
763     auto *Store = Builder.CreateStore(Count, Addr);
764     if (isCounterPromotionEnabled())
765       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
766   }
767   Inc->eraseFromParent();
768 }
769 
770 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
771   ConstantArray *Names =
772       cast<ConstantArray>(CoverageNamesVar->getInitializer());
773   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
774     Constant *NC = Names->getOperand(I);
775     Value *V = NC->stripPointerCasts();
776     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
777     GlobalVariable *Name = cast<GlobalVariable>(V);
778 
779     Name->setLinkage(GlobalValue::PrivateLinkage);
780     ReferencedNames.push_back(Name);
781     if (isa<ConstantExpr>(NC))
782       NC->dropAllReferences();
783   }
784   CoverageNamesVar->eraseFromParent();
785 }
786 
787 /// Get the name of a profiling variable for a particular function.
788 static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
789                               bool &Renamed) {
790   StringRef NamePrefix = getInstrProfNameVarPrefix();
791   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
792   Function *F = Inc->getParent()->getParent();
793   Module *M = F->getParent();
794   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
795       !canRenameComdatFunc(*F)) {
796     Renamed = false;
797     return (Prefix + Name).str();
798   }
799   Renamed = true;
800   uint64_t FuncHash = Inc->getHash()->getZExtValue();
801   SmallVector<char, 24> HashPostfix;
802   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
803     return (Prefix + Name).str();
804   return (Prefix + Name + "." + Twine(FuncHash)).str();
805 }
806 
807 static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
808   auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
809   if (!MD)
810     return 0;
811 
812   // If the flag is a ConstantAsMetadata, it should be an integer representable
813   // in 64-bits.
814   return cast<ConstantInt>(MD->getValue())->getZExtValue();
815 }
816 
817 static bool enablesValueProfiling(const Module &M) {
818   return isIRPGOFlagSet(&M) ||
819          getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
820 }
821 
822 // Conservatively returns true if data variables may be referenced by code.
823 static bool profDataReferencedByCode(const Module &M) {
824   return enablesValueProfiling(M);
825 }
826 
827 static inline bool shouldRecordFunctionAddr(Function *F) {
828   // Only record function addresses if IR PGO is enabled or if clang value
829   // profiling is enabled. Recording function addresses greatly increases object
830   // file size, because it prevents the inliner from deleting functions that
831   // have been inlined everywhere.
832   if (!profDataReferencedByCode(*F->getParent()))
833     return false;
834 
835   // Check the linkage
836   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
837   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
838       !HasAvailableExternallyLinkage)
839     return true;
840 
841   // A function marked 'alwaysinline' with available_externally linkage can't
842   // have its address taken. Doing so would create an undefined external ref to
843   // the function, which would fail to link.
844   if (HasAvailableExternallyLinkage &&
845       F->hasFnAttribute(Attribute::AlwaysInline))
846     return false;
847 
848   // Prohibit function address recording if the function is both internal and
849   // COMDAT. This avoids the profile data variable referencing internal symbols
850   // in COMDAT.
851   if (F->hasLocalLinkage() && F->hasComdat())
852     return false;
853 
854   // Check uses of this function for other than direct calls or invokes to it.
855   // Inline virtual functions have linkeOnceODR linkage. When a key method
856   // exists, the vtable will only be emitted in the TU where the key method
857   // is defined. In a TU where vtable is not available, the function won't
858   // be 'addresstaken'. If its address is not recorded here, the profile data
859   // with missing address may be picked by the linker leading  to missing
860   // indirect call target info.
861   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
862 }
863 
864 static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
865   // Don't do this for Darwin.  compiler-rt uses linker magic.
866   if (TT.isOSDarwin())
867     return false;
868   // Use linker script magic to get data/cnts/name start/end.
869   if (TT.isOSAIX() || TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
870       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS() || TT.isOSWindows())
871     return false;
872 
873   return true;
874 }
875 
876 GlobalVariable *
877 InstrProfiling::createRegionCounters(InstrProfInstBase *Inc, StringRef Name,
878                                      GlobalValue::LinkageTypes Linkage) {
879   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
880   auto &Ctx = M->getContext();
881   GlobalVariable *GV;
882   if (isa<InstrProfCoverInst>(Inc)) {
883     auto *CounterTy = Type::getInt8Ty(Ctx);
884     auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
885     // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
886     std::vector<Constant *> InitialValues(NumCounters,
887                                           Constant::getAllOnesValue(CounterTy));
888     GV = new GlobalVariable(*M, CounterArrTy, false, Linkage,
889                             ConstantArray::get(CounterArrTy, InitialValues),
890                             Name);
891     GV->setAlignment(Align(1));
892   } else {
893     auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
894     GV = new GlobalVariable(*M, CounterTy, false, Linkage,
895                             Constant::getNullValue(CounterTy), Name);
896     GV->setAlignment(Align(8));
897   }
898   return GV;
899 }
900 
901 GlobalVariable *
902 InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
903   GlobalVariable *NamePtr = Inc->getName();
904   auto &PD = ProfileDataMap[NamePtr];
905   if (PD.RegionCounters)
906     return PD.RegionCounters;
907 
908   // Match the linkage and visibility of the name global.
909   Function *Fn = Inc->getParent()->getParent();
910   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
911   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
912 
913   // Use internal rather than private linkage so the counter variable shows up
914   // in the symbol table when using debug info for correlation.
915   if (DebugInfoCorrelate && TT.isOSBinFormatMachO() &&
916       Linkage == GlobalValue::PrivateLinkage)
917     Linkage = GlobalValue::InternalLinkage;
918 
919   // Due to the limitation of binder as of 2021/09/28, the duplicate weak
920   // symbols in the same csect won't be discarded. When there are duplicate weak
921   // symbols, we can NOT guarantee that the relocations get resolved to the
922   // intended weak symbol, so we can not ensure the correctness of the relative
923   // CounterPtr, so we have to use private linkage for counter and data symbols.
924   if (TT.isOSBinFormatXCOFF()) {
925     Linkage = GlobalValue::PrivateLinkage;
926     Visibility = GlobalValue::DefaultVisibility;
927   }
928   // Move the name variable to the right section. Place them in a COMDAT group
929   // if the associated function is a COMDAT. This will make sure that only one
930   // copy of counters of the COMDAT function will be emitted after linking. Keep
931   // in mind that this pass may run before the inliner, so we need to create a
932   // new comdat group for the counters and profiling data. If we use the comdat
933   // of the parent function, that will result in relocations against discarded
934   // sections.
935   //
936   // If the data variable is referenced by code,  counters and data have to be
937   // in different comdats for COFF because the Visual C++ linker will report
938   // duplicate symbol errors if there are multiple external symbols with the
939   // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
940   //
941   // For ELF, when not using COMDAT, put counters, data and values into a
942   // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
943   // allows -z start-stop-gc to discard the entire group when the function is
944   // discarded.
945   bool DataReferencedByCode = profDataReferencedByCode(*M);
946   bool NeedComdat = needsComdatForCounter(*Fn, *M);
947   bool Renamed;
948   std::string CntsVarName =
949       getVarName(Inc, getInstrProfCountersVarPrefix(), Renamed);
950   std::string DataVarName =
951       getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
952   auto MaybeSetComdat = [&](GlobalVariable *GV) {
953     bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
954     if (UseComdat) {
955       StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
956                                 ? GV->getName()
957                                 : CntsVarName;
958       Comdat *C = M->getOrInsertComdat(GroupName);
959       if (!NeedComdat)
960         C->setSelectionKind(Comdat::NoDeduplicate);
961       GV->setComdat(C);
962     }
963   };
964 
965   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
966   LLVMContext &Ctx = M->getContext();
967 
968   auto *CounterPtr = createRegionCounters(Inc, CntsVarName, Linkage);
969   CounterPtr->setVisibility(Visibility);
970   CounterPtr->setSection(
971       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
972   MaybeSetComdat(CounterPtr);
973   CounterPtr->setLinkage(Linkage);
974   PD.RegionCounters = CounterPtr;
975   if (DebugInfoCorrelate) {
976     if (auto *SP = Fn->getSubprogram()) {
977       DIBuilder DB(*M, true, SP->getUnit());
978       Metadata *FunctionNameAnnotation[] = {
979           MDString::get(Ctx, InstrProfCorrelator::FunctionNameAttributeName),
980           MDString::get(Ctx, getPGOFuncNameVarInitializer(NamePtr)),
981       };
982       Metadata *CFGHashAnnotation[] = {
983           MDString::get(Ctx, InstrProfCorrelator::CFGHashAttributeName),
984           ConstantAsMetadata::get(Inc->getHash()),
985       };
986       Metadata *NumCountersAnnotation[] = {
987           MDString::get(Ctx, InstrProfCorrelator::NumCountersAttributeName),
988           ConstantAsMetadata::get(Inc->getNumCounters()),
989       };
990       auto Annotations = DB.getOrCreateArray({
991           MDNode::get(Ctx, FunctionNameAnnotation),
992           MDNode::get(Ctx, CFGHashAnnotation),
993           MDNode::get(Ctx, NumCountersAnnotation),
994       });
995       auto *DICounter = DB.createGlobalVariableExpression(
996           SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
997           /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
998           CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
999           /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1000           Annotations);
1001       CounterPtr->addDebugInfo(DICounter);
1002       DB.finalize();
1003     } else {
1004       std::string Msg = ("Missing debug info for function " + Fn->getName() +
1005                          "; required for profile correlation.")
1006                             .str();
1007       Ctx.diagnose(
1008           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1009     }
1010   }
1011 
1012   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
1013   // Allocate statically the array of pointers to value profile nodes for
1014   // the current function.
1015   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1016   uint64_t NS = 0;
1017   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1018     NS += PD.NumValueSites[Kind];
1019   if (NS > 0 && ValueProfileStaticAlloc &&
1020       !needsRuntimeRegistrationOfSectionRange(TT)) {
1021     ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1022     auto *ValuesVar = new GlobalVariable(
1023         *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1024         getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
1025     ValuesVar->setVisibility(Visibility);
1026     ValuesVar->setSection(
1027         getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1028     ValuesVar->setAlignment(Align(8));
1029     MaybeSetComdat(ValuesVar);
1030     ValuesPtrExpr =
1031         ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
1032   }
1033 
1034   if (DebugInfoCorrelate) {
1035     // Mark the counter variable as used so that it isn't optimized out.
1036     CompilerUsedVars.push_back(PD.RegionCounters);
1037     return PD.RegionCounters;
1038   }
1039 
1040   // Create data variable.
1041   auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
1042   auto *Int16Ty = Type::getInt16Ty(Ctx);
1043   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1044   Type *DataTypes[] = {
1045 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1046 #include "llvm/ProfileData/InstrProfData.inc"
1047   };
1048   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
1049 
1050   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
1051                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
1052                                : ConstantPointerNull::get(Int8PtrTy);
1053 
1054   Constant *Int16ArrayVals[IPVK_Last + 1];
1055   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1056     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1057 
1058   // If the data variable is not referenced by code (if we don't emit
1059   // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1060   // data variable live under linker GC, the data variable can be private. This
1061   // optimization applies to ELF.
1062   //
1063   // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1064   // to be false.
1065   //
1066   // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1067   // that other copies must have the same CFG and cannot have value profiling.
1068   // If no hash suffix, other profd copies may be referenced by code.
1069   if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1070       (TT.isOSBinFormatELF() ||
1071        (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1072     Linkage = GlobalValue::PrivateLinkage;
1073     Visibility = GlobalValue::DefaultVisibility;
1074   }
1075   auto *Data =
1076       new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1077   // Reference the counter variable with a label difference (link-time
1078   // constant).
1079   auto *RelativeCounterPtr =
1080       ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1081                            ConstantExpr::getPtrToInt(Data, IntPtrTy));
1082 
1083   Constant *DataVals[] = {
1084 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1085 #include "llvm/ProfileData/InstrProfData.inc"
1086   };
1087   Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1088 
1089   Data->setVisibility(Visibility);
1090   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
1091   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1092   MaybeSetComdat(Data);
1093   Data->setLinkage(Linkage);
1094 
1095   PD.DataVar = Data;
1096 
1097   // Mark the data variable as used so that it isn't stripped out.
1098   CompilerUsedVars.push_back(Data);
1099   // Now that the linkage set by the FE has been passed to the data and counter
1100   // variables, reset Name variable's linkage and visibility to private so that
1101   // it can be removed later by the compiler.
1102   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
1103   // Collect the referenced names to be used by emitNameData.
1104   ReferencedNames.push_back(NamePtr);
1105 
1106   return PD.RegionCounters;
1107 }
1108 
1109 void InstrProfiling::emitVNodes() {
1110   if (!ValueProfileStaticAlloc)
1111     return;
1112 
1113   // For now only support this on platforms that do
1114   // not require runtime registration to discover
1115   // named section start/end.
1116   if (needsRuntimeRegistrationOfSectionRange(TT))
1117     return;
1118 
1119   size_t TotalNS = 0;
1120   for (auto &PD : ProfileDataMap) {
1121     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1122       TotalNS += PD.second.NumValueSites[Kind];
1123   }
1124 
1125   if (!TotalNS)
1126     return;
1127 
1128   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1129 // Heuristic for small programs with very few total value sites.
1130 // The default value of vp-counters-per-site is chosen based on
1131 // the observation that large apps usually have a low percentage
1132 // of value sites that actually have any profile data, and thus
1133 // the average number of counters per site is low. For small
1134 // apps with very few sites, this may not be true. Bump up the
1135 // number of counters in this case.
1136 #define INSTR_PROF_MIN_VAL_COUNTS 10
1137   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1138     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1139 
1140   auto &Ctx = M->getContext();
1141   Type *VNodeTypes[] = {
1142 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1143 #include "llvm/ProfileData/InstrProfData.inc"
1144   };
1145   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
1146 
1147   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1148   auto *VNodesVar = new GlobalVariable(
1149       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
1150       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
1151   VNodesVar->setSection(
1152       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1153   // VNodesVar is used by runtime but not referenced via relocation by other
1154   // sections. Conservatively make it linker retained.
1155   UsedVars.push_back(VNodesVar);
1156 }
1157 
1158 void InstrProfiling::emitNameData() {
1159   std::string UncompressedData;
1160 
1161   if (ReferencedNames.empty())
1162     return;
1163 
1164   std::string CompressedNameStr;
1165   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
1166                                           DoInstrProfNameCompression)) {
1167     report_fatal_error(Twine(toString(std::move(E))), false);
1168   }
1169 
1170   auto &Ctx = M->getContext();
1171   auto *NamesVal =
1172       ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1173   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
1174                                 GlobalValue::PrivateLinkage, NamesVal,
1175                                 getInstrProfNamesVarName());
1176   NamesSize = CompressedNameStr.size();
1177   NamesVar->setSection(
1178       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1179   // On COFF, it's important to reduce the alignment down to 1 to prevent the
1180   // linker from inserting padding before the start of the names section or
1181   // between names entries.
1182   NamesVar->setAlignment(Align(1));
1183   // NamesVar is used by runtime but not referenced via relocation by other
1184   // sections. Conservatively make it linker retained.
1185   UsedVars.push_back(NamesVar);
1186 
1187   for (auto *NamePtr : ReferencedNames)
1188     NamePtr->eraseFromParent();
1189 }
1190 
1191 void InstrProfiling::emitRegistration() {
1192   if (!needsRuntimeRegistrationOfSectionRange(TT))
1193     return;
1194 
1195   // Construct the function.
1196   auto *VoidTy = Type::getVoidTy(M->getContext());
1197   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1198   auto *Int64Ty = Type::getInt64Ty(M->getContext());
1199   auto *RegisterFTy = FunctionType::get(VoidTy, false);
1200   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1201                                      getInstrProfRegFuncsName(), M);
1202   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1203   if (Options.NoRedZone)
1204     RegisterF->addFnAttr(Attribute::NoRedZone);
1205 
1206   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1207   auto *RuntimeRegisterF =
1208       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
1209                        getInstrProfRegFuncName(), M);
1210 
1211   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1212   for (Value *Data : CompilerUsedVars)
1213     if (!isa<Function>(Data))
1214       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1215   for (Value *Data : UsedVars)
1216     if (Data != NamesVar && !isa<Function>(Data))
1217       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1218 
1219   if (NamesVar) {
1220     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1221     auto *NamesRegisterTy =
1222         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
1223     auto *NamesRegisterF =
1224         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
1225                          getInstrProfNamesRegFuncName(), M);
1226     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1227                                     IRB.getInt64(NamesSize)});
1228   }
1229 
1230   IRB.CreateRetVoid();
1231 }
1232 
1233 bool InstrProfiling::emitRuntimeHook() {
1234   // We expect the linker to be invoked with -u<hook_var> flag for Linux
1235   // in which case there is no need to emit the external variable.
1236   if (TT.isOSLinux())
1237     return false;
1238 
1239   // If the module's provided its own runtime, we don't need to do anything.
1240   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1241     return false;
1242 
1243   // Declare an external variable that will pull in the runtime initialization.
1244   auto *Int32Ty = Type::getInt32Ty(M->getContext());
1245   auto *Var =
1246       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
1247                          nullptr, getInstrProfRuntimeHookVarName());
1248 
1249   if (TT.isOSBinFormatELF()) {
1250     // Mark the user variable as used so that it isn't stripped out.
1251     CompilerUsedVars.push_back(Var);
1252   } else {
1253     // Make a function that uses it.
1254     auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1255                                   GlobalValue::LinkOnceODRLinkage,
1256                                   getInstrProfRuntimeHookVarUseFuncName(), M);
1257     User->addFnAttr(Attribute::NoInline);
1258     if (Options.NoRedZone)
1259       User->addFnAttr(Attribute::NoRedZone);
1260     User->setVisibility(GlobalValue::HiddenVisibility);
1261     if (TT.supportsCOMDAT())
1262       User->setComdat(M->getOrInsertComdat(User->getName()));
1263 
1264     IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1265     auto *Load = IRB.CreateLoad(Int32Ty, Var);
1266     IRB.CreateRet(Load);
1267 
1268     // Mark the function as used so that it isn't stripped out.
1269     CompilerUsedVars.push_back(User);
1270   }
1271   return true;
1272 }
1273 
1274 void InstrProfiling::emitUses() {
1275   // The metadata sections are parallel arrays. Optimizers (e.g.
1276   // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1277   // we conservatively retain all unconditionally in the compiler.
1278   //
1279   // On ELF and Mach-O, the linker can guarantee the associated sections will be
1280   // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1281   // Similarly on COFF, if prof data is not referenced by code we use one comdat
1282   // and ensure this GC property as well. Otherwise, we have to conservatively
1283   // make all of the sections retained by the linker.
1284   if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1285       (TT.isOSBinFormatCOFF() && !profDataReferencedByCode(*M)))
1286     appendToCompilerUsed(*M, CompilerUsedVars);
1287   else
1288     appendToUsed(*M, CompilerUsedVars);
1289 
1290   // We do not add proper references from used metadata sections to NamesVar and
1291   // VNodesVar, so we have to be conservative and place them in llvm.used
1292   // regardless of the target,
1293   appendToUsed(*M, UsedVars);
1294 }
1295 
1296 void InstrProfiling::emitInitialization() {
1297   // Create ProfileFileName variable. Don't don't this for the
1298   // context-sensitive instrumentation lowering: This lowering is after
1299   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1300   // have already create the variable before LTO/ThinLTO linking.
1301   if (!IsCS)
1302     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1303   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1304   if (!RegisterF)
1305     return;
1306 
1307   // Create the initialization function.
1308   auto *VoidTy = Type::getVoidTy(M->getContext());
1309   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1310                              GlobalValue::InternalLinkage,
1311                              getInstrProfInitFuncName(), M);
1312   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1313   F->addFnAttr(Attribute::NoInline);
1314   if (Options.NoRedZone)
1315     F->addFnAttr(Attribute::NoRedZone);
1316 
1317   // Add the basic block and the necessary calls.
1318   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1319   IRB.CreateCall(RegisterF, {});
1320   IRB.CreateRetVoid();
1321 
1322   appendToGlobalCtors(*M, F, 0);
1323 }
1324