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