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/ADT/Triple.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/ProfileData/InstrProf.h"
21 #include "llvm/Transforms/InstrProfiling.h"
22 #include "llvm/Transforms/Utils/ModuleUtils.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "instrprof"
27 
28 namespace {
29 
30 cl::opt<bool> DoNameCompression("enable-name-compression",
31                                 cl::desc("Enable name string compression"),
32                                 cl::init(true));
33 
34 cl::opt<bool> ValueProfileStaticAlloc(
35     "vp-static-alloc",
36     cl::desc("Do static counter allocation for value profiler"),
37     cl::init(true));
38 cl::opt<double> NumCountersPerValueSite(
39     "vp-counters-per-site",
40     cl::desc("The average number of profile counters allocated "
41              "per value profiling site."),
42     // This is set to a very small value because in real programs, only
43     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
44     // For those sites with non-zero profile, the average number of targets
45     // is usually smaller than 2.
46     cl::init(1.0));
47 
48 class InstrProfilingLegacyPass : public ModulePass {
49   InstrProfiling InstrProf;
50 
51 public:
52   static char ID;
53   InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
54   InstrProfilingLegacyPass(const InstrProfOptions &Options)
55       : ModulePass(ID), InstrProf(Options) {}
56   const char *getPassName() const override {
57     return "Frontend instrumentation-based coverage lowering";
58   }
59 
60   bool runOnModule(Module &M) override { return InstrProf.run(M); }
61 
62   void getAnalysisUsage(AnalysisUsage &AU) const override {
63     AU.setPreservesCFG();
64   }
65 };
66 
67 } // anonymous namespace
68 
69 PreservedAnalyses InstrProfiling::run(Module &M, AnalysisManager<Module> &AM) {
70   if (!run(M))
71     return PreservedAnalyses::all();
72 
73   return PreservedAnalyses::none();
74 }
75 
76 char InstrProfilingLegacyPass::ID = 0;
77 INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof",
78                 "Frontend instrumentation-based coverage lowering.", false,
79                 false)
80 
81 ModulePass *llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
82   return new InstrProfilingLegacyPass(Options);
83 }
84 
85 bool InstrProfiling::isMachO() const {
86   return Triple(M->getTargetTriple()).isOSBinFormatMachO();
87 }
88 
89 /// Get the section name for the counter variables.
90 StringRef InstrProfiling::getCountersSection() const {
91   return getInstrProfCountersSectionName(isMachO());
92 }
93 
94 /// Get the section name for the name variables.
95 StringRef InstrProfiling::getNameSection() const {
96   return getInstrProfNameSectionName(isMachO());
97 }
98 
99 /// Get the section name for the profile data variables.
100 StringRef InstrProfiling::getDataSection() const {
101   return getInstrProfDataSectionName(isMachO());
102 }
103 
104 /// Get the section name for the coverage mapping data.
105 StringRef InstrProfiling::getCoverageSection() const {
106   return getInstrProfCoverageSectionName(isMachO());
107 }
108 
109 bool InstrProfiling::run(Module &M) {
110   bool MadeChange = false;
111 
112   this->M = &M;
113   NamesVar = nullptr;
114   NamesSize = 0;
115   ProfileDataMap.clear();
116   UsedVars.clear();
117 
118   // We did not know how many value sites there would be inside
119   // the instrumented function. This is counting the number of instrumented
120   // target value sites to enter it as field in the profile data variable.
121   for (Function &F : M) {
122     InstrProfIncrementInst *FirstProfIncInst = nullptr;
123     for (BasicBlock &BB : F)
124       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
125         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
126           computeNumValueSiteCounts(Ind);
127         else if (FirstProfIncInst == nullptr)
128           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
129 
130     // Value profiling intrinsic lowering requires per-function profile data
131     // variable to be created first.
132     if (FirstProfIncInst != nullptr)
133       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
134   }
135 
136   for (Function &F : M)
137     for (BasicBlock &BB : F)
138       for (auto I = BB.begin(), E = BB.end(); I != E;) {
139         auto Instr = I++;
140         if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) {
141           lowerIncrement(Inc);
142           MadeChange = true;
143         } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
144           lowerValueProfileInst(Ind);
145           MadeChange = true;
146         }
147       }
148 
149   if (GlobalVariable *CoverageNamesVar =
150           M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
151     lowerCoverageData(CoverageNamesVar);
152     MadeChange = true;
153   }
154 
155   if (!MadeChange)
156     return false;
157 
158   emitVNodes();
159   emitNameData();
160   emitRegistration();
161   emitRuntimeHook();
162   emitUses();
163   emitInitialization();
164   return true;
165 }
166 
167 static Constant *getOrInsertValueProfilingCall(Module &M) {
168   LLVMContext &Ctx = M.getContext();
169   auto *ReturnTy = Type::getVoidTy(M.getContext());
170   Type *ParamTypes[] = {
171 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
172 #include "llvm/ProfileData/InstrProfData.inc"
173   };
174   auto *ValueProfilingCallTy =
175       FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
176   return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
177                                ValueProfilingCallTy);
178 }
179 
180 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
181 
182   GlobalVariable *Name = Ind->getName();
183   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
184   uint64_t Index = Ind->getIndex()->getZExtValue();
185   auto It = ProfileDataMap.find(Name);
186   if (It == ProfileDataMap.end()) {
187     PerFunctionProfileData PD;
188     PD.NumValueSites[ValueKind] = Index + 1;
189     ProfileDataMap[Name] = PD;
190   } else if (It->second.NumValueSites[ValueKind] <= Index)
191     It->second.NumValueSites[ValueKind] = Index + 1;
192 }
193 
194 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
195 
196   GlobalVariable *Name = Ind->getName();
197   auto It = ProfileDataMap.find(Name);
198   assert(It != ProfileDataMap.end() && It->second.DataVar &&
199     "value profiling detected in function with no counter incerement");
200 
201   GlobalVariable *DataVar = It->second.DataVar;
202   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
203   uint64_t Index = Ind->getIndex()->getZExtValue();
204   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
205     Index += It->second.NumValueSites[Kind];
206 
207   IRBuilder<> Builder(Ind);
208   Value* Args[3] = {Ind->getTargetValue(),
209       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
210       Builder.getInt32(Index)};
211   Ind->replaceAllUsesWith(
212       Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
213   Ind->eraseFromParent();
214 }
215 
216 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
217   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
218 
219   IRBuilder<> Builder(Inc);
220   uint64_t Index = Inc->getIndex()->getZExtValue();
221   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
222   Value *Count = Builder.CreateLoad(Addr, "pgocount");
223   Count = Builder.CreateAdd(Count, Builder.getInt64(1));
224   Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
225   Inc->eraseFromParent();
226 }
227 
228 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
229 
230   ConstantArray *Names =
231       cast<ConstantArray>(CoverageNamesVar->getInitializer());
232   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
233     Constant *NC = Names->getOperand(I);
234     Value *V = NC->stripPointerCasts();
235     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
236     GlobalVariable *Name = cast<GlobalVariable>(V);
237 
238     Name->setLinkage(GlobalValue::PrivateLinkage);
239     ReferencedNames.push_back(Name);
240   }
241 }
242 
243 /// Get the name of a profiling variable for a particular function.
244 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
245   StringRef NamePrefix = getInstrProfNameVarPrefix();
246   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
247   return (Prefix + Name).str();
248 }
249 
250 static inline bool shouldRecordFunctionAddr(Function *F) {
251   // Check the linkage
252   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
253       !F->hasAvailableExternallyLinkage())
254     return true;
255   // Prohibit function address recording if the function is both internal and
256   // COMDAT. This avoids the profile data variable referencing internal symbols
257   // in COMDAT.
258   if (F->hasLocalLinkage() && F->hasComdat())
259     return false;
260   // Check uses of this function for other than direct calls or invokes to it.
261   return F->hasAddressTaken();
262 }
263 
264 static inline bool needsComdatForCounter(Function &F, Module &M) {
265 
266   if (F.hasComdat())
267     return true;
268 
269   Triple TT(M.getTargetTriple());
270   if (!TT.isOSBinFormatELF())
271     return false;
272 
273   // See createPGOFuncNameVar for more details. To avoid link errors, profile
274   // counters for function with available_externally linkage needs to be changed
275   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
276   // created. Without using comdat, duplicate entries won't be removed by the
277   // linker leading to increased data segement size and raw profile size. Even
278   // worse, since the referenced counter from profile per-function data object
279   // will be resolved to the common strong definition, the profile counts for
280   // available_externally functions will end up being duplicated in raw profile
281   // data. This can result in distorted profile as the counts of those dups
282   // will be accumulated by the profile merger.
283   GlobalValue::LinkageTypes Linkage = F.getLinkage();
284   if (Linkage != GlobalValue::ExternalWeakLinkage &&
285       Linkage != GlobalValue::AvailableExternallyLinkage)
286     return false;
287 
288   return true;
289 }
290 
291 static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
292                                                InstrProfIncrementInst *Inc) {
293   if (!needsComdatForCounter(F, M))
294     return nullptr;
295 
296   // COFF format requires a COMDAT section to have a key symbol with the same
297   // name. The linker targeting COFF also requires that the COMDAT
298   // a section is associated to must precede the associating section. For this
299   // reason, we must choose the counter var's name as the name of the comdat.
300   StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
301                                 ? getInstrProfCountersVarPrefix()
302                                 : getInstrProfComdatPrefix());
303   return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
304 }
305 
306 static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
307   // Don't do this for Darwin.  compiler-rt uses linker magic.
308   if (Triple(M.getTargetTriple()).isOSDarwin())
309     return false;
310 
311   // Use linker script magic to get data/cnts/name start/end.
312   if (Triple(M.getTargetTriple()).isOSLinux() ||
313       Triple(M.getTargetTriple()).isOSFreeBSD() ||
314       Triple(M.getTargetTriple()).isPS4CPU())
315     return false;
316 
317   return true;
318 }
319 
320 GlobalVariable *
321 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
322   GlobalVariable *NamePtr = Inc->getName();
323   auto It = ProfileDataMap.find(NamePtr);
324   PerFunctionProfileData PD;
325   if (It != ProfileDataMap.end()) {
326     if (It->second.RegionCounters)
327       return It->second.RegionCounters;
328     PD = It->second;
329   }
330 
331   // Move the name variable to the right section. Place them in a COMDAT group
332   // if the associated function is a COMDAT. This will make sure that
333   // only one copy of counters of the COMDAT function will be emitted after
334   // linking.
335   Function *Fn = Inc->getParent()->getParent();
336   Comdat *ProfileVarsComdat = nullptr;
337   ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
338 
339   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
340   LLVMContext &Ctx = M->getContext();
341   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
342 
343   // Create the counters variable.
344   auto *CounterPtr =
345       new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
346                          Constant::getNullValue(CounterTy),
347                          getVarName(Inc, getInstrProfCountersVarPrefix()));
348   CounterPtr->setVisibility(NamePtr->getVisibility());
349   CounterPtr->setSection(getCountersSection());
350   CounterPtr->setAlignment(8);
351   CounterPtr->setComdat(ProfileVarsComdat);
352 
353   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
354   // Allocate statically the array of pointers to value profile nodes for
355   // the current function.
356   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
357   if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
358 
359     uint64_t NS = 0;
360     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
361       NS += PD.NumValueSites[Kind];
362     if (NS) {
363       ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
364 
365       auto *ValuesVar =
366           new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
367                              Constant::getNullValue(ValuesTy),
368                              getVarName(Inc, getInstrProfValuesVarPrefix()));
369       ValuesVar->setVisibility(NamePtr->getVisibility());
370       ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
371       ValuesVar->setAlignment(8);
372       ValuesVar->setComdat(ProfileVarsComdat);
373       ValuesPtrExpr =
374           ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
375     }
376   }
377 
378   // Create data variable.
379   auto *Int16Ty = Type::getInt16Ty(Ctx);
380   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
381   Type *DataTypes[] = {
382     #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
383     #include "llvm/ProfileData/InstrProfData.inc"
384   };
385   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
386 
387   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn) ?
388                            ConstantExpr::getBitCast(Fn, Int8PtrTy) :
389                            ConstantPointerNull::get(Int8PtrTy);
390 
391   Constant *Int16ArrayVals[IPVK_Last+1];
392   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
393     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
394 
395   Constant *DataVals[] = {
396     #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
397     #include "llvm/ProfileData/InstrProfData.inc"
398   };
399   auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
400                                   ConstantStruct::get(DataTy, DataVals),
401                                   getVarName(Inc, getInstrProfDataVarPrefix()));
402   Data->setVisibility(NamePtr->getVisibility());
403   Data->setSection(getDataSection());
404   Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
405   Data->setComdat(ProfileVarsComdat);
406 
407   PD.RegionCounters = CounterPtr;
408   PD.DataVar = Data;
409   ProfileDataMap[NamePtr] = PD;
410 
411   // Mark the data variable as used so that it isn't stripped out.
412   UsedVars.push_back(Data);
413   // Now that the linkage set by the FE has been passed to the data and counter
414   // variables, reset Name variable's linkage and visibility to private so that
415   // it can be removed later by the compiler.
416   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
417   // Collect the referenced names to be used by emitNameData.
418   ReferencedNames.push_back(NamePtr);
419 
420   return CounterPtr;
421 }
422 
423 void InstrProfiling::emitVNodes() {
424   if (!ValueProfileStaticAlloc)
425     return;
426 
427   // For now only support this on platforms that do
428   // not require runtime registration to discover
429   // named section start/end.
430   if (needsRuntimeRegistrationOfSectionRange(*M))
431     return;
432 
433   size_t TotalNS = 0;
434   for (auto &PD : ProfileDataMap) {
435     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
436       TotalNS += PD.second.NumValueSites[Kind];
437   }
438 
439   if (!TotalNS)
440     return;
441 
442   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
443   // Heuristic for small programs with very few total value sites.
444   // The default value of vp-counters-per-site is chosen based on
445   // the observation that large apps usually have a low percentage
446   // of value sites that actually have any profile data, and thus
447   // the average number of counters per site is low. For small
448   // apps with very few sites, this may not be true. Bump up the
449   // number of counters in this case.
450 #define INSTR_PROF_MIN_VAL_COUNTS 10
451   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
452     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int) NumCounters * 2);
453 
454   auto &Ctx = M->getContext();
455   Type *VNodeTypes[] = {
456 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
457 #include "llvm/ProfileData/InstrProfData.inc"
458   };
459   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
460 
461   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
462   auto *VNodesVar = new GlobalVariable(
463       *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
464       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
465   VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
466   UsedVars.push_back(VNodesVar);
467 }
468 
469 void InstrProfiling::emitNameData() {
470   std::string UncompressedData;
471 
472   if (ReferencedNames.empty())
473     return;
474 
475   std::string CompressedNameStr;
476   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
477                                           DoNameCompression)) {
478     llvm::report_fatal_error(toString(std::move(E)), false);
479   }
480 
481   auto &Ctx = M->getContext();
482   auto *NamesVal = llvm::ConstantDataArray::getString(
483       Ctx, StringRef(CompressedNameStr), false);
484   NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
485                                       llvm::GlobalValue::PrivateLinkage,
486                                       NamesVal, getInstrProfNamesVarName());
487   NamesSize = CompressedNameStr.size();
488   NamesVar->setSection(getNameSection());
489   UsedVars.push_back(NamesVar);
490 }
491 
492 void InstrProfiling::emitRegistration() {
493   if (!needsRuntimeRegistrationOfSectionRange(*M))
494     return;
495 
496   // Construct the function.
497   auto *VoidTy = Type::getVoidTy(M->getContext());
498   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
499   auto *Int64Ty = Type::getInt64Ty(M->getContext());
500   auto *RegisterFTy = FunctionType::get(VoidTy, false);
501   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
502                                      getInstrProfRegFuncsName(), M);
503   RegisterF->setUnnamedAddr(true);
504   if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
505 
506   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
507   auto *RuntimeRegisterF =
508       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
509                        getInstrProfRegFuncName(), M);
510 
511   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
512   for (Value *Data : UsedVars)
513     if (Data != NamesVar)
514       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
515 
516   if (NamesVar) {
517     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
518     auto *NamesRegisterTy =
519         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
520     auto *NamesRegisterF =
521         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
522                          getInstrProfNamesRegFuncName(), M);
523     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
524                                     IRB.getInt64(NamesSize)});
525   }
526 
527   IRB.CreateRetVoid();
528 }
529 
530 void InstrProfiling::emitRuntimeHook() {
531 
532   // We expect the linker to be invoked with -u<hook_var> flag for linux,
533   // for which case there is no need to emit the user function.
534   if (Triple(M->getTargetTriple()).isOSLinux())
535     return;
536 
537   // If the module's provided its own runtime, we don't need to do anything.
538   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
539 
540   // Declare an external variable that will pull in the runtime initialization.
541   auto *Int32Ty = Type::getInt32Ty(M->getContext());
542   auto *Var =
543       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
544                          nullptr, getInstrProfRuntimeHookVarName());
545 
546   // Make a function that uses it.
547   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
548                                 GlobalValue::LinkOnceODRLinkage,
549                                 getInstrProfRuntimeHookVarUseFuncName(), M);
550   User->addFnAttr(Attribute::NoInline);
551   if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
552   User->setVisibility(GlobalValue::HiddenVisibility);
553   if (Triple(M->getTargetTriple()).supportsCOMDAT())
554     User->setComdat(M->getOrInsertComdat(User->getName()));
555 
556   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
557   auto *Load = IRB.CreateLoad(Var);
558   IRB.CreateRet(Load);
559 
560   // Mark the user variable as used so that it isn't stripped out.
561   UsedVars.push_back(User);
562 }
563 
564 void InstrProfiling::emitUses() {
565   if (UsedVars.empty())
566     return;
567 
568   GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
569   std::vector<Constant *> MergedVars;
570   if (LLVMUsed) {
571     // Collect the existing members of llvm.used.
572     ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
573     for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
574       MergedVars.push_back(Inits->getOperand(I));
575     LLVMUsed->eraseFromParent();
576   }
577 
578   Type *i8PTy = Type::getInt8PtrTy(M->getContext());
579   // Add uses for our data.
580   for (auto *Value : UsedVars)
581     MergedVars.push_back(
582         ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
583 
584   // Recreate llvm.used.
585   ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
586   LLVMUsed =
587       new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
588                          ConstantArray::get(ATy, MergedVars), "llvm.used");
589   LLVMUsed->setSection("llvm.metadata");
590 }
591 
592 void InstrProfiling::emitInitialization() {
593   std::string InstrProfileOutput = Options.InstrProfileOutput;
594 
595   Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
596   if (!RegisterF && InstrProfileOutput.empty()) return;
597 
598   // Create the initialization function.
599   auto *VoidTy = Type::getVoidTy(M->getContext());
600   auto *F = Function::Create(FunctionType::get(VoidTy, false),
601                              GlobalValue::InternalLinkage,
602                              getInstrProfInitFuncName(), M);
603   F->setUnnamedAddr(true);
604   F->addFnAttr(Attribute::NoInline);
605   if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
606 
607   // Add the basic block and the necessary calls.
608   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
609   if (RegisterF)
610     IRB.CreateCall(RegisterF, {});
611   if (!InstrProfileOutput.empty()) {
612     auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
613     auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
614     auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
615                                       getInstrProfFileOverriderFuncName(), M);
616 
617     // Create variable for profile name.
618     Constant *ProfileNameConst =
619         ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
620     GlobalVariable *ProfileName =
621         new GlobalVariable(*M, ProfileNameConst->getType(), true,
622                            GlobalValue::PrivateLinkage, ProfileNameConst);
623 
624     IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
625   }
626   IRB.CreateRetVoid();
627 
628   appendToGlobalCtors(*M, F, 0);
629 }
630