blob: be5c2c711f0e462cb284a78c99200147ca3ecd93 [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
Xinliang David Lie6b89292016-04-18 17:47:38 +000080class InstrProfilingLegacyPass : public ModulePass {
81 InstrProfiling InstrProf;
82
Justin Bogner61ba2e32014-12-08 18:02:35 +000083public:
84 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +000085
86 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +000087 InstrProfilingLegacyPass(const InstrProfOptions &Options)
88 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +000089
Mehdi Amini117296c2016-10-01 02:56:57 +000090 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +000091 return "Frontend instrumentation-based coverage lowering";
92 }
93
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000094 bool runOnModule(Module &M) override {
95 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
96 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000097
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000100 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000101 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000102};
103
Eugene Zelenko34c23272017-01-18 00:57:48 +0000104} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000105
Sean Silvafd03ac62016-08-09 00:28:38 +0000106PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000107 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
108 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000109 return PreservedAnalyses::all();
110
111 return PreservedAnalyses::none();
112}
113
114char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000115INITIALIZE_PASS_BEGIN(
116 InstrProfilingLegacyPass, "instrprof",
117 "Frontend instrumentation-based coverage lowering.", false, false)
118INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
119INITIALIZE_PASS_END(
120 InstrProfilingLegacyPass, "instrprof",
121 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000122
Xinliang David Li69a00f02016-06-21 02:39:08 +0000123ModulePass *
124llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000125 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000126}
127
Xinliang David Lie6b89292016-04-18 17:47:38 +0000128bool InstrProfiling::isMachO() const {
129 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
130}
131
132/// Get the section name for the counter variables.
133StringRef InstrProfiling::getCountersSection() const {
134 return getInstrProfCountersSectionName(isMachO());
135}
136
137/// Get the section name for the name variables.
138StringRef InstrProfiling::getNameSection() const {
139 return getInstrProfNameSectionName(isMachO());
140}
141
142/// Get the section name for the profile data variables.
143StringRef InstrProfiling::getDataSection() const {
144 return getInstrProfDataSectionName(isMachO());
145}
146
147/// Get the section name for the coverage mapping data.
148StringRef InstrProfiling::getCoverageSection() const {
149 return getInstrProfCoverageSectionName(isMachO());
150}
151
Xinliang David Li4ca17332016-09-18 18:34:07 +0000152static 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
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000159bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000160 bool MadeChange = false;
161
162 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000163 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000164 NamesVar = nullptr;
165 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000166 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000167 UsedVars.clear();
168
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000169 // 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.
Rong Xu294572f2016-01-19 18:29:54 +0000172 for (Function &F : M) {
173 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000174 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000175 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
176 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000177 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000178 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 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000186
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++;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000191 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
192 if (Inc) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000193 lowerIncrement(Inc);
194 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000195 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
196 lowerValueProfileInst(Ind);
197 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000198 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000199 }
200
Xinliang David Li81056072016-01-07 20:05:49 +0000201 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000202 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000203 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000204 MadeChange = true;
205 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000206
Justin Bogner61ba2e32014-12-08 18:02:35 +0000207 if (!MadeChange)
208 return false;
209
Xinliang David Lib628dd32016-05-21 22:55:34 +0000210 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000211 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000212 emitRegistration();
213 emitRuntimeHook();
214 emitUses();
215 emitInitialization();
216 return true;
217}
218
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000219static Constant *getOrInsertValueProfilingCall(Module &M,
220 const TargetLibraryInfo &TLI) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000221 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 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000227 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000228 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000229 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;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000236}
237
238void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000239 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
251void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000252 GlobalVariable *Name = Ind->getName();
253 auto It = ProfileDataMap.find(Name);
254 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000255 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000256
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);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000264 Value *Args[3] = {Ind->getTargetValue(),
265 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
266 Builder.getInt32(Index)};
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000267 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);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000272 Ind->eraseFromParent();
273}
274
Justin Bogner61ba2e32014-12-08 18:02:35 +0000275void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
276 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
277
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000278 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000279 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000280 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
281 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Xinliang David Lia754c472016-09-20 19:07:22 +0000282 Count = Builder.CreateAdd(Count, Inc->getStep());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000283 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
284 Inc->eraseFromParent();
285}
286
Xinliang David Li81056072016-01-07 20:05:49 +0000287void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000288 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();
Justin Bognerd24e1852015-02-11 02:52:44 +0000293 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
294 GlobalVariable *Name = cast<GlobalVariable>(V);
295
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000296 Name->setLinkage(GlobalValue::PrivateLinkage);
297 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000298 }
299}
300
Justin Bogner61ba2e32014-12-08 18:02:35 +0000301/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000302static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000303 StringRef NamePrefix = getInstrProfNameVarPrefix();
304 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000305 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();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000315}
316
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000317static inline bool shouldRecordFunctionAddr(Function *F) {
318 // Check the linkage
319 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
320 !F->hasAvailableExternallyLinkage())
321 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000322 // 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;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000327 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000328 // 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
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000331 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000332 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000333 // indirect call target info.
334 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000335}
336
Xinliang David Li985ff202016-02-27 23:11:30 +0000337static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000338 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000339 if (!needsComdatForCounter(F, M))
340 return nullptr;
341
Xinliang David Liab361ef2015-12-21 21:52:27 +0000342 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000343 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000344 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000345 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000346 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000347 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000348 : getInstrProfComdatPrefix());
349 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
350}
351
Xinliang David Lib628dd32016-05-21 22:55:34 +0000352static 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000366GlobalVariable *
367InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000368 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000369 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 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000376
Wei Mi3cc92042015-09-23 22:40:45 +0000377 // 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.
Diego Novillodf4837b2015-05-27 19:34:01 +0000381 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000382 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000383 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000384
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.
Xinliang David Li192c7482015-11-05 00:47:26 +0000390 auto *CounterPtr =
391 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000392 Constant::getNullValue(CounterTy),
393 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000394 CounterPtr->setVisibility(NamePtr->getVisibility());
395 CounterPtr->setSection(getCountersSection());
396 CounterPtr->setAlignment(8);
397 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000398
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000399 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000400 // 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)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000404 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 =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000419 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000420 }
421 }
422
423 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000424 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000425 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000426 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000427#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
428#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000429 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000430 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000431
Xinliang David Li69a00f02016-06-21 02:39:08 +0000432 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
433 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
434 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000435
Xinliang David Li69a00f02016-06-21 02:39:08 +0000436 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000437 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
438 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
439
Justin Bogner61ba2e32014-12-08 18:02:35 +0000440 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000441#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
442#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000443 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000444 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000445 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000446 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000447 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000448 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000449 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000450 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000451
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000452 PD.RegionCounters = CounterPtr;
453 PD.DataVar = Data;
454 ProfileDataMap[NamePtr] = PD;
455
Justin Bogner61ba2e32014-12-08 18:02:35 +0000456 // Mark the data variable as used so that it isn't stripped out.
457 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000458 // 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);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000464
Xinliang David Li192c7482015-11-05 00:47:26 +0000465 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000466}
467
Xinliang David Lib628dd32016-05-21 22:55:34 +0000468void InstrProfiling::emitVNodes() {
469 if (!ValueProfileStaticAlloc)
470 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000471
Xinliang David Lib628dd32016-05-21 22:55:34 +0000472 // 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;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000477
Xinliang David Lib628dd32016-05-21 22:55:34 +0000478 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;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000488// 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.
Xinliang David Lie4520762016-05-23 19:29:26 +0000495#define INSTR_PROF_MIN_VAL_COUNTS 10
496 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000497 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000498
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(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000508 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000509 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
510 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
511 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000512}
513
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000514void InstrProfiling::emitNameData() {
515 std::string UncompressedData;
516
517 if (ReferencedNames.empty())
518 return;
519
520 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000521 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000522 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000523 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000524 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000525
526 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000527 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000528 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000529 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
530 GlobalValue::PrivateLinkage, NamesVal,
531 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000532 NamesSize = CompressedNameStr.size();
533 NamesVar->setSection(getNameSection());
534 UsedVars.push_back(NamesVar);
535}
536
Justin Bogner61ba2e32014-12-08 18:02:35 +0000537void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000538 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000539 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000540
Justin Bogner61ba2e32014-12-08 18:02:35 +0000541 // Construct the function.
542 auto *VoidTy = Type::getVoidTy(M->getContext());
543 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000544 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000545 auto *RegisterFTy = FunctionType::get(VoidTy, false);
546 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000547 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000548 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000549 if (Options.NoRedZone)
550 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000551
Diego Novillob3029d22015-06-04 11:45:32 +0000552 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000553 auto *RuntimeRegisterF =
554 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000555 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000556
557 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
558 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000559 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000573 IRB.CreateRetVoid();
574}
575
576void InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000577 // 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
Justin Bogner61ba2e32014-12-08 18:02:35 +0000582 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000583 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
584 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000585
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,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000590 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000591
592 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000593 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
594 GlobalValue::LinkOnceODRLinkage,
595 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000596 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000597 if (Options.NoRedZone)
598 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000599 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000600 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000601 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000602
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
611void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000612 if (!UsedVars.empty())
613 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000614}
615
616void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000617 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000618
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000619 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
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000634 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000635 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000636 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000637
638 // Create the initialization function.
639 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000640 auto *F = Function::Create(FunctionType::get(VoidTy, false),
641 GlobalValue::InternalLinkage,
642 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000643 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000644 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000645 if (Options.NoRedZone)
646 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000647
648 // Add the basic block and the necessary calls.
649 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000650 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000651 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000652 IRB.CreateRetVoid();
653
654 appendToGlobalCtors(*M, F, 0);
655}