SampleProfileProbe.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. //===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the SampleProfileProber transformation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/BlockFrequencyInfo.h"
  15. #include "llvm/Analysis/TargetLibraryInfo.h"
  16. #include "llvm/IR/BasicBlock.h"
  17. #include "llvm/IR/CFG.h"
  18. #include "llvm/IR/Constant.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DebugInfoMetadata.h"
  21. #include "llvm/IR/GlobalValue.h"
  22. #include "llvm/IR/GlobalVariable.h"
  23. #include "llvm/IR/IRBuilder.h"
  24. #include "llvm/IR/Instruction.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/MDBuilder.h"
  27. #include "llvm/ProfileData/SampleProf.h"
  28. #include "llvm/Support/CRC.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Transforms/Instrumentation.h"
  31. #include "llvm/Transforms/Utils/ModuleUtils.h"
  32. #include <unordered_set>
  33. #include <vector>
  34. using namespace llvm;
  35. #define DEBUG_TYPE "sample-profile-probe"
  36. STATISTIC(ArtificialDbgLine,
  37. "Number of probes that have an artificial debug line");
  38. static cl::opt<bool>
  39. VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden,
  40. cl::desc("Do pseudo probe verification"));
  41. static cl::list<std::string> VerifyPseudoProbeFuncList(
  42. "verify-pseudo-probe-funcs", cl::Hidden,
  43. cl::desc("The option to specify the name of the functions to verify."));
  44. static cl::opt<bool>
  45. UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden,
  46. cl::desc("Update pseudo probe distribution factor"));
  47. static uint64_t getCallStackHash(const DILocation *DIL) {
  48. uint64_t Hash = 0;
  49. const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;
  50. while (InlinedAt) {
  51. Hash ^= MD5Hash(std::to_string(InlinedAt->getLine()));
  52. Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn()));
  53. const DISubprogram *SP = InlinedAt->getScope()->getSubprogram();
  54. // Use linkage name for C++ if possible.
  55. auto Name = SP->getLinkageName();
  56. if (Name.empty())
  57. Name = SP->getName();
  58. Hash ^= MD5Hash(Name);
  59. InlinedAt = InlinedAt->getInlinedAt();
  60. }
  61. return Hash;
  62. }
  63. static uint64_t computeCallStackHash(const Instruction &Inst) {
  64. return getCallStackHash(Inst.getDebugLoc());
  65. }
  66. bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
  67. // Skip function declaration.
  68. if (F->isDeclaration())
  69. return false;
  70. // Skip function that will not be emitted into object file. The prevailing
  71. // defintion will be verified instead.
  72. if (F->hasAvailableExternallyLinkage())
  73. return false;
  74. // Do a name matching.
  75. static std::unordered_set<std::string> VerifyFuncNames(
  76. VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());
  77. return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str());
  78. }
  79. void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
  80. if (VerifyPseudoProbe) {
  81. PIC.registerAfterPassCallback(
  82. [this](StringRef P, Any IR, const PreservedAnalyses &) {
  83. this->runAfterPass(P, IR);
  84. });
  85. }
  86. }
  87. // Callback to run after each transformation for the new pass manager.
  88. void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {
  89. std::string Banner =
  90. "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
  91. dbgs() << Banner;
  92. if (any_isa<const Module *>(IR))
  93. runAfterPass(any_cast<const Module *>(IR));
  94. else if (any_isa<const Function *>(IR))
  95. runAfterPass(any_cast<const Function *>(IR));
  96. else if (any_isa<const LazyCallGraph::SCC *>(IR))
  97. runAfterPass(any_cast<const LazyCallGraph::SCC *>(IR));
  98. else if (any_isa<const Loop *>(IR))
  99. runAfterPass(any_cast<const Loop *>(IR));
  100. else
  101. llvm_unreachable("Unknown IR unit");
  102. }
  103. void PseudoProbeVerifier::runAfterPass(const Module *M) {
  104. for (const Function &F : *M)
  105. runAfterPass(&F);
  106. }
  107. void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {
  108. for (const LazyCallGraph::Node &N : *C)
  109. runAfterPass(&N.getFunction());
  110. }
  111. void PseudoProbeVerifier::runAfterPass(const Function *F) {
  112. if (!shouldVerifyFunction(F))
  113. return;
  114. ProbeFactorMap ProbeFactors;
  115. for (const auto &BB : *F)
  116. collectProbeFactors(&BB, ProbeFactors);
  117. verifyProbeFactors(F, ProbeFactors);
  118. }
  119. void PseudoProbeVerifier::runAfterPass(const Loop *L) {
  120. const Function *F = L->getHeader()->getParent();
  121. runAfterPass(F);
  122. }
  123. void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,
  124. ProbeFactorMap &ProbeFactors) {
  125. for (const auto &I : *Block) {
  126. if (Optional<PseudoProbe> Probe = extractProbe(I)) {
  127. uint64_t Hash = computeCallStackHash(I);
  128. ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;
  129. }
  130. }
  131. }
  132. void PseudoProbeVerifier::verifyProbeFactors(
  133. const Function *F, const ProbeFactorMap &ProbeFactors) {
  134. bool BannerPrinted = false;
  135. auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];
  136. for (const auto &I : ProbeFactors) {
  137. float CurProbeFactor = I.second;
  138. if (PrevProbeFactors.count(I.first)) {
  139. float PrevProbeFactor = PrevProbeFactors[I.first];
  140. if (std::abs(CurProbeFactor - PrevProbeFactor) >
  141. DistributionFactorVariance) {
  142. if (!BannerPrinted) {
  143. dbgs() << "Function " << F->getName() << ":\n";
  144. BannerPrinted = true;
  145. }
  146. dbgs() << "Probe " << I.first.first << "\tprevious factor "
  147. << format("%0.2f", PrevProbeFactor) << "\tcurrent factor "
  148. << format("%0.2f", CurProbeFactor) << "\n";
  149. }
  150. }
  151. // Update
  152. PrevProbeFactors[I.first] = I.second;
  153. }
  154. }
  155. PseudoProbeManager::PseudoProbeManager(const Module &M) {
  156. if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
  157. for (const auto *Operand : FuncInfo->operands()) {
  158. const auto *MD = cast<MDNode>(Operand);
  159. auto GUID =
  160. mdconst::dyn_extract<ConstantInt>(MD->getOperand(0))->getZExtValue();
  161. auto Hash =
  162. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
  163. GUIDToProbeDescMap.try_emplace(GUID, PseudoProbeDescriptor(GUID, Hash));
  164. }
  165. }
  166. }
  167. const PseudoProbeDescriptor *
  168. PseudoProbeManager::getDesc(const Function &F) const {
  169. auto I = GUIDToProbeDescMap.find(
  170. Function::getGUID(FunctionSamples::getCanonicalFnName(F)));
  171. return I == GUIDToProbeDescMap.end() ? nullptr : &I->second;
  172. }
  173. bool PseudoProbeManager::moduleIsProbed(const Module &M) const {
  174. return M.getNamedMetadata(PseudoProbeDescMetadataName);
  175. }
  176. bool PseudoProbeManager::profileIsValid(const Function &F,
  177. const FunctionSamples &Samples) const {
  178. const auto *Desc = getDesc(F);
  179. if (!Desc) {
  180. LLVM_DEBUG(dbgs() << "Probe descriptor missing for Function " << F.getName()
  181. << "\n");
  182. return false;
  183. } else {
  184. if (Desc->getFunctionHash() != Samples.getFunctionHash()) {
  185. LLVM_DEBUG(dbgs() << "Hash mismatch for Function " << F.getName()
  186. << "\n");
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. SampleProfileProber::SampleProfileProber(Function &Func,
  193. const std::string &CurModuleUniqueId)
  194. : F(&Func), CurModuleUniqueId(CurModuleUniqueId) {
  195. BlockProbeIds.clear();
  196. CallProbeIds.clear();
  197. LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
  198. computeProbeIdForBlocks();
  199. computeProbeIdForCallsites();
  200. computeCFGHash();
  201. }
  202. // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
  203. // value of each BB in the CFG. The higher 32 bits record the number of edges
  204. // preceded by the number of indirect calls.
  205. // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().
  206. void SampleProfileProber::computeCFGHash() {
  207. std::vector<uint8_t> Indexes;
  208. JamCRC JC;
  209. for (auto &BB : *F) {
  210. auto *TI = BB.getTerminator();
  211. for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
  212. auto *Succ = TI->getSuccessor(I);
  213. auto Index = getBlockId(Succ);
  214. for (int J = 0; J < 4; J++)
  215. Indexes.push_back((uint8_t)(Index >> (J * 8)));
  216. }
  217. }
  218. JC.update(Indexes);
  219. FunctionHash = (uint64_t)CallProbeIds.size() << 48 |
  220. (uint64_t)Indexes.size() << 32 | JC.getCRC();
  221. // Reserve bit 60-63 for other information purpose.
  222. FunctionHash &= 0x0FFFFFFFFFFFFFFF;
  223. assert(FunctionHash && "Function checksum should not be zero");
  224. LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()
  225. << ":\n"
  226. << " CRC = " << JC.getCRC() << ", Edges = "
  227. << Indexes.size() << ", ICSites = " << CallProbeIds.size()
  228. << ", Hash = " << FunctionHash << "\n");
  229. }
  230. void SampleProfileProber::computeProbeIdForBlocks() {
  231. for (auto &BB : *F) {
  232. BlockProbeIds[&BB] = ++LastProbeId;
  233. }
  234. }
  235. void SampleProfileProber::computeProbeIdForCallsites() {
  236. for (auto &BB : *F) {
  237. for (auto &I : BB) {
  238. if (!isa<CallBase>(I))
  239. continue;
  240. if (isa<IntrinsicInst>(&I))
  241. continue;
  242. CallProbeIds[&I] = ++LastProbeId;
  243. }
  244. }
  245. }
  246. uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {
  247. auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB));
  248. return I == BlockProbeIds.end() ? 0 : I->second;
  249. }
  250. uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {
  251. auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call));
  252. return Iter == CallProbeIds.end() ? 0 : Iter->second;
  253. }
  254. void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {
  255. Module *M = F.getParent();
  256. MDBuilder MDB(F.getContext());
  257. // Compute a GUID without considering the function's linkage type. This is
  258. // fine since function name is the only key in the profile database.
  259. uint64_t Guid = Function::getGUID(F.getName());
  260. // Assign an artificial debug line to a probe that doesn't come with a real
  261. // line. A probe not having a debug line will get an incomplete inline
  262. // context. This will cause samples collected on the probe to be counted
  263. // into the base profile instead of a context profile. The line number
  264. // itself is not important though.
  265. auto AssignDebugLoc = [&](Instruction *I) {
  266. assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&
  267. "Expecting pseudo probe or call instructions");
  268. if (!I->getDebugLoc()) {
  269. if (auto *SP = F.getSubprogram()) {
  270. auto DIL = DILocation::get(SP->getContext(), 0, 0, SP);
  271. I->setDebugLoc(DIL);
  272. ArtificialDbgLine++;
  273. LLVM_DEBUG({
  274. dbgs() << "\nIn Function " << F.getName()
  275. << " Probe gets an artificial debug line\n";
  276. I->dump();
  277. });
  278. }
  279. }
  280. };
  281. // Probe basic blocks.
  282. for (auto &I : BlockProbeIds) {
  283. BasicBlock *BB = I.first;
  284. uint32_t Index = I.second;
  285. // Insert a probe before an instruction with a valid debug line number which
  286. // will be assigned to the probe. The line number will be used later to
  287. // model the inline context when the probe is inlined into other functions.
  288. // Debug instructions, phi nodes and lifetime markers do not have an valid
  289. // line number. Real instructions generated by optimizations may not come
  290. // with a line number either.
  291. auto HasValidDbgLine = [](Instruction *J) {
  292. return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) &&
  293. !J->isLifetimeStartOrEnd() && J->getDebugLoc();
  294. };
  295. Instruction *J = &*BB->getFirstInsertionPt();
  296. while (J != BB->getTerminator() && !HasValidDbgLine(J)) {
  297. J = J->getNextNode();
  298. }
  299. IRBuilder<> Builder(J);
  300. assert(Builder.GetInsertPoint() != BB->end() &&
  301. "Cannot get the probing point");
  302. Function *ProbeFn =
  303. llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe);
  304. Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index),
  305. Builder.getInt32(0),
  306. Builder.getInt64(PseudoProbeFullDistributionFactor)};
  307. auto *Probe = Builder.CreateCall(ProbeFn, Args);
  308. AssignDebugLoc(Probe);
  309. }
  310. // Probe both direct calls and indirect calls. Direct calls are probed so that
  311. // their probe ID can be used as an call site identifier to represent a
  312. // calling context.
  313. for (auto &I : CallProbeIds) {
  314. auto *Call = I.first;
  315. uint32_t Index = I.second;
  316. uint32_t Type = cast<CallBase>(Call)->getCalledFunction()
  317. ? (uint32_t)PseudoProbeType::DirectCall
  318. : (uint32_t)PseudoProbeType::IndirectCall;
  319. AssignDebugLoc(Call);
  320. // Levarge the 32-bit discriminator field of debug data to store the ID and
  321. // type of a callsite probe. This gets rid of the dependency on plumbing a
  322. // customized metadata through the codegen pipeline.
  323. uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(
  324. Index, Type, 0, PseudoProbeDwarfDiscriminator::FullDistributionFactor);
  325. if (auto DIL = Call->getDebugLoc()) {
  326. DIL = DIL->cloneWithDiscriminator(V);
  327. Call->setDebugLoc(DIL);
  328. }
  329. }
  330. // Create module-level metadata that contains function info necessary to
  331. // synthesize probe-based sample counts, which are
  332. // - FunctionGUID
  333. // - FunctionHash.
  334. // - FunctionName
  335. auto Hash = getFunctionHash();
  336. auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, &F);
  337. auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName);
  338. assert(NMD && "llvm.pseudo_probe_desc should be pre-created");
  339. NMD->addOperand(MD);
  340. // Preserve a comdat group to hold all probes materialized later. This
  341. // allows that when the function is considered dead and removed, the
  342. // materialized probes are disposed too.
  343. // Imported functions are defined in another module. They do not need
  344. // the following handling since same care will be taken for them in their
  345. // original module. The pseudo probes inserted into an imported functions
  346. // above will naturally not be emitted since the imported function is free
  347. // from object emission. However they will be emitted together with the
  348. // inliner functions that the imported function is inlined into. We are not
  349. // creating a comdat group for an import function since it's useless anyway.
  350. if (!F.isDeclarationForLinker()) {
  351. if (TM) {
  352. auto Triple = TM->getTargetTriple();
  353. if (Triple.supportsCOMDAT() && TM->getFunctionSections())
  354. getOrCreateFunctionComdat(F, Triple);
  355. }
  356. }
  357. }
  358. PreservedAnalyses SampleProfileProbePass::run(Module &M,
  359. ModuleAnalysisManager &AM) {
  360. auto ModuleId = getUniqueModuleId(&M);
  361. // Create the pseudo probe desc metadata beforehand.
  362. // Note that modules with only data but no functions will require this to
  363. // be set up so that they will be known as probed later.
  364. M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName);
  365. for (auto &F : M) {
  366. if (F.isDeclaration())
  367. continue;
  368. SampleProfileProber ProbeManager(F, ModuleId);
  369. ProbeManager.instrumentOneFunc(F, TM);
  370. }
  371. return PreservedAnalyses::none();
  372. }
  373. void PseudoProbeUpdatePass::runOnFunction(Function &F,
  374. FunctionAnalysisManager &FAM) {
  375. BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
  376. auto BBProfileCount = [&BFI](BasicBlock *BB) {
  377. return BFI.getBlockProfileCount(BB).getValueOr(0);
  378. };
  379. // Collect the sum of execution weight for each probe.
  380. ProbeFactorMap ProbeFactors;
  381. for (auto &Block : F) {
  382. for (auto &I : Block) {
  383. if (Optional<PseudoProbe> Probe = extractProbe(I)) {
  384. uint64_t Hash = computeCallStackHash(I);
  385. ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);
  386. }
  387. }
  388. }
  389. // Fix up over-counted probes.
  390. for (auto &Block : F) {
  391. for (auto &I : Block) {
  392. if (Optional<PseudoProbe> Probe = extractProbe(I)) {
  393. uint64_t Hash = computeCallStackHash(I);
  394. float Sum = ProbeFactors[{Probe->Id, Hash}];
  395. if (Sum != 0)
  396. setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum);
  397. }
  398. }
  399. }
  400. }
  401. PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,
  402. ModuleAnalysisManager &AM) {
  403. if (UpdatePseudoProbe) {
  404. for (auto &F : M) {
  405. if (F.isDeclaration())
  406. continue;
  407. FunctionAnalysisManager &FAM =
  408. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  409. runOnFunction(F, FAM);
  410. }
  411. }
  412. return PreservedAnalyses::none();
  413. }