InstrProfiling.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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_increment intrinsics emitted by a frontend for
  11. // profiling. It also builds the data structures and initialization code needed
  12. // for updating execution counts and emitting the profile at runtime.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Instrumentation.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/IR/IRBuilder.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. #include "llvm/IR/Module.h"
  20. #include "llvm/Transforms/Utils/ModuleUtils.h"
  21. using namespace llvm;
  22. #define DEBUG_TYPE "instrprof"
  23. namespace {
  24. class InstrProfiling : public ModulePass {
  25. public:
  26. static char ID;
  27. InstrProfiling() : ModulePass(ID) {}
  28. InstrProfiling(const InstrProfOptions &Options)
  29. : ModulePass(ID), Options(Options) {}
  30. const char *getPassName() const override {
  31. return "Frontend instrumentation-based coverage lowering";
  32. }
  33. bool runOnModule(Module &M) override;
  34. void getAnalysisUsage(AnalysisUsage &AU) const override {
  35. AU.setPreservesCFG();
  36. }
  37. private:
  38. InstrProfOptions Options;
  39. Module *M;
  40. DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
  41. std::vector<Value *> UsedVars;
  42. bool isMachO() const {
  43. return Triple(M->getTargetTriple()).isOSBinFormatMachO();
  44. }
  45. /// Get the section name for the counter variables.
  46. StringRef getCountersSection() const {
  47. return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
  48. }
  49. /// Get the section name for the name variables.
  50. StringRef getNameSection() const {
  51. return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
  52. }
  53. /// Get the section name for the profile data variables.
  54. StringRef getDataSection() const {
  55. return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
  56. }
  57. /// Get the section name for the coverage mapping data.
  58. StringRef getCoverageSection() const {
  59. return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap";
  60. }
  61. /// Replace instrprof_increment with an increment of the appropriate value.
  62. void lowerIncrement(InstrProfIncrementInst *Inc);
  63. /// Set up the section and uses for coverage data and its references.
  64. void lowerCoverageData(GlobalVariable *CoverageData);
  65. /// Get the region counters for an increment, creating them if necessary.
  66. ///
  67. /// If the counter array doesn't yet exist, the profile data variables
  68. /// referring to them will also be created.
  69. GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
  70. /// Emit runtime registration functions for each profile data variable.
  71. void emitRegistration();
  72. /// Emit the necessary plumbing to pull in the runtime initialization.
  73. void emitRuntimeHook();
  74. /// Add uses of our data variables and runtime hook.
  75. void emitUses();
  76. /// Create a static initializer for our data, on platforms that need it,
  77. /// and for any profile output file that was specified.
  78. void emitInitialization();
  79. };
  80. } // anonymous namespace
  81. char InstrProfiling::ID = 0;
  82. INITIALIZE_PASS(InstrProfiling, "instrprof",
  83. "Frontend instrumentation-based coverage lowering.", false,
  84. false)
  85. ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
  86. return new InstrProfiling(Options);
  87. }
  88. bool InstrProfiling::runOnModule(Module &M) {
  89. bool MadeChange = false;
  90. this->M = &M;
  91. RegionCounters.clear();
  92. UsedVars.clear();
  93. for (Function &F : M)
  94. for (BasicBlock &BB : F)
  95. for (auto I = BB.begin(), E = BB.end(); I != E;)
  96. if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
  97. lowerIncrement(Inc);
  98. MadeChange = true;
  99. }
  100. if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) {
  101. lowerCoverageData(Coverage);
  102. MadeChange = true;
  103. }
  104. if (!MadeChange)
  105. return false;
  106. emitRegistration();
  107. emitRuntimeHook();
  108. emitUses();
  109. emitInitialization();
  110. return true;
  111. }
  112. void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
  113. GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
  114. IRBuilder<> Builder(Inc->getParent(), *Inc);
  115. uint64_t Index = Inc->getIndex()->getZExtValue();
  116. Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
  117. Value *Count = Builder.CreateLoad(Addr, "pgocount");
  118. Count = Builder.CreateAdd(Count, Builder.getInt64(1));
  119. Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
  120. Inc->eraseFromParent();
  121. }
  122. void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
  123. CoverageData->setSection(getCoverageSection());
  124. CoverageData->setAlignment(8);
  125. Constant *Init = CoverageData->getInitializer();
  126. // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
  127. // for some C. If not, the frontend's given us something broken.
  128. assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
  129. assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
  130. "invalid function list in coverage map");
  131. ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
  132. for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
  133. Constant *Record = Records->getOperand(I);
  134. Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
  135. assert(isa<GlobalVariable>(V) && "Missing reference to function name");
  136. GlobalVariable *Name = cast<GlobalVariable>(V);
  137. // If we have region counters for this name, we've already handled it.
  138. auto It = RegionCounters.find(Name);
  139. if (It != RegionCounters.end())
  140. continue;
  141. // Move the name variable to the right section.
  142. Name->setSection(getNameSection());
  143. Name->setAlignment(1);
  144. }
  145. }
  146. /// Get the name of a profiling variable for a particular function.
  147. static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) {
  148. auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
  149. StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
  150. return ("__llvm_profile_" + VarName + "_" + Name).str();
  151. }
  152. GlobalVariable *
  153. InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
  154. GlobalVariable *Name = Inc->getName();
  155. auto It = RegionCounters.find(Name);
  156. if (It != RegionCounters.end())
  157. return It->second;
  158. // Move the name variable to the right section. Make sure it is placed in the
  159. // same comdat as its associated function. Otherwise, we may get multiple
  160. // counters for the same function in certain cases.
  161. Function *Fn = Inc->getParent()->getParent();
  162. Name->setSection(getNameSection());
  163. Name->setAlignment(1);
  164. Name->setComdat(Fn->getComdat());
  165. uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
  166. LLVMContext &Ctx = M->getContext();
  167. ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
  168. // Create the counters variable.
  169. auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
  170. Constant::getNullValue(CounterTy),
  171. getVarName(Inc, "counters"));
  172. Counters->setVisibility(Name->getVisibility());
  173. Counters->setSection(getCountersSection());
  174. Counters->setAlignment(8);
  175. Counters->setComdat(Fn->getComdat());
  176. RegionCounters[Inc->getName()] = Counters;
  177. // Create data variable.
  178. auto *NameArrayTy = Name->getType()->getPointerElementType();
  179. auto *Int32Ty = Type::getInt32Ty(Ctx);
  180. auto *Int64Ty = Type::getInt64Ty(Ctx);
  181. auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
  182. auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
  183. Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
  184. auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
  185. Constant *DataVals[] = {
  186. ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
  187. ConstantInt::get(Int32Ty, NumCounters),
  188. ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
  189. ConstantExpr::getBitCast(Name, Int8PtrTy),
  190. ConstantExpr::getBitCast(Counters, Int64PtrTy)};
  191. auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
  192. ConstantStruct::get(DataTy, DataVals),
  193. getVarName(Inc, "data"));
  194. Data->setVisibility(Name->getVisibility());
  195. Data->setSection(getDataSection());
  196. Data->setAlignment(8);
  197. Data->setComdat(Fn->getComdat());
  198. // Mark the data variable as used so that it isn't stripped out.
  199. UsedVars.push_back(Data);
  200. return Counters;
  201. }
  202. void InstrProfiling::emitRegistration() {
  203. // Don't do this for Darwin. compiler-rt uses linker magic.
  204. if (Triple(M->getTargetTriple()).isOSDarwin())
  205. return;
  206. // Construct the function.
  207. auto *VoidTy = Type::getVoidTy(M->getContext());
  208. auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
  209. auto *RegisterFTy = FunctionType::get(VoidTy, false);
  210. auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
  211. "__llvm_profile_register_functions", M);
  212. RegisterF->setUnnamedAddr(true);
  213. if (Options.NoRedZone)
  214. RegisterF->addFnAttr(Attribute::NoRedZone);
  215. auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
  216. auto *RuntimeRegisterF =
  217. Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
  218. "__llvm_profile_register_function", M);
  219. IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
  220. for (Value *Data : UsedVars)
  221. IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
  222. IRB.CreateRetVoid();
  223. }
  224. void InstrProfiling::emitRuntimeHook() {
  225. const char *const RuntimeVarName = "__llvm_profile_runtime";
  226. const char *const RuntimeUserName = "__llvm_profile_runtime_user";
  227. // If the module's provided its own runtime, we don't need to do anything.
  228. if (M->getGlobalVariable(RuntimeVarName))
  229. return;
  230. // Declare an external variable that will pull in the runtime initialization.
  231. auto *Int32Ty = Type::getInt32Ty(M->getContext());
  232. auto *Var =
  233. new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
  234. nullptr, RuntimeVarName);
  235. // Make a function that uses it.
  236. auto *User =
  237. Function::Create(FunctionType::get(Int32Ty, false),
  238. GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M);
  239. User->addFnAttr(Attribute::NoInline);
  240. if (Options.NoRedZone)
  241. User->addFnAttr(Attribute::NoRedZone);
  242. User->setVisibility(GlobalValue::HiddenVisibility);
  243. IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
  244. auto *Load = IRB.CreateLoad(Var);
  245. IRB.CreateRet(Load);
  246. // Mark the user variable as used so that it isn't stripped out.
  247. UsedVars.push_back(User);
  248. }
  249. void InstrProfiling::emitUses() {
  250. if (UsedVars.empty())
  251. return;
  252. GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
  253. std::vector<Constant *> MergedVars;
  254. if (LLVMUsed) {
  255. // Collect the existing members of llvm.used.
  256. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  257. for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
  258. MergedVars.push_back(Inits->getOperand(I));
  259. LLVMUsed->eraseFromParent();
  260. }
  261. Type *i8PTy = Type::getInt8PtrTy(M->getContext());
  262. // Add uses for our data.
  263. for (auto *Value : UsedVars)
  264. MergedVars.push_back(
  265. ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
  266. // Recreate llvm.used.
  267. ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
  268. LLVMUsed =
  269. new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
  270. ConstantArray::get(ATy, MergedVars), "llvm.used");
  271. LLVMUsed->setSection("llvm.metadata");
  272. }
  273. void InstrProfiling::emitInitialization() {
  274. std::string InstrProfileOutput = Options.InstrProfileOutput;
  275. Constant *RegisterF = M->getFunction("__llvm_profile_register_functions");
  276. if (!RegisterF && InstrProfileOutput.empty())
  277. return;
  278. // Create the initialization function.
  279. auto *VoidTy = Type::getVoidTy(M->getContext());
  280. auto *F =
  281. Function::Create(FunctionType::get(VoidTy, false),
  282. GlobalValue::InternalLinkage, "__llvm_profile_init", M);
  283. F->setUnnamedAddr(true);
  284. F->addFnAttr(Attribute::NoInline);
  285. if (Options.NoRedZone)
  286. F->addFnAttr(Attribute::NoRedZone);
  287. // Add the basic block and the necessary calls.
  288. IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
  289. if (RegisterF)
  290. IRB.CreateCall(RegisterF, {});
  291. if (!InstrProfileOutput.empty()) {
  292. auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
  293. auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
  294. auto *SetNameF =
  295. Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
  296. "__llvm_profile_override_default_filename", M);
  297. // Create variable for profile name.
  298. Constant *ProfileNameConst =
  299. ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
  300. GlobalVariable *ProfileName =
  301. new GlobalVariable(*M, ProfileNameConst->getType(), true,
  302. GlobalValue::PrivateLinkage, ProfileNameConst);
  303. IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
  304. }
  305. IRB.CreateRetVoid();
  306. appendToGlobalCtors(*M, F, 0);
  307. }