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