blob: d2f5b29e24b6c316396055f3d6f313923f7ce5d9 [file] [log] [blame]
Justin Bogner61ba2e32014-12-08 18:02:35 +00001//===-- 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//
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000010// 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.
Justin Bogner61ba2e32014-12-08 18:02:35 +000013//
14//===----------------------------------------------------------------------===//
15
Justin Bogner61ba2e32014-12-08 18:02:35 +000016#include "llvm/ADT/Triple.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000020#include "llvm/ProfileData/InstrProf.h"
Xinliang David Lie6b89292016-04-18 17:47:38 +000021#include "llvm/Transforms/InstrProfiling.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000022#include "llvm/Transforms/Utils/ModuleUtils.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "instrprof"
27
28namespace {
29
Xinliang David Lia82d6c02016-02-08 18:13:49 +000030cl::opt<bool> DoNameCompression("enable-name-compression",
31 cl::desc("Enable name string compression"),
32 cl::init(true));
33
Xinliang David Lib628dd32016-05-21 22:55:34 +000034cl::opt<bool> ValueProfileStaticAlloc(
35 "vp-static-alloc",
36 cl::desc("Do static counter allocation for value profiler"),
37 cl::init(true));
38cl::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
Xinliang David Lie6b89292016-04-18 17:47:38 +000048class InstrProfilingLegacyPass : public ModulePass {
49 InstrProfiling InstrProf;
50
Justin Bogner61ba2e32014-12-08 18:02:35 +000051public:
52 static char ID;
Xinliang David Lie6b89292016-04-18 17:47:38 +000053 InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
54 InstrProfilingLegacyPass(const InstrProfOptions &Options)
55 : ModulePass(ID), InstrProf(Options) {}
Justin Bogner61ba2e32014-12-08 18:02:35 +000056 const char *getPassName() const override {
57 return "Frontend instrumentation-based coverage lowering";
58 }
59
Xinliang David Lie6b89292016-04-18 17:47:38 +000060 bool runOnModule(Module &M) override { return InstrProf.run(M); }
Justin Bogner61ba2e32014-12-08 18:02:35 +000061
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.setPreservesCFG();
64 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000065};
66
67} // anonymous namespace
68
Xinliang David Lie6b89292016-04-18 17:47:38 +000069PreservedAnalyses InstrProfiling::run(Module &M, AnalysisManager<Module> &AM) {
70 if (!run(M))
71 return PreservedAnalyses::all();
72
73 return PreservedAnalyses::none();
74}
75
76char InstrProfilingLegacyPass::ID = 0;
77INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof",
Justin Bogner61ba2e32014-12-08 18:02:35 +000078 "Frontend instrumentation-based coverage lowering.", false,
79 false)
80
Xinliang David Lie6b89292016-04-18 17:47:38 +000081ModulePass *llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
82 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +000083}
84
Xinliang David Lie6b89292016-04-18 17:47:38 +000085bool InstrProfiling::isMachO() const {
86 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
87}
88
89/// Get the section name for the counter variables.
90StringRef InstrProfiling::getCountersSection() const {
91 return getInstrProfCountersSectionName(isMachO());
92}
93
94/// Get the section name for the name variables.
95StringRef InstrProfiling::getNameSection() const {
96 return getInstrProfNameSectionName(isMachO());
97}
98
99/// Get the section name for the profile data variables.
100StringRef InstrProfiling::getDataSection() const {
101 return getInstrProfDataSectionName(isMachO());
102}
103
104/// Get the section name for the coverage mapping data.
105StringRef InstrProfiling::getCoverageSection() const {
106 return getInstrProfCoverageSectionName(isMachO());
107}
108
109bool InstrProfiling::run(Module &M) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000110 bool MadeChange = false;
111
112 this->M = &M;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000113 NamesVar = nullptr;
114 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000115 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000116 UsedVars.clear();
117
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000118 // 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.
Rong Xu294572f2016-01-19 18:29:54 +0000121 for (Function &F : M) {
122 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000123 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000124 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
125 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000126 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000127 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 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000135
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)) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000141 lowerIncrement(Inc);
142 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000143 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
144 lowerValueProfileInst(Ind);
145 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000146 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000147 }
148
Xinliang David Li81056072016-01-07 20:05:49 +0000149 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000150 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000151 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000152 MadeChange = true;
153 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000154
Justin Bogner61ba2e32014-12-08 18:02:35 +0000155 if (!MadeChange)
156 return false;
157
Xinliang David Lib628dd32016-05-21 22:55:34 +0000158 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000159 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000160 emitRegistration();
161 emitRuntimeHook();
162 emitUses();
163 emitInitialization();
164 return true;
165}
166
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000167static Constant *getOrInsertValueProfilingCall(Module &M) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000168 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 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000174 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000175 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Xinliang David Li924e0582015-11-22 05:42:31 +0000176 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000177 ValueProfilingCallTy);
178}
179
180void 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
194void 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000216void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
217 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
218
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000219 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000220 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000221 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
222 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000223 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
224 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
225 Inc->eraseFromParent();
226}
227
Xinliang David Li81056072016-01-07 20:05:49 +0000228void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000229
Xinliang David Li81056072016-01-07 20:05:49 +0000230 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();
Justin Bognerd24e1852015-02-11 02:52:44 +0000235 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
236 GlobalVariable *Name = cast<GlobalVariable>(V);
237
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000238 Name->setLinkage(GlobalValue::PrivateLinkage);
239 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000240 }
241}
242
Justin Bogner61ba2e32014-12-08 18:02:35 +0000243/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000244static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000245 StringRef NamePrefix = getInstrProfNameVarPrefix();
246 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Xinliang David Li83bc4222015-10-22 20:32:12 +0000247 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000248}
249
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000250static inline bool shouldRecordFunctionAddr(Function *F) {
251 // Check the linkage
252 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
253 !F->hasAvailableExternallyLinkage())
254 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000255 // 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;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000260 // Check uses of this function for other than direct calls or invokes to it.
261 return F->hasAddressTaken();
262}
263
Xinliang David Li985ff202016-02-27 23:11:30 +0000264static 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
291static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000292 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000293 if (!needsComdatForCounter(F, M))
294 return nullptr;
295
Xinliang David Liab361ef2015-12-21 21:52:27 +0000296 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000297 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000298 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000299 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000300 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000301 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000302 : getInstrProfComdatPrefix());
303 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
304}
305
Xinliang David Lib628dd32016-05-21 22:55:34 +0000306static 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000320GlobalVariable *
321InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000322 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000323 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 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000330
Wei Mi3cc92042015-09-23 22:40:45 +0000331 // 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.
Diego Novillodf4837b2015-05-27 19:34:01 +0000335 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000336 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000337 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000338
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.
Xinliang David Li192c7482015-11-05 00:47:26 +0000344 auto *CounterPtr =
345 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000346 Constant::getNullValue(CounterTy),
347 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000348 CounterPtr->setVisibility(NamePtr->getVisibility());
349 CounterPtr->setSection(getCountersSection());
350 CounterPtr->setAlignment(8);
351 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000352
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000353 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000354 // 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.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000379 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000380 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000381 Type *DataTypes[] = {
382 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
383 #include "llvm/ProfileData/InstrProfData.inc"
384 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000385 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000386
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000387 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000395 Constant *DataVals[] = {
Xinliang David Li192c7482015-11-05 00:47:26 +0000396 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
397 #include "llvm/ProfileData/InstrProfData.inc"
398 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000399 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000400 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000401 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000402 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000403 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000404 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000405 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000406
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000407 PD.RegionCounters = CounterPtr;
408 PD.DataVar = Data;
409 ProfileDataMap[NamePtr] = PD;
410
Justin Bogner61ba2e32014-12-08 18:02:35 +0000411 // Mark the data variable as used so that it isn't stripped out.
412 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000413 // 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);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000419
Xinliang David Li192c7482015-11-05 00:47:26 +0000420 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000421}
422
Xinliang David Lib628dd32016-05-21 22:55:34 +0000423void InstrProfiling::emitVNodes() {
424 if (!ValueProfileStaticAlloc)
425 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000426
Xinliang David Lib628dd32016-05-21 22:55:34 +0000427 // 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;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000432
Xinliang David Lib628dd32016-05-21 22:55:34 +0000433 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.
Xinliang David Lie4520762016-05-23 19:29:26 +0000450#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);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000453
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);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000467}
468
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000469void InstrProfiling::emitNameData() {
470 std::string UncompressedData;
471
472 if (ReferencedNames.empty())
473 return;
474
475 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000476 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000477 DoNameCompression)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000478 llvm::report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000479 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000480
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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000492void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000493 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000494 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000495
Justin Bogner61ba2e32014-12-08 18:02:35 +0000496 // Construct the function.
497 auto *VoidTy = Type::getVoidTy(M->getContext());
498 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000499 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000500 auto *RegisterFTy = FunctionType::get(VoidTy, false);
501 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000502 getInstrProfRegFuncsName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000503 RegisterF->setUnnamedAddr(true);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000504 if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000505
Diego Novillob3029d22015-06-04 11:45:32 +0000506 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000507 auto *RuntimeRegisterF =
508 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000509 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000510
511 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
512 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000513 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000527 IRB.CreateRetVoid();
528}
529
530void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000531
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000532 // 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000537 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000538 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000539
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,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000544 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000545
546 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000547 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
548 GlobalValue::LinkOnceODRLinkage,
549 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000550 User->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000551 if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000552 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000553 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000554 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000555
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
564void InstrProfiling::emitUses() {
565 if (UsedVars.empty())
566 return;
567
568 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000569 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000570 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(
Diego Novillob3029d22015-06-04 11:45:32 +0000582 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000583
584 // Recreate llvm.used.
585 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000586 LLVMUsed =
587 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
588 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000589 LLVMUsed->setSection("llvm.metadata");
590}
591
592void InstrProfiling::emitInitialization() {
Justin Bognerba1900c2015-04-30 23:49:23 +0000593 std::string InstrProfileOutput = Options.InstrProfileOutput;
594
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000595 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
596 if (!RegisterF && InstrProfileOutput.empty()) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000597
598 // Create the initialization function.
599 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000600 auto *F = Function::Create(FunctionType::get(VoidTy, false),
601 GlobalValue::InternalLinkage,
602 getInstrProfInitFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000603 F->setUnnamedAddr(true);
604 F->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000605 if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000606
607 // Add the basic block and the necessary calls.
608 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000609 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000610 IRB.CreateCall(RegisterF, {});
Justin Bognerba1900c2015-04-30 23:49:23 +0000611 if (!InstrProfileOutput.empty()) {
612 auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
613 auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000614 auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
615 getInstrProfFileOverriderFuncName(), M);
Justin Bognerba1900c2015-04-30 23:49:23 +0000616
Diego Novillob0257c82015-06-29 20:03:46 +0000617 // Create variable for profile name.
Justin Bognerba1900c2015-04-30 23:49:23 +0000618 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 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000626 IRB.CreateRetVoid();
627
628 appendToGlobalCtors(*M, F, 0);
629}