blob: f2c19328ff120a3187bda0bd72fe43e9417dcae5 [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
Xinliang David Li69a00f02016-06-21 02:39:08 +000016#include "llvm/Transforms/InstrProfiling.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000020#include "llvm/ADT/Triple.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000021#include "llvm/ADT/Twine.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000023#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"
Justin Bogner61ba2e32014-12-08 18:02:35 +000033#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include "llvm/IR/IRBuilder.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000035#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000036#include "llvm/IR/Type.h"
37#include "llvm/Pass.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000038#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000039#include "llvm/Support/Casting.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Error.h"
42#include "llvm/Support/ErrorHandling.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000043#include "llvm/Transforms/Utils/ModuleUtils.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000044#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000049
50using namespace llvm;
51
52#define DEBUG_TYPE "instrprof"
53
54namespace {
55
Xinliang David Lia82d6c02016-02-08 18:13:49 +000056cl::opt<bool> DoNameCompression("enable-name-compression",
57 cl::desc("Enable name string compression"),
58 cl::init(true));
59
Rong Xu20f5df12017-01-11 20:19:41 +000060cl::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
Xinliang David Lib628dd32016-05-21 22:55:34 +000065cl::opt<bool> ValueProfileStaticAlloc(
66 "vp-static-alloc",
67 cl::desc("Do static counter allocation for value profiler"),
68 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000069
Xinliang David Lib628dd32016-05-21 22:55:34 +000070cl::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
Rong Xu60faea12017-03-16 21:15:48 +000080cl::opt<std::string> MemOPSizeRange(
81 "memop-size-range",
82 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
83 "precisely, in a format of <start_val>:<end_val>"),
84 cl::init(""));
85cl::opt<unsigned> MemOPSizeLarge(
86 "memop-size-large",
87 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
88 "Value of 0 disables the large value profiling."),
89 cl::init(8192));
90
Xinliang David Lie6b89292016-04-18 17:47:38 +000091class InstrProfilingLegacyPass : public ModulePass {
92 InstrProfiling InstrProf;
93
Justin Bogner61ba2e32014-12-08 18:02:35 +000094public:
95 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +000096
97 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +000098 InstrProfilingLegacyPass(const InstrProfOptions &Options)
99 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000100
Mehdi Amini117296c2016-10-01 02:56:57 +0000101 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000102 return "Frontend instrumentation-based coverage lowering";
103 }
104
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000105 bool runOnModule(Module &M) override {
106 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
107 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000108
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000111 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000112 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000113};
114
Eugene Zelenko34c23272017-01-18 00:57:48 +0000115} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000116
Sean Silvafd03ac62016-08-09 00:28:38 +0000117PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000118 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
119 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000120 return PreservedAnalyses::all();
121
122 return PreservedAnalyses::none();
123}
124
125char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000126INITIALIZE_PASS_BEGIN(
127 InstrProfilingLegacyPass, "instrprof",
128 "Frontend instrumentation-based coverage lowering.", false, false)
129INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
130INITIALIZE_PASS_END(
131 InstrProfilingLegacyPass, "instrprof",
132 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000133
Xinliang David Li69a00f02016-06-21 02:39:08 +0000134ModulePass *
135llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000136 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000137}
138
Xinliang David Lie6b89292016-04-18 17:47:38 +0000139bool InstrProfiling::isMachO() const {
140 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
141}
142
143/// Get the section name for the counter variables.
144StringRef InstrProfiling::getCountersSection() const {
145 return getInstrProfCountersSectionName(isMachO());
146}
147
148/// Get the section name for the name variables.
149StringRef InstrProfiling::getNameSection() const {
150 return getInstrProfNameSectionName(isMachO());
151}
152
153/// Get the section name for the profile data variables.
154StringRef InstrProfiling::getDataSection() const {
155 return getInstrProfDataSectionName(isMachO());
156}
157
158/// Get the section name for the coverage mapping data.
159StringRef InstrProfiling::getCoverageSection() const {
160 return getInstrProfCoverageSectionName(isMachO());
161}
162
Xinliang David Li4ca17332016-09-18 18:34:07 +0000163static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
164 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
165 if (Inc)
166 return Inc;
167 return dyn_cast<InstrProfIncrementInst>(Instr);
168}
169
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000170bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000171 bool MadeChange = false;
172
173 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000174 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000175 NamesVar = nullptr;
176 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000177 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000178 UsedVars.clear();
Rong Xu60faea12017-03-16 21:15:48 +0000179 getMemOPSizeOptions();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000180
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000181 // We did not know how many value sites there would be inside
182 // the instrumented function. This is counting the number of instrumented
183 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000184 for (Function &F : M) {
185 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000186 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000187 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
188 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000189 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000190 else if (FirstProfIncInst == nullptr)
191 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
192
193 // Value profiling intrinsic lowering requires per-function profile data
194 // variable to be created first.
195 if (FirstProfIncInst != nullptr)
196 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
197 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000198
199 for (Function &F : M)
200 for (BasicBlock &BB : F)
201 for (auto I = BB.begin(), E = BB.end(); I != E;) {
202 auto Instr = I++;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000203 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
204 if (Inc) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000205 lowerIncrement(Inc);
206 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000207 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
208 lowerValueProfileInst(Ind);
209 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000210 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000211 }
212
Xinliang David Li81056072016-01-07 20:05:49 +0000213 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000214 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000215 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000216 MadeChange = true;
217 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000218
Justin Bogner61ba2e32014-12-08 18:02:35 +0000219 if (!MadeChange)
220 return false;
221
Xinliang David Lib628dd32016-05-21 22:55:34 +0000222 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000223 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000224 emitRegistration();
225 emitRuntimeHook();
226 emitUses();
227 emitInitialization();
228 return true;
229}
230
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000231static Constant *getOrInsertValueProfilingCall(Module &M,
Rong Xu60faea12017-03-16 21:15:48 +0000232 const TargetLibraryInfo &TLI,
233 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000234 LLVMContext &Ctx = M.getContext();
235 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000236
237 Constant *Res;
238 if (!IsRange) {
239 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000240#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
241#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000242 };
243 auto *ValueProfilingCallTy =
244 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
245 Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
246 ValueProfilingCallTy);
247 } else {
248 Type *RangeParamTypes[] = {
249#define VALUE_RANGE_PROF 1
250#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
251#include "llvm/ProfileData/InstrProfData.inc"
252#undef VALUE_RANGE_PROF
253 };
254 auto *ValueRangeProfilingCallTy =
255 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
256 Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
257 ValueRangeProfilingCallTy);
258 }
259
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000260 if (Function *FunRes = dyn_cast<Function>(Res)) {
261 if (auto AK = TLI.getExtAttrForI32Param(false))
262 FunRes->addAttribute(3, AK);
263 }
264 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000265}
266
267void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000268 GlobalVariable *Name = Ind->getName();
269 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
270 uint64_t Index = Ind->getIndex()->getZExtValue();
271 auto It = ProfileDataMap.find(Name);
272 if (It == ProfileDataMap.end()) {
273 PerFunctionProfileData PD;
274 PD.NumValueSites[ValueKind] = Index + 1;
275 ProfileDataMap[Name] = PD;
276 } else if (It->second.NumValueSites[ValueKind] <= Index)
277 It->second.NumValueSites[ValueKind] = Index + 1;
278}
279
280void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000281 GlobalVariable *Name = Ind->getName();
282 auto It = ProfileDataMap.find(Name);
283 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000284 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000285
286 GlobalVariable *DataVar = It->second.DataVar;
287 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
288 uint64_t Index = Ind->getIndex()->getZExtValue();
289 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
290 Index += It->second.NumValueSites[Kind];
291
292 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000293 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
294 llvm::InstrProfValueKind::IPVK_MemOPSize);
295 CallInst *Call = nullptr;
296 if (!IsRange) {
297 Value *Args[3] = {Ind->getTargetValue(),
298 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
299 Builder.getInt32(Index)};
300 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
301 } else {
302 Value *Args[6] = {Ind->getTargetValue(),
303 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
304 Builder.getInt32(Index),
305 Builder.getInt64(MemOPSizeRangeStart),
306 Builder.getInt64(MemOPSizeRangeLast),
307 Builder.getInt64(MemOPSizeLargeVal)};
308 Call =
309 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
310 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000311 if (auto AK = TLI->getExtAttrForI32Param(false))
312 Call->addAttribute(3, AK);
313 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000314 Ind->eraseFromParent();
315}
316
Justin Bogner61ba2e32014-12-08 18:02:35 +0000317void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
318 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
319
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000320 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000321 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000322 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
323 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Xinliang David Lia754c472016-09-20 19:07:22 +0000324 Count = Builder.CreateAdd(Count, Inc->getStep());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000325 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
326 Inc->eraseFromParent();
327}
328
Xinliang David Li81056072016-01-07 20:05:49 +0000329void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000330 ConstantArray *Names =
331 cast<ConstantArray>(CoverageNamesVar->getInitializer());
332 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
333 Constant *NC = Names->getOperand(I);
334 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000335 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
336 GlobalVariable *Name = cast<GlobalVariable>(V);
337
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000338 Name->setLinkage(GlobalValue::PrivateLinkage);
339 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000340 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000341 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000342 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000343}
344
Justin Bogner61ba2e32014-12-08 18:02:35 +0000345/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000346static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000347 StringRef NamePrefix = getInstrProfNameVarPrefix();
348 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000349 Function *F = Inc->getParent()->getParent();
350 Module *M = F->getParent();
351 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
352 !canRenameComdatFunc(*F))
353 return (Prefix + Name).str();
354 uint64_t FuncHash = Inc->getHash()->getZExtValue();
355 SmallVector<char, 24> HashPostfix;
356 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
357 return (Prefix + Name).str();
358 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000359}
360
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000361static inline bool shouldRecordFunctionAddr(Function *F) {
362 // Check the linkage
363 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
364 !F->hasAvailableExternallyLinkage())
365 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000366 // Prohibit function address recording if the function is both internal and
367 // COMDAT. This avoids the profile data variable referencing internal symbols
368 // in COMDAT.
369 if (F->hasLocalLinkage() && F->hasComdat())
370 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000371 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000372 // Inline virtual functions have linkeOnceODR linkage. When a key method
373 // exists, the vtable will only be emitted in the TU where the key method
374 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000375 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000376 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000377 // indirect call target info.
378 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000379}
380
Xinliang David Li985ff202016-02-27 23:11:30 +0000381static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000382 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000383 if (!needsComdatForCounter(F, M))
384 return nullptr;
385
Xinliang David Liab361ef2015-12-21 21:52:27 +0000386 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000387 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000388 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000389 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000390 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000391 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000392 : getInstrProfComdatPrefix());
393 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
394}
395
Xinliang David Lib628dd32016-05-21 22:55:34 +0000396static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
397 // Don't do this for Darwin. compiler-rt uses linker magic.
398 if (Triple(M.getTargetTriple()).isOSDarwin())
399 return false;
400
401 // Use linker script magic to get data/cnts/name start/end.
402 if (Triple(M.getTargetTriple()).isOSLinux() ||
403 Triple(M.getTargetTriple()).isOSFreeBSD() ||
404 Triple(M.getTargetTriple()).isPS4CPU())
405 return false;
406
407 return true;
408}
409
Justin Bogner61ba2e32014-12-08 18:02:35 +0000410GlobalVariable *
411InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000412 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000413 auto It = ProfileDataMap.find(NamePtr);
414 PerFunctionProfileData PD;
415 if (It != ProfileDataMap.end()) {
416 if (It->second.RegionCounters)
417 return It->second.RegionCounters;
418 PD = It->second;
419 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000420
Wei Mi3cc92042015-09-23 22:40:45 +0000421 // Move the name variable to the right section. Place them in a COMDAT group
422 // if the associated function is a COMDAT. This will make sure that
423 // only one copy of counters of the COMDAT function will be emitted after
424 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000425 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000426 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000427 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000428
429 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
430 LLVMContext &Ctx = M->getContext();
431 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
432
433 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000434 auto *CounterPtr =
435 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000436 Constant::getNullValue(CounterTy),
437 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000438 CounterPtr->setVisibility(NamePtr->getVisibility());
439 CounterPtr->setSection(getCountersSection());
440 CounterPtr->setAlignment(8);
441 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000442
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000443 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000444 // Allocate statically the array of pointers to value profile nodes for
445 // the current function.
446 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
447 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000448 uint64_t NS = 0;
449 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
450 NS += PD.NumValueSites[Kind];
451 if (NS) {
452 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
453
454 auto *ValuesVar =
455 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
456 Constant::getNullValue(ValuesTy),
457 getVarName(Inc, getInstrProfValuesVarPrefix()));
458 ValuesVar->setVisibility(NamePtr->getVisibility());
459 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
460 ValuesVar->setAlignment(8);
461 ValuesVar->setComdat(ProfileVarsComdat);
462 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000463 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000464 }
465 }
466
467 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000468 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000469 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000470 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000471#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
472#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000473 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000474 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000475
Xinliang David Li69a00f02016-06-21 02:39:08 +0000476 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
477 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
478 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000479
Xinliang David Li69a00f02016-06-21 02:39:08 +0000480 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000481 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
482 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
483
Justin Bogner61ba2e32014-12-08 18:02:35 +0000484 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000485#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
486#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000487 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000488 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000489 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000490 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000491 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000492 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000493 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000494 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000495
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000496 PD.RegionCounters = CounterPtr;
497 PD.DataVar = Data;
498 ProfileDataMap[NamePtr] = PD;
499
Justin Bogner61ba2e32014-12-08 18:02:35 +0000500 // Mark the data variable as used so that it isn't stripped out.
501 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000502 // Now that the linkage set by the FE has been passed to the data and counter
503 // variables, reset Name variable's linkage and visibility to private so that
504 // it can be removed later by the compiler.
505 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
506 // Collect the referenced names to be used by emitNameData.
507 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000508
Xinliang David Li192c7482015-11-05 00:47:26 +0000509 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000510}
511
Xinliang David Lib628dd32016-05-21 22:55:34 +0000512void InstrProfiling::emitVNodes() {
513 if (!ValueProfileStaticAlloc)
514 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000515
Xinliang David Lib628dd32016-05-21 22:55:34 +0000516 // For now only support this on platforms that do
517 // not require runtime registration to discover
518 // named section start/end.
519 if (needsRuntimeRegistrationOfSectionRange(*M))
520 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000521
Xinliang David Lib628dd32016-05-21 22:55:34 +0000522 size_t TotalNS = 0;
523 for (auto &PD : ProfileDataMap) {
524 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
525 TotalNS += PD.second.NumValueSites[Kind];
526 }
527
528 if (!TotalNS)
529 return;
530
531 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000532// Heuristic for small programs with very few total value sites.
533// The default value of vp-counters-per-site is chosen based on
534// the observation that large apps usually have a low percentage
535// of value sites that actually have any profile data, and thus
536// the average number of counters per site is low. For small
537// apps with very few sites, this may not be true. Bump up the
538// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000539#define INSTR_PROF_MIN_VAL_COUNTS 10
540 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000541 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000542
543 auto &Ctx = M->getContext();
544 Type *VNodeTypes[] = {
545#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
546#include "llvm/ProfileData/InstrProfData.inc"
547 };
548 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
549
550 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
551 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000552 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000553 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
554 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
555 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000556}
557
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000558void InstrProfiling::emitNameData() {
559 std::string UncompressedData;
560
561 if (ReferencedNames.empty())
562 return;
563
564 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000565 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000566 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000567 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000568 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000569
570 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000571 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000572 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000573 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
574 GlobalValue::PrivateLinkage, NamesVal,
575 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000576 NamesSize = CompressedNameStr.size();
577 NamesVar->setSection(getNameSection());
578 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000579
580 for (auto *NamePtr : ReferencedNames)
581 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000582}
583
Justin Bogner61ba2e32014-12-08 18:02:35 +0000584void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000585 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000586 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000587
Justin Bogner61ba2e32014-12-08 18:02:35 +0000588 // Construct the function.
589 auto *VoidTy = Type::getVoidTy(M->getContext());
590 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000591 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000592 auto *RegisterFTy = FunctionType::get(VoidTy, false);
593 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000594 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000595 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000596 if (Options.NoRedZone)
597 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000598
Diego Novillob3029d22015-06-04 11:45:32 +0000599 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000600 auto *RuntimeRegisterF =
601 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000602 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000603
604 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
605 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000606 if (Data != NamesVar)
607 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
608
609 if (NamesVar) {
610 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
611 auto *NamesRegisterTy =
612 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
613 auto *NamesRegisterF =
614 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
615 getInstrProfNamesRegFuncName(), M);
616 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
617 IRB.getInt64(NamesSize)});
618 }
619
Justin Bogner61ba2e32014-12-08 18:02:35 +0000620 IRB.CreateRetVoid();
621}
622
623void InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000624 // We expect the linker to be invoked with -u<hook_var> flag for linux,
625 // for which case there is no need to emit the user function.
626 if (Triple(M->getTargetTriple()).isOSLinux())
627 return;
628
Justin Bogner61ba2e32014-12-08 18:02:35 +0000629 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000630 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
631 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000632
633 // Declare an external variable that will pull in the runtime initialization.
634 auto *Int32Ty = Type::getInt32Ty(M->getContext());
635 auto *Var =
636 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000637 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000638
639 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000640 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
641 GlobalValue::LinkOnceODRLinkage,
642 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000643 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000644 if (Options.NoRedZone)
645 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000646 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000647 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000648 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000649
650 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
651 auto *Load = IRB.CreateLoad(Var);
652 IRB.CreateRet(Load);
653
654 // Mark the user variable as used so that it isn't stripped out.
655 UsedVars.push_back(User);
656}
657
658void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000659 if (!UsedVars.empty())
660 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000661}
662
663void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000664 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000665
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000666 if (!InstrProfileOutput.empty()) {
667 // Create variable for profile name.
668 Constant *ProfileNameConst =
669 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
670 GlobalVariable *ProfileNameVar = new GlobalVariable(
671 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
672 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
673 Triple TT(M->getTargetTriple());
674 if (TT.supportsCOMDAT()) {
675 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
676 ProfileNameVar->setComdat(M->getOrInsertComdat(
677 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
678 }
679 }
680
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000681 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000682 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000683 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000684
685 // Create the initialization function.
686 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000687 auto *F = Function::Create(FunctionType::get(VoidTy, false),
688 GlobalValue::InternalLinkage,
689 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000690 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000691 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000692 if (Options.NoRedZone)
693 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000694
695 // Add the basic block and the necessary calls.
696 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000697 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000698 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000699 IRB.CreateRetVoid();
700
701 appendToGlobalCtors(*M, F, 0);
702}
Rong Xu60faea12017-03-16 21:15:48 +0000703
704void InstrProfiling::getMemOPSizeOptions() {
705 // Parse the value profile options.
706 MemOPSizeRangeStart = DefaultMemOPSizeRangeStart;
707 MemOPSizeRangeLast = DefaultMemOPSizeRangeLast;
708 if (!MemOPSizeRange.empty()) {
709 auto Pos = MemOPSizeRange.find(":");
710 if (Pos != std::string::npos) {
711 if (Pos > 0)
712 MemOPSizeRangeStart = atoi(MemOPSizeRange.substr(0, Pos).c_str());
713 if (Pos < MemOPSizeRange.size() - 1)
714 MemOPSizeRangeLast = atoi(MemOPSizeRange.substr(Pos + 1).c_str());
715 } else
716 MemOPSizeRangeLast = atoi(MemOPSizeRange.c_str());
717 }
718 assert(MemOPSizeRangeLast >= MemOPSizeRangeStart);
719
720 MemOPSizeLargeVal = MemOPSizeLarge;
721 if (MemOPSizeLargeVal == 0)
722 MemOPSizeLargeVal = INT64_MIN;
723}