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/LoopInfo.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Pass.h"
39 #include "llvm/ProfileData/InstrProf.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include "llvm/Transforms/Utils/SSAUpdater.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstddef>
50 #include <cstdint>
51 #include <string>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "instrprof"
56 
57 // The start and end values of precise value profile range for memory
58 // intrinsic sizes
59 cl::opt<std::string> MemOPSizeRange(
60     "memop-size-range",
61     cl::desc("Set the range of size in memory intrinsic calls to be profiled "
62              "precisely, in a format of <start_val>:<end_val>"),
63     cl::init(""));
64 
65 // The value that considered to be large value in  memory intrinsic.
66 cl::opt<unsigned> MemOPSizeLarge(
67     "memop-size-large",
68     cl::desc("Set large value thresthold in memory intrinsic size profiling. "
69              "Value of 0 disables the large value profiling."),
70     cl::init(8192));
71 
72 namespace {
73 
74 cl::opt<bool> DoNameCompression("enable-name-compression",
75                                 cl::desc("Enable name string compression"),
76                                 cl::init(true));
77 
78 cl::opt<bool> DoHashBasedCounterSplit(
79     "hash-based-counter-split",
80     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
81     cl::init(true));
82 
83 cl::opt<bool> ValueProfileStaticAlloc(
84     "vp-static-alloc",
85     cl::desc("Do static counter allocation for value profiler"),
86     cl::init(true));
87 
88 cl::opt<double> NumCountersPerValueSite(
89     "vp-counters-per-site",
90     cl::desc("The average number of profile counters allocated "
91              "per value profiling site."),
92     // This is set to a very small value because in real programs, only
93     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
94     // For those sites with non-zero profile, the average number of targets
95     // is usually smaller than 2.
96     cl::init(1.0));
97 
98 cl::opt<bool> AtomicCounterUpdateAll(
99     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
100     cl::desc("Make all profile counter updates atomic (for testing only)"),
101     cl::init(false));
102 
103 cl::opt<bool> AtomicCounterUpdatePromoted(
104     "atomic-counter-update-promoted", cl::ZeroOrMore,
105     cl::desc("Do counter update using atomic fetch add "
106              " for promoted counters only"),
107     cl::init(false));
108 
109 // If the option is not specified, the default behavior about whether
110 // counter promotion is done depends on how instrumentaiton lowering
111 // pipeline is setup, i.e., the default value of true of this option
112 // does not mean the promotion will be done by default. Explicitly
113 // setting this option can override the default behavior.
114 cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
115                                  cl::desc("Do counter register promotion"),
116                                  cl::init(false));
117 cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
118     cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
119     cl::desc("Max number counter promotions per loop to avoid"
120              " increasing register pressure too much"));
121 
122 // A debug option
123 cl::opt<int>
124     MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
125                        cl::desc("Max number of allowed counter promotions"));
126 
127 cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
128     cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
129     cl::desc("The max number of exiting blocks of a loop to allow "
130              " speculative counter promotion"));
131 
132 cl::opt<bool> SpeculativeCounterPromotionToLoop(
133     cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
134     cl::desc("When the option is false, if the target block is in a loop, "
135              "the promotion will be disallowed unless the promoted counter "
136              " update can be further/iteratively promoted into an acyclic "
137              " region."));
138 
139 cl::opt<bool> IterativeCounterPromotion(
140     cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
141     cl::desc("Allow counter promotion across the whole loop nest."));
142 
143 class InstrProfilingLegacyPass : public ModulePass {
144   InstrProfiling InstrProf;
145 
146 public:
147   static char ID;
148 
149   InstrProfilingLegacyPass() : ModulePass(ID) {}
150   InstrProfilingLegacyPass(const InstrProfOptions &Options)
151       : ModulePass(ID), InstrProf(Options) {}
152 
153   StringRef getPassName() const override {
154     return "Frontend instrumentation-based coverage lowering";
155   }
156 
157   bool runOnModule(Module &M) override {
158     return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
159   }
160 
161   void getAnalysisUsage(AnalysisUsage &AU) const override {
162     AU.setPreservesCFG();
163     AU.addRequired<TargetLibraryInfoWrapperPass>();
164   }
165 };
166 
167 ///
168 /// A helper class to promote one counter RMW operation in the loop
169 /// into register update.
170 ///
171 /// RWM update for the counter will be sinked out of the loop after
172 /// the transformation.
173 ///
174 class PGOCounterPromoterHelper : public LoadAndStorePromoter {
175 public:
176   PGOCounterPromoterHelper(
177       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
178       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
179       ArrayRef<Instruction *> InsertPts,
180       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
181       LoopInfo &LI)
182       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
183         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
184     assert(isa<LoadInst>(L));
185     assert(isa<StoreInst>(S));
186     SSA.AddAvailableValue(PH, Init);
187   }
188 
189   void doExtraRewritesBeforeFinalDeletion() const override {
190     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
191       BasicBlock *ExitBlock = ExitBlocks[i];
192       Instruction *InsertPos = InsertPts[i];
193       // Get LiveIn value into the ExitBlock. If there are multiple
194       // predecessors, the value is defined by a PHI node in this
195       // block.
196       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
197       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
198       IRBuilder<> Builder(InsertPos);
199       if (AtomicCounterUpdatePromoted)
200         // automic update currently can only be promoted across the current
201         // loop, not the whole loop nest.
202         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
203                                 AtomicOrdering::SequentiallyConsistent);
204       else {
205         LoadInst *OldVal = Builder.CreateLoad(Addr, "pgocount.promoted");
206         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
207         auto *NewStore = Builder.CreateStore(NewVal, Addr);
208 
209         // Now update the parent loop's candidate list:
210         if (IterativeCounterPromotion) {
211           auto *TargetLoop = LI.getLoopFor(ExitBlock);
212           if (TargetLoop)
213             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
214         }
215       }
216     }
217   }
218 
219 private:
220   Instruction *Store;
221   ArrayRef<BasicBlock *> ExitBlocks;
222   ArrayRef<Instruction *> InsertPts;
223   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
224   LoopInfo &LI;
225 };
226 
227 /// A helper class to do register promotion for all profile counter
228 /// updates in a loop.
229 ///
230 class PGOCounterPromoter {
231 public:
232   PGOCounterPromoter(
233       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
234       Loop &CurLoop, LoopInfo &LI)
235       : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
236         LI(LI) {
237 
238     SmallVector<BasicBlock *, 8> LoopExitBlocks;
239     SmallPtrSet<BasicBlock *, 8> BlockSet;
240     L.getExitBlocks(LoopExitBlocks);
241 
242     for (BasicBlock *ExitBlock : LoopExitBlocks) {
243       if (BlockSet.insert(ExitBlock).second) {
244         ExitBlocks.push_back(ExitBlock);
245         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
246       }
247     }
248   }
249 
250   bool run(int64_t *NumPromoted) {
251     // Skip 'infinite' loops:
252     if (ExitBlocks.size() == 0)
253       return false;
254     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
255     if (MaxProm == 0)
256       return false;
257 
258     unsigned Promoted = 0;
259     for (auto &Cand : LoopToCandidates[&L]) {
260 
261       SmallVector<PHINode *, 4> NewPHIs;
262       SSAUpdater SSA(&NewPHIs);
263       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
264 
265       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
266                                         L.getLoopPreheader(), ExitBlocks,
267                                         InsertPts, LoopToCandidates, LI);
268       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
269       Promoted++;
270       if (Promoted >= MaxProm)
271         break;
272 
273       (*NumPromoted)++;
274       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
275         break;
276     }
277 
278     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
279                       << L.getLoopDepth() << ")\n");
280     return Promoted != 0;
281   }
282 
283 private:
284   bool allowSpeculativeCounterPromotion(Loop *LP) {
285     SmallVector<BasicBlock *, 8> ExitingBlocks;
286     L.getExitingBlocks(ExitingBlocks);
287     // Not considierered speculative.
288     if (ExitingBlocks.size() == 1)
289       return true;
290     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
291       return false;
292     return true;
293   }
294 
295   // Returns the max number of Counter Promotions for LP.
296   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
297     // We can't insert into a catchswitch.
298     SmallVector<BasicBlock *, 8> LoopExitBlocks;
299     LP->getExitBlocks(LoopExitBlocks);
300     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
301           return isa<CatchSwitchInst>(Exit->getTerminator());
302         }))
303       return 0;
304 
305     if (!LP->hasDedicatedExits())
306       return 0;
307 
308     BasicBlock *PH = LP->getLoopPreheader();
309     if (!PH)
310       return 0;
311 
312     SmallVector<BasicBlock *, 8> ExitingBlocks;
313     LP->getExitingBlocks(ExitingBlocks);
314     // Not considierered speculative.
315     if (ExitingBlocks.size() == 1)
316       return MaxNumOfPromotionsPerLoop;
317 
318     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
319       return 0;
320 
321     // Whether the target block is in a loop does not matter:
322     if (SpeculativeCounterPromotionToLoop)
323       return MaxNumOfPromotionsPerLoop;
324 
325     // Now check the target block:
326     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
327     for (auto *TargetBlock : LoopExitBlocks) {
328       auto *TargetLoop = LI.getLoopFor(TargetBlock);
329       if (!TargetLoop)
330         continue;
331       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
332       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
333       MaxProm =
334           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
335                                 PendingCandsInTarget);
336     }
337     return MaxProm;
338   }
339 
340   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
341   SmallVector<BasicBlock *, 8> ExitBlocks;
342   SmallVector<Instruction *, 8> InsertPts;
343   Loop &L;
344   LoopInfo &LI;
345 };
346 
347 } // end anonymous namespace
348 
349 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
350   auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
351   if (!run(M, TLI))
352     return PreservedAnalyses::all();
353 
354   return PreservedAnalyses::none();
355 }
356 
357 char InstrProfilingLegacyPass::ID = 0;
358 INITIALIZE_PASS_BEGIN(
359     InstrProfilingLegacyPass, "instrprof",
360     "Frontend instrumentation-based coverage lowering.", false, false)
361 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
362 INITIALIZE_PASS_END(
363     InstrProfilingLegacyPass, "instrprof",
364     "Frontend instrumentation-based coverage lowering.", false, false)
365 
366 ModulePass *
367 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
368   return new InstrProfilingLegacyPass(Options);
369 }
370 
371 static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
372   InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
373   if (Inc)
374     return Inc;
375   return dyn_cast<InstrProfIncrementInst>(Instr);
376 }
377 
378 bool InstrProfiling::lowerIntrinsics(Function *F) {
379   bool MadeChange = false;
380   PromotionCandidates.clear();
381   for (BasicBlock &BB : *F) {
382     for (auto I = BB.begin(), E = BB.end(); I != E;) {
383       auto Instr = I++;
384       InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
385       if (Inc) {
386         lowerIncrement(Inc);
387         MadeChange = true;
388       } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
389         lowerValueProfileInst(Ind);
390         MadeChange = true;
391       }
392     }
393   }
394 
395   if (!MadeChange)
396     return false;
397 
398   promoteCounterLoadStores(F);
399   return true;
400 }
401 
402 bool InstrProfiling::isCounterPromotionEnabled() const {
403   if (DoCounterPromotion.getNumOccurrences() > 0)
404     return DoCounterPromotion;
405 
406   return Options.DoCounterPromotion;
407 }
408 
409 void InstrProfiling::promoteCounterLoadStores(Function *F) {
410   if (!isCounterPromotionEnabled())
411     return;
412 
413   DominatorTree DT(*F);
414   LoopInfo LI(DT);
415   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
416 
417   for (const auto &LoadStore : PromotionCandidates) {
418     auto *CounterLoad = LoadStore.first;
419     auto *CounterStore = LoadStore.second;
420     BasicBlock *BB = CounterLoad->getParent();
421     Loop *ParentLoop = LI.getLoopFor(BB);
422     if (!ParentLoop)
423       continue;
424     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
425   }
426 
427   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
428 
429   // Do a post-order traversal of the loops so that counter updates can be
430   // iteratively hoisted outside the loop nest.
431   for (auto *Loop : llvm::reverse(Loops)) {
432     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI);
433     Promoter.run(&TotalCountersPromoted);
434   }
435 }
436 
437 /// Check if the module contains uses of any profiling intrinsics.
438 static bool containsProfilingIntrinsics(Module &M) {
439   if (auto *F = M.getFunction(
440           Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
441     if (!F->use_empty())
442       return true;
443   if (auto *F = M.getFunction(
444           Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
445     if (!F->use_empty())
446       return true;
447   if (auto *F = M.getFunction(
448           Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
449     if (!F->use_empty())
450       return true;
451   return false;
452 }
453 
454 bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
455   this->M = &M;
456   this->TLI = &TLI;
457   NamesVar = nullptr;
458   NamesSize = 0;
459   ProfileDataMap.clear();
460   UsedVars.clear();
461   getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
462                               MemOPSizeRangeLast);
463   TT = Triple(M.getTargetTriple());
464 
465   // Emit the runtime hook even if no counters are present.
466   bool MadeChange = emitRuntimeHook();
467 
468   // Improve compile time by avoiding linear scans when there is no work.
469   GlobalVariable *CoverageNamesVar =
470       M.getNamedGlobal(getCoverageUnusedNamesVarName());
471   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
472     return MadeChange;
473 
474   // We did not know how many value sites there would be inside
475   // the instrumented function. This is counting the number of instrumented
476   // target value sites to enter it as field in the profile data variable.
477   for (Function &F : M) {
478     InstrProfIncrementInst *FirstProfIncInst = nullptr;
479     for (BasicBlock &BB : F)
480       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
481         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
482           computeNumValueSiteCounts(Ind);
483         else if (FirstProfIncInst == nullptr)
484           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
485 
486     // Value profiling intrinsic lowering requires per-function profile data
487     // variable to be created first.
488     if (FirstProfIncInst != nullptr)
489       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
490   }
491 
492   for (Function &F : M)
493     MadeChange |= lowerIntrinsics(&F);
494 
495   if (CoverageNamesVar) {
496     lowerCoverageData(CoverageNamesVar);
497     MadeChange = true;
498   }
499 
500   if (!MadeChange)
501     return false;
502 
503   emitVNodes();
504   emitNameData();
505   emitRegistration();
506   emitUses();
507   emitInitialization();
508   return true;
509 }
510 
511 static Constant *getOrInsertValueProfilingCall(Module &M,
512                                                const TargetLibraryInfo &TLI,
513                                                bool IsRange = false) {
514   LLVMContext &Ctx = M.getContext();
515   auto *ReturnTy = Type::getVoidTy(M.getContext());
516 
517   Constant *Res;
518   if (!IsRange) {
519     Type *ParamTypes[] = {
520 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
521 #include "llvm/ProfileData/InstrProfData.inc"
522     };
523     auto *ValueProfilingCallTy =
524         FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
525     Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
526                                 ValueProfilingCallTy);
527   } else {
528     Type *RangeParamTypes[] = {
529 #define VALUE_RANGE_PROF 1
530 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
531 #include "llvm/ProfileData/InstrProfData.inc"
532 #undef VALUE_RANGE_PROF
533     };
534     auto *ValueRangeProfilingCallTy =
535         FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
536     Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
537                                 ValueRangeProfilingCallTy);
538   }
539 
540   if (Function *FunRes = dyn_cast<Function>(Res)) {
541     if (auto AK = TLI.getExtAttrForI32Param(false))
542       FunRes->addParamAttr(2, AK);
543   }
544   return Res;
545 }
546 
547 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
548   GlobalVariable *Name = Ind->getName();
549   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
550   uint64_t Index = Ind->getIndex()->getZExtValue();
551   auto It = ProfileDataMap.find(Name);
552   if (It == ProfileDataMap.end()) {
553     PerFunctionProfileData PD;
554     PD.NumValueSites[ValueKind] = Index + 1;
555     ProfileDataMap[Name] = PD;
556   } else if (It->second.NumValueSites[ValueKind] <= Index)
557     It->second.NumValueSites[ValueKind] = Index + 1;
558 }
559 
560 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
561   GlobalVariable *Name = Ind->getName();
562   auto It = ProfileDataMap.find(Name);
563   assert(It != ProfileDataMap.end() && It->second.DataVar &&
564          "value profiling detected in function with no counter incerement");
565 
566   GlobalVariable *DataVar = It->second.DataVar;
567   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
568   uint64_t Index = Ind->getIndex()->getZExtValue();
569   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
570     Index += It->second.NumValueSites[Kind];
571 
572   IRBuilder<> Builder(Ind);
573   bool IsRange = (Ind->getValueKind()->getZExtValue() ==
574                   llvm::InstrProfValueKind::IPVK_MemOPSize);
575   CallInst *Call = nullptr;
576   if (!IsRange) {
577     Value *Args[3] = {Ind->getTargetValue(),
578                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
579                       Builder.getInt32(Index)};
580     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
581   } else {
582     Value *Args[6] = {
583         Ind->getTargetValue(),
584         Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
585         Builder.getInt32(Index),
586         Builder.getInt64(MemOPSizeRangeStart),
587         Builder.getInt64(MemOPSizeRangeLast),
588         Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
589     Call =
590         Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
591   }
592   if (auto AK = TLI->getExtAttrForI32Param(false))
593     Call->addParamAttr(2, AK);
594   Ind->replaceAllUsesWith(Call);
595   Ind->eraseFromParent();
596 }
597 
598 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
599   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
600 
601   IRBuilder<> Builder(Inc);
602   uint64_t Index = Inc->getIndex()->getZExtValue();
603   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
604 
605   if (Options.Atomic || AtomicCounterUpdateAll) {
606     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
607                             AtomicOrdering::Monotonic);
608   } else {
609     Value *Load = Builder.CreateLoad(Addr, "pgocount");
610     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
611     auto *Store = Builder.CreateStore(Count, Addr);
612     if (isCounterPromotionEnabled())
613       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
614   }
615   Inc->eraseFromParent();
616 }
617 
618 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
619   ConstantArray *Names =
620       cast<ConstantArray>(CoverageNamesVar->getInitializer());
621   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
622     Constant *NC = Names->getOperand(I);
623     Value *V = NC->stripPointerCasts();
624     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
625     GlobalVariable *Name = cast<GlobalVariable>(V);
626 
627     Name->setLinkage(GlobalValue::PrivateLinkage);
628     ReferencedNames.push_back(Name);
629     NC->dropAllReferences();
630   }
631   CoverageNamesVar->eraseFromParent();
632 }
633 
634 /// Get the name of a profiling variable for a particular function.
635 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
636   StringRef NamePrefix = getInstrProfNameVarPrefix();
637   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
638   Function *F = Inc->getParent()->getParent();
639   Module *M = F->getParent();
640   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
641       !canRenameComdatFunc(*F))
642     return (Prefix + Name).str();
643   uint64_t FuncHash = Inc->getHash()->getZExtValue();
644   SmallVector<char, 24> HashPostfix;
645   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
646     return (Prefix + Name).str();
647   return (Prefix + Name + "." + Twine(FuncHash)).str();
648 }
649 
650 static inline bool shouldRecordFunctionAddr(Function *F) {
651   // Check the linkage
652   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
653   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
654       !HasAvailableExternallyLinkage)
655     return true;
656 
657   // A function marked 'alwaysinline' with available_externally linkage can't
658   // have its address taken. Doing so would create an undefined external ref to
659   // the function, which would fail to link.
660   if (HasAvailableExternallyLinkage &&
661       F->hasFnAttribute(Attribute::AlwaysInline))
662     return false;
663 
664   // Prohibit function address recording if the function is both internal and
665   // COMDAT. This avoids the profile data variable referencing internal symbols
666   // in COMDAT.
667   if (F->hasLocalLinkage() && F->hasComdat())
668     return false;
669 
670   // Check uses of this function for other than direct calls or invokes to it.
671   // Inline virtual functions have linkeOnceODR linkage. When a key method
672   // exists, the vtable will only be emitted in the TU where the key method
673   // is defined. In a TU where vtable is not available, the function won't
674   // be 'addresstaken'. If its address is not recorded here, the profile data
675   // with missing address may be picked by the linker leading  to missing
676   // indirect call target info.
677   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
678 }
679 
680 static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
681                                                InstrProfIncrementInst *Inc) {
682   if (!needsComdatForCounter(F, M))
683     return nullptr;
684 
685   // COFF format requires a COMDAT section to have a key symbol with the same
686   // name. The linker targeting COFF also requires that the COMDAT
687   // a section is associated to must precede the associating section. For this
688   // reason, we must choose the counter var's name as the name of the comdat.
689   StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
690                                 ? getInstrProfCountersVarPrefix()
691                                 : getInstrProfComdatPrefix());
692   return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
693 }
694 
695 static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
696   // Don't do this for Darwin.  compiler-rt uses linker magic.
697   if (Triple(M.getTargetTriple()).isOSDarwin())
698     return false;
699 
700   // Use linker script magic to get data/cnts/name start/end.
701   if (Triple(M.getTargetTriple()).isOSLinux() ||
702       Triple(M.getTargetTriple()).isOSFreeBSD() ||
703       Triple(M.getTargetTriple()).isOSNetBSD() ||
704       Triple(M.getTargetTriple()).isOSFuchsia() ||
705       Triple(M.getTargetTriple()).isPS4CPU())
706     return false;
707 
708   return true;
709 }
710 
711 GlobalVariable *
712 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
713   GlobalVariable *NamePtr = Inc->getName();
714   auto It = ProfileDataMap.find(NamePtr);
715   PerFunctionProfileData PD;
716   if (It != ProfileDataMap.end()) {
717     if (It->second.RegionCounters)
718       return It->second.RegionCounters;
719     PD = It->second;
720   }
721 
722   // Move the name variable to the right section. Place them in a COMDAT group
723   // if the associated function is a COMDAT. This will make sure that
724   // only one copy of counters of the COMDAT function will be emitted after
725   // linking.
726   Function *Fn = Inc->getParent()->getParent();
727   Comdat *ProfileVarsComdat = nullptr;
728   ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
729 
730   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
731   LLVMContext &Ctx = M->getContext();
732   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
733 
734   // Create the counters variable.
735   auto *CounterPtr =
736       new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
737                          Constant::getNullValue(CounterTy),
738                          getVarName(Inc, getInstrProfCountersVarPrefix()));
739   CounterPtr->setVisibility(NamePtr->getVisibility());
740   CounterPtr->setSection(
741       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
742   CounterPtr->setAlignment(8);
743   CounterPtr->setComdat(ProfileVarsComdat);
744 
745   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
746   // Allocate statically the array of pointers to value profile nodes for
747   // the current function.
748   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
749   if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
750     uint64_t NS = 0;
751     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
752       NS += PD.NumValueSites[Kind];
753     if (NS) {
754       ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
755 
756       auto *ValuesVar =
757           new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
758                              Constant::getNullValue(ValuesTy),
759                              getVarName(Inc, getInstrProfValuesVarPrefix()));
760       ValuesVar->setVisibility(NamePtr->getVisibility());
761       ValuesVar->setSection(
762           getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
763       ValuesVar->setAlignment(8);
764       ValuesVar->setComdat(ProfileVarsComdat);
765       ValuesPtrExpr =
766           ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
767     }
768   }
769 
770   // Create data variable.
771   auto *Int16Ty = Type::getInt16Ty(Ctx);
772   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
773   Type *DataTypes[] = {
774 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
775 #include "llvm/ProfileData/InstrProfData.inc"
776   };
777   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
778 
779   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
780                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
781                                : ConstantPointerNull::get(Int8PtrTy);
782 
783   Constant *Int16ArrayVals[IPVK_Last + 1];
784   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
785     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
786 
787   Constant *DataVals[] = {
788 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
789 #include "llvm/ProfileData/InstrProfData.inc"
790   };
791   auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
792                                   ConstantStruct::get(DataTy, DataVals),
793                                   getVarName(Inc, getInstrProfDataVarPrefix()));
794   Data->setVisibility(NamePtr->getVisibility());
795   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
796   Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
797   Data->setComdat(ProfileVarsComdat);
798 
799   PD.RegionCounters = CounterPtr;
800   PD.DataVar = Data;
801   ProfileDataMap[NamePtr] = PD;
802 
803   // Mark the data variable as used so that it isn't stripped out.
804   UsedVars.push_back(Data);
805   // Now that the linkage set by the FE has been passed to the data and counter
806   // variables, reset Name variable's linkage and visibility to private so that
807   // it can be removed later by the compiler.
808   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
809   // Collect the referenced names to be used by emitNameData.
810   ReferencedNames.push_back(NamePtr);
811 
812   return CounterPtr;
813 }
814 
815 void InstrProfiling::emitVNodes() {
816   if (!ValueProfileStaticAlloc)
817     return;
818 
819   // For now only support this on platforms that do
820   // not require runtime registration to discover
821   // named section start/end.
822   if (needsRuntimeRegistrationOfSectionRange(*M))
823     return;
824 
825   size_t TotalNS = 0;
826   for (auto &PD : ProfileDataMap) {
827     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
828       TotalNS += PD.second.NumValueSites[Kind];
829   }
830 
831   if (!TotalNS)
832     return;
833 
834   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
835 // Heuristic for small programs with very few total value sites.
836 // The default value of vp-counters-per-site is chosen based on
837 // the observation that large apps usually have a low percentage
838 // of value sites that actually have any profile data, and thus
839 // the average number of counters per site is low. For small
840 // apps with very few sites, this may not be true. Bump up the
841 // number of counters in this case.
842 #define INSTR_PROF_MIN_VAL_COUNTS 10
843   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
844     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
845 
846   auto &Ctx = M->getContext();
847   Type *VNodeTypes[] = {
848 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
849 #include "llvm/ProfileData/InstrProfData.inc"
850   };
851   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
852 
853   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
854   auto *VNodesVar = new GlobalVariable(
855       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
856       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
857   VNodesVar->setSection(
858       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
859   UsedVars.push_back(VNodesVar);
860 }
861 
862 void InstrProfiling::emitNameData() {
863   std::string UncompressedData;
864 
865   if (ReferencedNames.empty())
866     return;
867 
868   std::string CompressedNameStr;
869   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
870                                           DoNameCompression)) {
871     report_fatal_error(toString(std::move(E)), false);
872   }
873 
874   auto &Ctx = M->getContext();
875   auto *NamesVal = ConstantDataArray::getString(
876       Ctx, StringRef(CompressedNameStr), false);
877   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
878                                 GlobalValue::PrivateLinkage, NamesVal,
879                                 getInstrProfNamesVarName());
880   NamesSize = CompressedNameStr.size();
881   NamesVar->setSection(
882       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
883   UsedVars.push_back(NamesVar);
884 
885   for (auto *NamePtr : ReferencedNames)
886     NamePtr->eraseFromParent();
887 }
888 
889 void InstrProfiling::emitRegistration() {
890   if (!needsRuntimeRegistrationOfSectionRange(*M))
891     return;
892 
893   // Construct the function.
894   auto *VoidTy = Type::getVoidTy(M->getContext());
895   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
896   auto *Int64Ty = Type::getInt64Ty(M->getContext());
897   auto *RegisterFTy = FunctionType::get(VoidTy, false);
898   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
899                                      getInstrProfRegFuncsName(), M);
900   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
901   if (Options.NoRedZone)
902     RegisterF->addFnAttr(Attribute::NoRedZone);
903 
904   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
905   auto *RuntimeRegisterF =
906       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
907                        getInstrProfRegFuncName(), M);
908 
909   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
910   for (Value *Data : UsedVars)
911     if (Data != NamesVar && !isa<Function>(Data))
912       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
913 
914   if (NamesVar) {
915     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
916     auto *NamesRegisterTy =
917         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
918     auto *NamesRegisterF =
919         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
920                          getInstrProfNamesRegFuncName(), M);
921     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
922                                     IRB.getInt64(NamesSize)});
923   }
924 
925   IRB.CreateRetVoid();
926 }
927 
928 bool InstrProfiling::emitRuntimeHook() {
929   // We expect the linker to be invoked with -u<hook_var> flag for linux,
930   // for which case there is no need to emit the user function.
931   if (Triple(M->getTargetTriple()).isOSLinux())
932     return false;
933 
934   // If the module's provided its own runtime, we don't need to do anything.
935   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
936     return false;
937 
938   // Declare an external variable that will pull in the runtime initialization.
939   auto *Int32Ty = Type::getInt32Ty(M->getContext());
940   auto *Var =
941       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
942                          nullptr, getInstrProfRuntimeHookVarName());
943 
944   // Make a function that uses it.
945   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
946                                 GlobalValue::LinkOnceODRLinkage,
947                                 getInstrProfRuntimeHookVarUseFuncName(), M);
948   User->addFnAttr(Attribute::NoInline);
949   if (Options.NoRedZone)
950     User->addFnAttr(Attribute::NoRedZone);
951   User->setVisibility(GlobalValue::HiddenVisibility);
952   if (Triple(M->getTargetTriple()).supportsCOMDAT())
953     User->setComdat(M->getOrInsertComdat(User->getName()));
954 
955   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
956   auto *Load = IRB.CreateLoad(Var);
957   IRB.CreateRet(Load);
958 
959   // Mark the user variable as used so that it isn't stripped out.
960   UsedVars.push_back(User);
961   return true;
962 }
963 
964 void InstrProfiling::emitUses() {
965   if (!UsedVars.empty())
966     appendToUsed(*M, UsedVars);
967 }
968 
969 void InstrProfiling::emitInitialization() {
970   StringRef InstrProfileOutput = Options.InstrProfileOutput;
971 
972   if (!InstrProfileOutput.empty()) {
973     // Create variable for profile name.
974     Constant *ProfileNameConst =
975         ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
976     GlobalVariable *ProfileNameVar = new GlobalVariable(
977         *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
978         ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
979     if (TT.supportsCOMDAT()) {
980       ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
981       ProfileNameVar->setComdat(M->getOrInsertComdat(
982           StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
983     }
984   }
985 
986   Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
987   if (!RegisterF)
988     return;
989 
990   // Create the initialization function.
991   auto *VoidTy = Type::getVoidTy(M->getContext());
992   auto *F = Function::Create(FunctionType::get(VoidTy, false),
993                              GlobalValue::InternalLinkage,
994                              getInstrProfInitFuncName(), M);
995   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
996   F->addFnAttr(Attribute::NoInline);
997   if (Options.NoRedZone)
998     F->addFnAttr(Attribute::NoRedZone);
999 
1000   // Add the basic block and the necessary calls.
1001   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1002   if (RegisterF)
1003     IRB.CreateCall(RegisterF, {});
1004   IRB.CreateRetVoid();
1005 
1006   appendToGlobalCtors(*M, F, 0);
1007 }
1008