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