334c41f3abc2287e59b3218c04e38cac0c24894a
[oota-llvm.git] / lib / Transforms / Instrumentation / InstrProfiling.cpp
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/Instrumentation.h"
22 #include "llvm/Transforms/Utils/ModuleUtils.h"
23
24 using namespace llvm;
25
26 #define DEBUG_TYPE "instrprof"
27
28 namespace {
29
30 class InstrProfiling : public ModulePass {
31 public:
32   static char ID;
33
34   InstrProfiling() : ModulePass(ID) {}
35
36   InstrProfiling(const InstrProfOptions &Options)
37       : ModulePass(ID), Options(Options) {}
38
39   const char *getPassName() const override {
40     return "Frontend instrumentation-based coverage lowering";
41   }
42
43   bool runOnModule(Module &M) override;
44
45   void getAnalysisUsage(AnalysisUsage &AU) const override {
46     AU.setPreservesCFG();
47   }
48
49 private:
50   InstrProfOptions Options;
51   Module *M;
52   typedef struct PerFunctionProfileData {
53     uint32_t NumValueSites[IPVK_Last+1];
54     GlobalVariable* RegionCounters;
55     GlobalVariable* DataVar;
56     PerFunctionProfileData() : RegionCounters(nullptr), DataVar(nullptr) {
57       memset(NumValueSites, 0, sizeof(uint32_t) * (IPVK_Last+1));
58     }
59   } PerFunctionProfileData;
60   DenseMap<GlobalVariable *, PerFunctionProfileData> ProfileDataMap;
61   std::vector<Value *> UsedVars;
62
63   bool isMachO() const {
64     return Triple(M->getTargetTriple()).isOSBinFormatMachO();
65   }
66
67   /// Get the section name for the counter variables.
68   StringRef getCountersSection() const {
69     return getInstrProfCountersSectionName(isMachO());
70   }
71
72   /// Get the section name for the name variables.
73   StringRef getNameSection() const {
74     return getInstrProfNameSectionName(isMachO());
75   }
76
77   /// Get the section name for the profile data variables.
78   StringRef getDataSection() const {
79     return getInstrProfDataSectionName(isMachO());
80   }
81
82   /// Get the section name for the coverage mapping data.
83   StringRef getCoverageSection() const {
84     return getInstrProfCoverageSectionName(isMachO());
85   }
86
87   /// Count the number of instrumented value sites for the function.
88   void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
89
90   /// Replace instrprof_value_profile with a call to runtime library.
91   void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
92
93   /// Replace instrprof_increment with an increment of the appropriate value.
94   void lowerIncrement(InstrProfIncrementInst *Inc);
95
96   /// Set up the section and uses for coverage data and its references.
97   void lowerCoverageData(GlobalVariable *CoverageData);
98
99   /// Get the region counters for an increment, creating them if necessary.
100   ///
101   /// If the counter array doesn't yet exist, the profile data variables
102   /// referring to them will also be created.
103   GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
104
105   /// Emit runtime registration functions for each profile data variable.
106   void emitRegistration();
107
108   /// Emit the necessary plumbing to pull in the runtime initialization.
109   void emitRuntimeHook();
110
111   /// Add uses of our data variables and runtime hook.
112   void emitUses();
113
114   /// Create a static initializer for our data, on platforms that need it,
115   /// and for any profile output file that was specified.
116   void emitInitialization();
117 };
118
119 } // anonymous namespace
120
121 char InstrProfiling::ID = 0;
122 INITIALIZE_PASS(InstrProfiling, "instrprof",
123                 "Frontend instrumentation-based coverage lowering.", false,
124                 false)
125
126 ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
127   return new InstrProfiling(Options);
128 }
129
130 bool InstrProfiling::runOnModule(Module &M) {
131   bool MadeChange = false;
132
133   this->M = &M;
134   ProfileDataMap.clear();
135   UsedVars.clear();
136
137   // We did not know how many value sites there would be inside
138   // the instrumented function. This is counting the number of instrumented
139   // target value sites to enter it as field in the profile data variable.
140   for (Function &F : M)
141     for (BasicBlock &BB : F)
142       for (auto I = BB.begin(), E = BB.end(); I != E;)
143         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I++))
144           computeNumValueSiteCounts(Ind);
145
146   for (Function &F : M)
147     for (BasicBlock &BB : F)
148       for (auto I = BB.begin(), E = BB.end(); I != E;) {
149         auto Instr = I++;
150         if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) {
151           lowerIncrement(Inc);
152           MadeChange = true;
153         } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
154           lowerValueProfileInst(Ind);
155           MadeChange = true;
156         }
157       }
158
159   if (GlobalVariable *Coverage =
160           M.getNamedGlobal(getCoverageMappingVarName())) {
161     lowerCoverageData(Coverage);
162     MadeChange = true;
163   }
164
165   if (!MadeChange)
166     return false;
167
168   emitRegistration();
169   emitRuntimeHook();
170   emitUses();
171   emitInitialization();
172   return true;
173 }
174
175 static Constant *getOrInsertValueProfilingCall(Module &M) {
176   auto *VoidTy = Type::getVoidTy(M.getContext());
177   auto *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
178   auto *Int32Ty = Type::getInt32Ty(M.getContext());
179   auto *Int64Ty = Type::getInt64Ty(M.getContext());
180   Type *ArgTypes[] = {Int64Ty, VoidPtrTy, Int32Ty};
181   auto *ValueProfilingCallTy =
182       FunctionType::get(VoidTy, makeArrayRef(ArgTypes), false);
183   return M.getOrInsertFunction("__llvm_profile_instrument_target",
184                                ValueProfilingCallTy);
185 }
186
187 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
188
189   GlobalVariable *Name = Ind->getName();
190   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
191   uint64_t Index = Ind->getIndex()->getZExtValue();
192   auto It = ProfileDataMap.find(Name);
193   if (It == ProfileDataMap.end()) {
194     PerFunctionProfileData PD;
195     PD.NumValueSites[ValueKind] = Index + 1;
196     ProfileDataMap[Name] = PD;
197   } else if (It->second.NumValueSites[ValueKind] <= Index)
198     It->second.NumValueSites[ValueKind] = Index + 1;
199 }
200
201 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
202
203   GlobalVariable *Name = Ind->getName();
204   auto It = ProfileDataMap.find(Name);
205   assert(It != ProfileDataMap.end() && It->second.DataVar &&
206     "value profiling detected in function with no counter incerement");
207
208   GlobalVariable *DataVar = It->second.DataVar;
209   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
210   uint64_t Index = Ind->getIndex()->getZExtValue();
211   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
212     Index += It->second.NumValueSites[Kind];
213
214   IRBuilder<> Builder(Ind);
215   Value* Args[3] = {Ind->getTargetValue(),
216       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
217       Builder.getInt32(Index)};
218   Ind->replaceAllUsesWith(
219       Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
220   Ind->eraseFromParent();
221 }
222
223 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
224   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
225
226   IRBuilder<> Builder(Inc);
227   uint64_t Index = Inc->getIndex()->getZExtValue();
228   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
229   Value *Count = Builder.CreateLoad(Addr, "pgocount");
230   Count = Builder.CreateAdd(Count, Builder.getInt64(1));
231   Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
232   Inc->eraseFromParent();
233 }
234
235 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
236   CoverageData->setSection(getCoverageSection());
237   CoverageData->setAlignment(8);
238
239   Constant *Init = CoverageData->getInitializer();
240   // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
241   // for some C. If not, the frontend's given us something broken.
242   assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
243   assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
244          "invalid function list in coverage map");
245   ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
246   for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
247     Constant *Record = Records->getOperand(I);
248     Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
249
250     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
251     GlobalVariable *Name = cast<GlobalVariable>(V);
252
253     // If we have region counters for this name, we've already handled it.
254     auto It = ProfileDataMap.find(Name);
255     if (It != ProfileDataMap.end())
256       if (It->second.RegionCounters)
257         continue;
258
259     // Move the name variable to the right section.
260     Name->setSection(getNameSection());
261     Name->setAlignment(1);
262   }
263 }
264
265 /// Get the name of a profiling variable for a particular function.
266 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
267   auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
268   StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
269   return (Prefix + Name).str();
270 }
271
272 static inline bool shouldRecordFunctionAddr(Function *F) {
273   // Check the linkage
274   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
275       !F->hasAvailableExternallyLinkage())
276     return true;
277   // Check uses of this function for other than direct calls or invokes to it.
278   return F->hasAddressTaken();
279 }
280
281 GlobalVariable *
282 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
283   GlobalVariable *NamePtr = Inc->getName();
284   auto It = ProfileDataMap.find(NamePtr);
285   PerFunctionProfileData PD;
286   if (It != ProfileDataMap.end()) {
287     if (It->second.RegionCounters)
288       return It->second.RegionCounters;
289     PD = It->second;
290   }
291
292   // Move the name variable to the right section. Place them in a COMDAT group
293   // if the associated function is a COMDAT. This will make sure that
294   // only one copy of counters of the COMDAT function will be emitted after
295   // linking.
296   Function *Fn = Inc->getParent()->getParent();
297   Comdat *ProfileVarsComdat = nullptr;
298   if (Fn->hasComdat())
299     ProfileVarsComdat = M->getOrInsertComdat(
300         StringRef(getVarName(Inc, getInstrProfComdatPrefix())));
301   NamePtr->setSection(getNameSection());
302   NamePtr->setAlignment(1);
303   NamePtr->setComdat(ProfileVarsComdat);
304
305   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
306   LLVMContext &Ctx = M->getContext();
307   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
308
309   // Create the counters variable.
310   auto *CounterPtr =
311       new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
312                          Constant::getNullValue(CounterTy),
313                          getVarName(Inc, getInstrProfCountersVarPrefix()));
314   CounterPtr->setVisibility(NamePtr->getVisibility());
315   CounterPtr->setSection(getCountersSection());
316   CounterPtr->setAlignment(8);
317   CounterPtr->setComdat(ProfileVarsComdat);
318
319   // Create data variable.
320   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
321   auto *Int16Ty = Type::getInt16Ty(Ctx);
322   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last+1);
323   Type *DataTypes[] = {
324     #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
325     #include "llvm/ProfileData/InstrProfData.inc"
326   };
327   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
328
329   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn) ?
330                            ConstantExpr::getBitCast(Fn, Int8PtrTy) :
331                            ConstantPointerNull::get(Int8PtrTy);
332
333   Constant *Int16ArrayVals[IPVK_Last+1];
334   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
335     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
336
337   Constant *DataVals[] = {
338     #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
339     #include "llvm/ProfileData/InstrProfData.inc"
340   };
341   auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
342                                   ConstantStruct::get(DataTy, DataVals),
343                                   getVarName(Inc, getInstrProfDataVarPrefix()));
344   Data->setVisibility(NamePtr->getVisibility());
345   Data->setSection(getDataSection());
346   Data->setAlignment(8);
347   Data->setComdat(ProfileVarsComdat);
348
349   PD.RegionCounters = CounterPtr;
350   PD.DataVar = Data;
351   ProfileDataMap[NamePtr] = PD;
352
353   // Mark the data variable as used so that it isn't stripped out.
354   UsedVars.push_back(Data);
355
356   return CounterPtr;
357 }
358
359 void InstrProfiling::emitRegistration() {
360   // Don't do this for Darwin.  compiler-rt uses linker magic.
361   if (Triple(M->getTargetTriple()).isOSDarwin())
362     return;
363
364   // Use linker script magic to get data/cnts/name start/end.
365   if (Triple(M->getTargetTriple()).isOSLinux() ||
366       Triple(M->getTargetTriple()).isOSFreeBSD())
367     return;
368
369   // Construct the function.
370   auto *VoidTy = Type::getVoidTy(M->getContext());
371   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
372   auto *RegisterFTy = FunctionType::get(VoidTy, false);
373   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
374                                      getInstrProfRegFuncsName(), M);
375   RegisterF->setUnnamedAddr(true);
376   if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
377
378   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
379   auto *RuntimeRegisterF =
380       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
381                        getInstrProfRegFuncName(), M);
382
383   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
384   for (Value *Data : UsedVars)
385     IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
386   IRB.CreateRetVoid();
387 }
388
389 void InstrProfiling::emitRuntimeHook() {
390
391   // We expect the linker to be invoked with -u<hook_var> flag for linux,
392   // for which case there is no need to emit the user function.
393   if (Triple(M->getTargetTriple()).isOSLinux())
394     return;
395
396   // If the module's provided its own runtime, we don't need to do anything.
397   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
398
399   // Declare an external variable that will pull in the runtime initialization.
400   auto *Int32Ty = Type::getInt32Ty(M->getContext());
401   auto *Var =
402       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
403                          nullptr, getInstrProfRuntimeHookVarName());
404
405   // Make a function that uses it.
406   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
407                                 GlobalValue::LinkOnceODRLinkage,
408                                 getInstrProfRuntimeHookVarUseFuncName(), M);
409   User->addFnAttr(Attribute::NoInline);
410   if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
411   User->setVisibility(GlobalValue::HiddenVisibility);
412
413   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
414   auto *Load = IRB.CreateLoad(Var);
415   IRB.CreateRet(Load);
416
417   // Mark the user variable as used so that it isn't stripped out.
418   UsedVars.push_back(User);
419 }
420
421 void InstrProfiling::emitUses() {
422   if (UsedVars.empty())
423     return;
424
425   GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
426   std::vector<Constant *> MergedVars;
427   if (LLVMUsed) {
428     // Collect the existing members of llvm.used.
429     ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
430     for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
431       MergedVars.push_back(Inits->getOperand(I));
432     LLVMUsed->eraseFromParent();
433   }
434
435   Type *i8PTy = Type::getInt8PtrTy(M->getContext());
436   // Add uses for our data.
437   for (auto *Value : UsedVars)
438     MergedVars.push_back(
439         ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
440
441   // Recreate llvm.used.
442   ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
443   LLVMUsed =
444       new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
445                          ConstantArray::get(ATy, MergedVars), "llvm.used");
446   LLVMUsed->setSection("llvm.metadata");
447 }
448
449 void InstrProfiling::emitInitialization() {
450   std::string InstrProfileOutput = Options.InstrProfileOutput;
451
452   Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
453   if (!RegisterF && InstrProfileOutput.empty()) return;
454
455   // Create the initialization function.
456   auto *VoidTy = Type::getVoidTy(M->getContext());
457   auto *F = Function::Create(FunctionType::get(VoidTy, false),
458                              GlobalValue::InternalLinkage,
459                              getInstrProfInitFuncName(), M);
460   F->setUnnamedAddr(true);
461   F->addFnAttr(Attribute::NoInline);
462   if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
463
464   // Add the basic block and the necessary calls.
465   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
466   if (RegisterF)
467     IRB.CreateCall(RegisterF, {});
468   if (!InstrProfileOutput.empty()) {
469     auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
470     auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
471     auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
472                                       getInstrProfFileOverriderFuncName(), M);
473
474     // Create variable for profile name.
475     Constant *ProfileNameConst =
476         ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
477     GlobalVariable *ProfileName =
478         new GlobalVariable(*M, ProfileNameConst->getType(), true,
479                            GlobalValue::PrivateLinkage, ProfileNameConst);
480
481     IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
482   }
483   IRB.CreateRetVoid();
484
485   appendToGlobalCtors(*M, F, 0);
486 }