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