ProfileGenerator.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. //===-- ProfileGenerator.cpp - Profile Generator ---------------*- C++ -*-===//
  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. #include "ProfileGenerator.h"
  9. #include "ErrorHandling.h"
  10. #include "MissingFrameInferrer.h"
  11. #include "PerfReader.h"
  12. #include "ProfiledBinary.h"
  13. #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"
  14. #include "llvm/ProfileData/ProfileCommon.h"
  15. #include <algorithm>
  16. #include <float.h>
  17. #include <unordered_set>
  18. #include <utility>
  19. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  20. cl::Required,
  21. cl::desc("Output profile file"));
  22. static cl::alias OutputA("o", cl::desc("Alias for --output"),
  23. cl::aliasopt(OutputFilename));
  24. static cl::opt<SampleProfileFormat> OutputFormat(
  25. "format", cl::desc("Format of output profile"), cl::init(SPF_Ext_Binary),
  26. cl::values(
  27. clEnumValN(SPF_Binary, "binary", "Binary encoding (default)"),
  28. clEnumValN(SPF_Compact_Binary, "compbinary", "Compact binary encoding"),
  29. clEnumValN(SPF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  30. clEnumValN(SPF_Text, "text", "Text encoding"),
  31. clEnumValN(SPF_GCC, "gcc",
  32. "GCC encoding (only meaningful for -sample)")));
  33. static cl::opt<bool> UseMD5(
  34. "use-md5", cl::Hidden,
  35. cl::desc("Use md5 to represent function names in the output profile (only "
  36. "meaningful for -extbinary)"));
  37. static cl::opt<bool> PopulateProfileSymbolList(
  38. "populate-profile-symbol-list", cl::init(false), cl::Hidden,
  39. cl::desc("Populate profile symbol list (only meaningful for -extbinary)"));
  40. static cl::opt<bool> FillZeroForAllFuncs(
  41. "fill-zero-for-all-funcs", cl::init(false), cl::Hidden,
  42. cl::desc("Attribute all functions' range with zero count "
  43. "even it's not hit by any samples."));
  44. static cl::opt<int32_t, true> RecursionCompression(
  45. "compress-recursion",
  46. cl::desc("Compressing recursion by deduplicating adjacent frame "
  47. "sequences up to the specified size. -1 means no size limit."),
  48. cl::Hidden,
  49. cl::location(llvm::sampleprof::CSProfileGenerator::MaxCompressionSize));
  50. static cl::opt<bool>
  51. TrimColdProfile("trim-cold-profile",
  52. cl::desc("If the total count of the profile is smaller "
  53. "than threshold, it will be trimmed."));
  54. static cl::opt<bool> CSProfMergeColdContext(
  55. "csprof-merge-cold-context", cl::init(true),
  56. cl::desc("If the total count of context profile is smaller than "
  57. "the threshold, it will be merged into context-less base "
  58. "profile."));
  59. static cl::opt<uint32_t> CSProfMaxColdContextDepth(
  60. "csprof-max-cold-context-depth", cl::init(1),
  61. cl::desc("Keep the last K contexts while merging cold profile. 1 means the "
  62. "context-less base profile"));
  63. static cl::opt<int, true> CSProfMaxContextDepth(
  64. "csprof-max-context-depth",
  65. cl::desc("Keep the last K contexts while merging profile. -1 means no "
  66. "depth limit."),
  67. cl::location(llvm::sampleprof::CSProfileGenerator::MaxContextDepth));
  68. static cl::opt<double> HotFunctionDensityThreshold(
  69. "hot-function-density-threshold", llvm::cl::init(1000),
  70. llvm::cl::desc(
  71. "specify density threshold for hot functions (default: 1000)"),
  72. llvm::cl::Optional);
  73. static cl::opt<bool> ShowDensity("show-density", llvm::cl::init(false),
  74. llvm::cl::desc("show profile density details"),
  75. llvm::cl::Optional);
  76. static cl::opt<bool> UpdateTotalSamples(
  77. "update-total-samples", llvm::cl::init(false),
  78. llvm::cl::desc(
  79. "Update total samples by accumulating all its body samples."),
  80. llvm::cl::Optional);
  81. static cl::opt<bool> GenCSNestedProfile(
  82. "gen-cs-nested-profile", cl::Hidden, cl::init(true),
  83. cl::desc("Generate nested function profiles for CSSPGO"));
  84. cl::opt<bool> InferMissingFrames(
  85. "infer-missing-frames", llvm::cl::init(true),
  86. llvm::cl::desc(
  87. "Infer missing call frames due to compiler tail call elimination."),
  88. llvm::cl::Optional);
  89. using namespace llvm;
  90. using namespace sampleprof;
  91. namespace llvm {
  92. extern cl::opt<int> ProfileSummaryCutoffHot;
  93. extern cl::opt<bool> UseContextLessSummary;
  94. namespace sampleprof {
  95. // Initialize the MaxCompressionSize to -1 which means no size limit
  96. int32_t CSProfileGenerator::MaxCompressionSize = -1;
  97. int CSProfileGenerator::MaxContextDepth = -1;
  98. bool ProfileGeneratorBase::UseFSDiscriminator = false;
  99. std::unique_ptr<ProfileGeneratorBase>
  100. ProfileGeneratorBase::create(ProfiledBinary *Binary,
  101. const ContextSampleCounterMap *SampleCounters,
  102. bool ProfileIsCS) {
  103. std::unique_ptr<ProfileGeneratorBase> Generator;
  104. if (ProfileIsCS) {
  105. if (Binary->useFSDiscriminator())
  106. exitWithError("FS discriminator is not supported in CS profile.");
  107. Generator.reset(new CSProfileGenerator(Binary, SampleCounters));
  108. } else {
  109. Generator.reset(new ProfileGenerator(Binary, SampleCounters));
  110. }
  111. ProfileGeneratorBase::UseFSDiscriminator = Binary->useFSDiscriminator();
  112. FunctionSamples::ProfileIsFS = Binary->useFSDiscriminator();
  113. return Generator;
  114. }
  115. std::unique_ptr<ProfileGeneratorBase>
  116. ProfileGeneratorBase::create(ProfiledBinary *Binary, SampleProfileMap &Profiles,
  117. bool ProfileIsCS) {
  118. std::unique_ptr<ProfileGeneratorBase> Generator;
  119. if (ProfileIsCS) {
  120. if (Binary->useFSDiscriminator())
  121. exitWithError("FS discriminator is not supported in CS profile.");
  122. Generator.reset(new CSProfileGenerator(Binary, Profiles));
  123. } else {
  124. Generator.reset(new ProfileGenerator(Binary, std::move(Profiles)));
  125. }
  126. ProfileGeneratorBase::UseFSDiscriminator = Binary->useFSDiscriminator();
  127. FunctionSamples::ProfileIsFS = Binary->useFSDiscriminator();
  128. return Generator;
  129. }
  130. void ProfileGeneratorBase::write(std::unique_ptr<SampleProfileWriter> Writer,
  131. SampleProfileMap &ProfileMap) {
  132. // Populate profile symbol list if extended binary format is used.
  133. ProfileSymbolList SymbolList;
  134. if (PopulateProfileSymbolList && OutputFormat == SPF_Ext_Binary) {
  135. Binary->populateSymbolListFromDWARF(SymbolList);
  136. Writer->setProfileSymbolList(&SymbolList);
  137. }
  138. if (std::error_code EC = Writer->write(ProfileMap))
  139. exitWithError(std::move(EC));
  140. }
  141. void ProfileGeneratorBase::write() {
  142. auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
  143. if (std::error_code EC = WriterOrErr.getError())
  144. exitWithError(EC, OutputFilename);
  145. if (UseMD5) {
  146. if (OutputFormat != SPF_Ext_Binary)
  147. WithColor::warning() << "-use-md5 is ignored. Specify "
  148. "--format=extbinary to enable it\n";
  149. else
  150. WriterOrErr.get()->setUseMD5();
  151. }
  152. write(std::move(WriterOrErr.get()), ProfileMap);
  153. }
  154. void ProfileGeneratorBase::showDensitySuggestion(double Density) {
  155. if (Density == 0.0)
  156. WithColor::warning() << "The --profile-summary-cutoff-hot option may be "
  157. "set too low. Please check your command.\n";
  158. else if (Density < HotFunctionDensityThreshold)
  159. WithColor::warning()
  160. << "AutoFDO is estimated to optimize better with "
  161. << format("%.1f", HotFunctionDensityThreshold / Density)
  162. << "x more samples. Please consider increasing sampling rate or "
  163. "profiling for longer duration to get more samples.\n";
  164. if (ShowDensity)
  165. outs() << "Minimum profile density for hot functions with top "
  166. << format("%.2f",
  167. static_cast<double>(ProfileSummaryCutoffHot.getValue()) /
  168. 10000)
  169. << "% total samples: " << format("%.1f", Density) << "\n";
  170. }
  171. double ProfileGeneratorBase::calculateDensity(const SampleProfileMap &Profiles,
  172. uint64_t HotCntThreshold) {
  173. double Density = DBL_MAX;
  174. std::vector<const FunctionSamples *> HotFuncs;
  175. for (auto &I : Profiles) {
  176. auto &FuncSamples = I.second;
  177. if (FuncSamples.getTotalSamples() < HotCntThreshold)
  178. continue;
  179. HotFuncs.emplace_back(&FuncSamples);
  180. }
  181. for (auto *FuncSamples : HotFuncs) {
  182. auto *Func = Binary->getBinaryFunction(FuncSamples->getName());
  183. if (!Func)
  184. continue;
  185. uint64_t FuncSize = Func->getFuncSize();
  186. if (FuncSize == 0)
  187. continue;
  188. Density =
  189. std::min(Density, static_cast<double>(FuncSamples->getTotalSamples()) /
  190. FuncSize);
  191. }
  192. return Density == DBL_MAX ? 0.0 : Density;
  193. }
  194. void ProfileGeneratorBase::findDisjointRanges(RangeSample &DisjointRanges,
  195. const RangeSample &Ranges) {
  196. /*
  197. Regions may overlap with each other. Using the boundary info, find all
  198. disjoint ranges and their sample count. BoundaryPoint contains the count
  199. multiple samples begin/end at this points.
  200. |<--100-->| Sample1
  201. |<------200------>| Sample2
  202. A B C
  203. In the example above,
  204. Sample1 begins at A, ends at B, its value is 100.
  205. Sample2 beings at A, ends at C, its value is 200.
  206. For A, BeginCount is the sum of sample begins at A, which is 300 and no
  207. samples ends at A, so EndCount is 0.
  208. Then boundary points A, B, and C with begin/end counts are:
  209. A: (300, 0)
  210. B: (0, 100)
  211. C: (0, 200)
  212. */
  213. struct BoundaryPoint {
  214. // Sum of sample counts beginning at this point
  215. uint64_t BeginCount = UINT64_MAX;
  216. // Sum of sample counts ending at this point
  217. uint64_t EndCount = UINT64_MAX;
  218. // Is the begin point of a zero range.
  219. bool IsZeroRangeBegin = false;
  220. // Is the end point of a zero range.
  221. bool IsZeroRangeEnd = false;
  222. void addBeginCount(uint64_t Count) {
  223. if (BeginCount == UINT64_MAX)
  224. BeginCount = 0;
  225. BeginCount += Count;
  226. }
  227. void addEndCount(uint64_t Count) {
  228. if (EndCount == UINT64_MAX)
  229. EndCount = 0;
  230. EndCount += Count;
  231. }
  232. };
  233. /*
  234. For the above example. With boundary points, follwing logic finds two
  235. disjoint region of
  236. [A,B]: 300
  237. [B+1,C]: 200
  238. If there is a boundary point that both begin and end, the point itself
  239. becomes a separate disjoint region. For example, if we have original
  240. ranges of
  241. |<--- 100 --->|
  242. |<--- 200 --->|
  243. A B C
  244. there are three boundary points with their begin/end counts of
  245. A: (100, 0)
  246. B: (200, 100)
  247. C: (0, 200)
  248. the disjoint ranges would be
  249. [A, B-1]: 100
  250. [B, B]: 300
  251. [B+1, C]: 200.
  252. Example for zero value range:
  253. |<--- 100 --->|
  254. |<--- 200 --->|
  255. |<--------------- 0 ----------------->|
  256. A B C D E F
  257. [A, B-1] : 0
  258. [B, C] : 100
  259. [C+1, D-1]: 0
  260. [D, E] : 200
  261. [E+1, F] : 0
  262. */
  263. std::map<uint64_t, BoundaryPoint> Boundaries;
  264. for (const auto &Item : Ranges) {
  265. assert(Item.first.first <= Item.first.second &&
  266. "Invalid instruction range");
  267. auto &BeginPoint = Boundaries[Item.first.first];
  268. auto &EndPoint = Boundaries[Item.first.second];
  269. uint64_t Count = Item.second;
  270. BeginPoint.addBeginCount(Count);
  271. EndPoint.addEndCount(Count);
  272. if (Count == 0) {
  273. BeginPoint.IsZeroRangeBegin = true;
  274. EndPoint.IsZeroRangeEnd = true;
  275. }
  276. }
  277. // Use UINT64_MAX to indicate there is no existing range between BeginAddress
  278. // and the next valid address
  279. uint64_t BeginAddress = UINT64_MAX;
  280. int ZeroRangeDepth = 0;
  281. uint64_t Count = 0;
  282. for (const auto &Item : Boundaries) {
  283. uint64_t Address = Item.first;
  284. const BoundaryPoint &Point = Item.second;
  285. if (Point.BeginCount != UINT64_MAX) {
  286. if (BeginAddress != UINT64_MAX)
  287. DisjointRanges[{BeginAddress, Address - 1}] = Count;
  288. Count += Point.BeginCount;
  289. BeginAddress = Address;
  290. ZeroRangeDepth += Point.IsZeroRangeBegin;
  291. }
  292. if (Point.EndCount != UINT64_MAX) {
  293. assert((BeginAddress != UINT64_MAX) &&
  294. "First boundary point cannot be 'end' point");
  295. DisjointRanges[{BeginAddress, Address}] = Count;
  296. assert(Count >= Point.EndCount && "Mismatched live ranges");
  297. Count -= Point.EndCount;
  298. BeginAddress = Address + 1;
  299. ZeroRangeDepth -= Point.IsZeroRangeEnd;
  300. // If the remaining count is zero and it's no longer in a zero range, this
  301. // means we consume all the ranges before, thus mark BeginAddress as
  302. // UINT64_MAX. e.g. supposing we have two non-overlapping ranges:
  303. // [<---- 10 ---->]
  304. // [<---- 20 ---->]
  305. // A B C D
  306. // The BeginAddress(B+1) will reset to invalid(UINT64_MAX), so we won't
  307. // have the [B+1, C-1] zero range.
  308. if (Count == 0 && ZeroRangeDepth == 0)
  309. BeginAddress = UINT64_MAX;
  310. }
  311. }
  312. }
  313. void ProfileGeneratorBase::updateBodySamplesforFunctionProfile(
  314. FunctionSamples &FunctionProfile, const SampleContextFrame &LeafLoc,
  315. uint64_t Count) {
  316. // Use the maximum count of samples with same line location
  317. uint32_t Discriminator = getBaseDiscriminator(LeafLoc.Location.Discriminator);
  318. // Use duplication factor to compensated for loop unroll/vectorization.
  319. // Note that this is only needed when we're taking MAX of the counts at
  320. // the location instead of SUM.
  321. Count *= getDuplicationFactor(LeafLoc.Location.Discriminator);
  322. ErrorOr<uint64_t> R =
  323. FunctionProfile.findSamplesAt(LeafLoc.Location.LineOffset, Discriminator);
  324. uint64_t PreviousCount = R ? R.get() : 0;
  325. if (PreviousCount <= Count) {
  326. FunctionProfile.addBodySamples(LeafLoc.Location.LineOffset, Discriminator,
  327. Count - PreviousCount);
  328. }
  329. }
  330. void ProfileGeneratorBase::updateTotalSamples() {
  331. for (auto &Item : ProfileMap) {
  332. FunctionSamples &FunctionProfile = Item.second;
  333. FunctionProfile.updateTotalSamples();
  334. }
  335. }
  336. void ProfileGeneratorBase::updateCallsiteSamples() {
  337. for (auto &Item : ProfileMap) {
  338. FunctionSamples &FunctionProfile = Item.second;
  339. FunctionProfile.updateCallsiteSamples();
  340. }
  341. }
  342. void ProfileGeneratorBase::updateFunctionSamples() {
  343. updateCallsiteSamples();
  344. if (UpdateTotalSamples)
  345. updateTotalSamples();
  346. }
  347. void ProfileGeneratorBase::collectProfiledFunctions() {
  348. std::unordered_set<const BinaryFunction *> ProfiledFunctions;
  349. if (collectFunctionsFromRawProfile(ProfiledFunctions))
  350. Binary->setProfiledFunctions(ProfiledFunctions);
  351. else if (collectFunctionsFromLLVMProfile(ProfiledFunctions))
  352. Binary->setProfiledFunctions(ProfiledFunctions);
  353. else
  354. llvm_unreachable("Unsupported input profile");
  355. }
  356. bool ProfileGeneratorBase::collectFunctionsFromRawProfile(
  357. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) {
  358. if (!SampleCounters)
  359. return false;
  360. // Go through all the stacks, ranges and branches in sample counters, use
  361. // the start of the range to look up the function it belongs and record the
  362. // function.
  363. for (const auto &CI : *SampleCounters) {
  364. if (const auto *CtxKey = dyn_cast<AddrBasedCtxKey>(CI.first.getPtr())) {
  365. for (auto StackAddr : CtxKey->Context) {
  366. if (FuncRange *FRange = Binary->findFuncRange(StackAddr))
  367. ProfiledFunctions.insert(FRange->Func);
  368. }
  369. }
  370. for (auto Item : CI.second.RangeCounter) {
  371. uint64_t StartAddress = Item.first.first;
  372. if (FuncRange *FRange = Binary->findFuncRange(StartAddress))
  373. ProfiledFunctions.insert(FRange->Func);
  374. }
  375. for (auto Item : CI.second.BranchCounter) {
  376. uint64_t SourceAddress = Item.first.first;
  377. uint64_t TargetAddress = Item.first.second;
  378. if (FuncRange *FRange = Binary->findFuncRange(SourceAddress))
  379. ProfiledFunctions.insert(FRange->Func);
  380. if (FuncRange *FRange = Binary->findFuncRange(TargetAddress))
  381. ProfiledFunctions.insert(FRange->Func);
  382. }
  383. }
  384. return true;
  385. }
  386. bool ProfileGenerator::collectFunctionsFromLLVMProfile(
  387. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) {
  388. for (const auto &FS : ProfileMap) {
  389. if (auto *Func = Binary->getBinaryFunction(FS.first.getName()))
  390. ProfiledFunctions.insert(Func);
  391. }
  392. return true;
  393. }
  394. bool CSProfileGenerator::collectFunctionsFromLLVMProfile(
  395. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) {
  396. for (auto *Node : ContextTracker) {
  397. if (!Node->getFuncName().empty())
  398. if (auto *Func = Binary->getBinaryFunction(Node->getFuncName()))
  399. ProfiledFunctions.insert(Func);
  400. }
  401. return true;
  402. }
  403. FunctionSamples &
  404. ProfileGenerator::getTopLevelFunctionProfile(StringRef FuncName) {
  405. SampleContext Context(FuncName);
  406. auto Ret = ProfileMap.emplace(Context, FunctionSamples());
  407. if (Ret.second) {
  408. FunctionSamples &FProfile = Ret.first->second;
  409. FProfile.setContext(Context);
  410. }
  411. return Ret.first->second;
  412. }
  413. void ProfileGenerator::generateProfile() {
  414. collectProfiledFunctions();
  415. if (Binary->usePseudoProbes())
  416. Binary->decodePseudoProbe();
  417. if (SampleCounters) {
  418. if (Binary->usePseudoProbes()) {
  419. generateProbeBasedProfile();
  420. } else {
  421. generateLineNumBasedProfile();
  422. }
  423. }
  424. postProcessProfiles();
  425. }
  426. void ProfileGenerator::postProcessProfiles() {
  427. computeSummaryAndThreshold(ProfileMap);
  428. trimColdProfiles(ProfileMap, ColdCountThreshold);
  429. calculateAndShowDensity(ProfileMap);
  430. }
  431. void ProfileGenerator::trimColdProfiles(const SampleProfileMap &Profiles,
  432. uint64_t ColdCntThreshold) {
  433. if (!TrimColdProfile)
  434. return;
  435. // Move cold profiles into a tmp container.
  436. std::vector<SampleContext> ColdProfiles;
  437. for (const auto &I : ProfileMap) {
  438. if (I.second.getTotalSamples() < ColdCntThreshold)
  439. ColdProfiles.emplace_back(I.first);
  440. }
  441. // Remove the cold profile from ProfileMap.
  442. for (const auto &I : ColdProfiles)
  443. ProfileMap.erase(I);
  444. }
  445. void ProfileGenerator::generateLineNumBasedProfile() {
  446. assert(SampleCounters->size() == 1 &&
  447. "Must have one entry for profile generation.");
  448. const SampleCounter &SC = SampleCounters->begin()->second;
  449. // Fill in function body samples
  450. populateBodySamplesForAllFunctions(SC.RangeCounter);
  451. // Fill in boundary sample counts as well as call site samples for calls
  452. populateBoundarySamplesForAllFunctions(SC.BranchCounter);
  453. updateFunctionSamples();
  454. }
  455. void ProfileGenerator::generateProbeBasedProfile() {
  456. assert(SampleCounters->size() == 1 &&
  457. "Must have one entry for profile generation.");
  458. // Enable pseudo probe functionalities in SampleProf
  459. FunctionSamples::ProfileIsProbeBased = true;
  460. const SampleCounter &SC = SampleCounters->begin()->second;
  461. // Fill in function body samples
  462. populateBodySamplesWithProbesForAllFunctions(SC.RangeCounter);
  463. // Fill in boundary sample counts as well as call site samples for calls
  464. populateBoundarySamplesWithProbesForAllFunctions(SC.BranchCounter);
  465. updateFunctionSamples();
  466. }
  467. void ProfileGenerator::populateBodySamplesWithProbesForAllFunctions(
  468. const RangeSample &RangeCounter) {
  469. ProbeCounterMap ProbeCounter;
  470. // preprocessRangeCounter returns disjoint ranges, so no longer to redo it
  471. // inside extractProbesFromRange.
  472. extractProbesFromRange(preprocessRangeCounter(RangeCounter), ProbeCounter,
  473. false);
  474. for (const auto &PI : ProbeCounter) {
  475. const MCDecodedPseudoProbe *Probe = PI.first;
  476. uint64_t Count = PI.second;
  477. SampleContextFrameVector FrameVec;
  478. Binary->getInlineContextForProbe(Probe, FrameVec, true);
  479. FunctionSamples &FunctionProfile =
  480. getLeafProfileAndAddTotalSamples(FrameVec, Count);
  481. FunctionProfile.addBodySamplesForProbe(Probe->getIndex(), Count);
  482. if (Probe->isEntry())
  483. FunctionProfile.addHeadSamples(Count);
  484. }
  485. }
  486. void ProfileGenerator::populateBoundarySamplesWithProbesForAllFunctions(
  487. const BranchSample &BranchCounters) {
  488. for (const auto &Entry : BranchCounters) {
  489. uint64_t SourceAddress = Entry.first.first;
  490. uint64_t TargetAddress = Entry.first.second;
  491. uint64_t Count = Entry.second;
  492. assert(Count != 0 && "Unexpected zero weight branch");
  493. StringRef CalleeName = getCalleeNameForAddress(TargetAddress);
  494. if (CalleeName.size() == 0)
  495. continue;
  496. const MCDecodedPseudoProbe *CallProbe =
  497. Binary->getCallProbeForAddr(SourceAddress);
  498. if (CallProbe == nullptr)
  499. continue;
  500. // Record called target sample and its count.
  501. SampleContextFrameVector FrameVec;
  502. Binary->getInlineContextForProbe(CallProbe, FrameVec, true);
  503. if (!FrameVec.empty()) {
  504. FunctionSamples &FunctionProfile =
  505. getLeafProfileAndAddTotalSamples(FrameVec, 0);
  506. FunctionProfile.addCalledTargetSamples(
  507. FrameVec.back().Location.LineOffset, 0, CalleeName, Count);
  508. }
  509. }
  510. }
  511. FunctionSamples &ProfileGenerator::getLeafProfileAndAddTotalSamples(
  512. const SampleContextFrameVector &FrameVec, uint64_t Count) {
  513. // Get top level profile
  514. FunctionSamples *FunctionProfile =
  515. &getTopLevelFunctionProfile(FrameVec[0].FuncName);
  516. FunctionProfile->addTotalSamples(Count);
  517. if (Binary->usePseudoProbes()) {
  518. const auto *FuncDesc = Binary->getFuncDescForGUID(
  519. Function::getGUID(FunctionProfile->getName()));
  520. FunctionProfile->setFunctionHash(FuncDesc->FuncHash);
  521. }
  522. for (size_t I = 1; I < FrameVec.size(); I++) {
  523. LineLocation Callsite(
  524. FrameVec[I - 1].Location.LineOffset,
  525. getBaseDiscriminator(FrameVec[I - 1].Location.Discriminator));
  526. FunctionSamplesMap &SamplesMap =
  527. FunctionProfile->functionSamplesAt(Callsite);
  528. auto Ret =
  529. SamplesMap.emplace(FrameVec[I].FuncName.str(), FunctionSamples());
  530. if (Ret.second) {
  531. SampleContext Context(FrameVec[I].FuncName);
  532. Ret.first->second.setContext(Context);
  533. }
  534. FunctionProfile = &Ret.first->second;
  535. FunctionProfile->addTotalSamples(Count);
  536. if (Binary->usePseudoProbes()) {
  537. const auto *FuncDesc = Binary->getFuncDescForGUID(
  538. Function::getGUID(FunctionProfile->getName()));
  539. FunctionProfile->setFunctionHash(FuncDesc->FuncHash);
  540. }
  541. }
  542. return *FunctionProfile;
  543. }
  544. RangeSample
  545. ProfileGenerator::preprocessRangeCounter(const RangeSample &RangeCounter) {
  546. RangeSample Ranges(RangeCounter.begin(), RangeCounter.end());
  547. if (FillZeroForAllFuncs) {
  548. for (auto &FuncI : Binary->getAllBinaryFunctions()) {
  549. for (auto &R : FuncI.second.Ranges) {
  550. Ranges[{R.first, R.second - 1}] += 0;
  551. }
  552. }
  553. } else {
  554. // For each range, we search for all ranges of the function it belongs to
  555. // and initialize it with zero count, so it remains zero if doesn't hit any
  556. // samples. This is to be consistent with compiler that interpret zero count
  557. // as unexecuted(cold).
  558. for (const auto &I : RangeCounter) {
  559. uint64_t StartAddress = I.first.first;
  560. for (const auto &Range : Binary->getRanges(StartAddress))
  561. Ranges[{Range.first, Range.second - 1}] += 0;
  562. }
  563. }
  564. RangeSample DisjointRanges;
  565. findDisjointRanges(DisjointRanges, Ranges);
  566. return DisjointRanges;
  567. }
  568. void ProfileGenerator::populateBodySamplesForAllFunctions(
  569. const RangeSample &RangeCounter) {
  570. for (const auto &Range : preprocessRangeCounter(RangeCounter)) {
  571. uint64_t RangeBegin = Range.first.first;
  572. uint64_t RangeEnd = Range.first.second;
  573. uint64_t Count = Range.second;
  574. InstructionPointer IP(Binary, RangeBegin, true);
  575. // Disjoint ranges may have range in the middle of two instr,
  576. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  577. // can be Addr1+1 to Addr2-1. We should ignore such range.
  578. if (IP.Address > RangeEnd)
  579. continue;
  580. do {
  581. const SampleContextFrameVector FrameVec =
  582. Binary->getFrameLocationStack(IP.Address);
  583. if (!FrameVec.empty()) {
  584. // FIXME: As accumulating total count per instruction caused some
  585. // regression, we changed to accumulate total count per byte as a
  586. // workaround. Tuning hotness threshold on the compiler side might be
  587. // necessary in the future.
  588. FunctionSamples &FunctionProfile = getLeafProfileAndAddTotalSamples(
  589. FrameVec, Count * Binary->getInstSize(IP.Address));
  590. updateBodySamplesforFunctionProfile(FunctionProfile, FrameVec.back(),
  591. Count);
  592. }
  593. } while (IP.advance() && IP.Address <= RangeEnd);
  594. }
  595. }
  596. StringRef
  597. ProfileGeneratorBase::getCalleeNameForAddress(uint64_t TargetAddress) {
  598. // Get the function range by branch target if it's a call branch.
  599. auto *FRange = Binary->findFuncRangeForStartAddr(TargetAddress);
  600. // We won't accumulate sample count for a range whose start is not the real
  601. // function entry such as outlined function or inner labels.
  602. if (!FRange || !FRange->IsFuncEntry)
  603. return StringRef();
  604. return FunctionSamples::getCanonicalFnName(FRange->getFuncName());
  605. }
  606. void ProfileGenerator::populateBoundarySamplesForAllFunctions(
  607. const BranchSample &BranchCounters) {
  608. for (const auto &Entry : BranchCounters) {
  609. uint64_t SourceAddress = Entry.first.first;
  610. uint64_t TargetAddress = Entry.first.second;
  611. uint64_t Count = Entry.second;
  612. assert(Count != 0 && "Unexpected zero weight branch");
  613. StringRef CalleeName = getCalleeNameForAddress(TargetAddress);
  614. if (CalleeName.size() == 0)
  615. continue;
  616. // Record called target sample and its count.
  617. const SampleContextFrameVector &FrameVec =
  618. Binary->getCachedFrameLocationStack(SourceAddress);
  619. if (!FrameVec.empty()) {
  620. FunctionSamples &FunctionProfile =
  621. getLeafProfileAndAddTotalSamples(FrameVec, 0);
  622. FunctionProfile.addCalledTargetSamples(
  623. FrameVec.back().Location.LineOffset,
  624. getBaseDiscriminator(FrameVec.back().Location.Discriminator),
  625. CalleeName, Count);
  626. }
  627. // Add head samples for callee.
  628. FunctionSamples &CalleeProfile = getTopLevelFunctionProfile(CalleeName);
  629. CalleeProfile.addHeadSamples(Count);
  630. }
  631. }
  632. void ProfileGeneratorBase::calculateAndShowDensity(
  633. const SampleProfileMap &Profiles) {
  634. double Density = calculateDensity(Profiles, HotCountThreshold);
  635. showDensitySuggestion(Density);
  636. }
  637. FunctionSamples *
  638. CSProfileGenerator::getOrCreateFunctionSamples(ContextTrieNode *ContextNode,
  639. bool WasLeafInlined) {
  640. FunctionSamples *FProfile = ContextNode->getFunctionSamples();
  641. if (!FProfile) {
  642. FSamplesList.emplace_back();
  643. FProfile = &FSamplesList.back();
  644. FProfile->setName(ContextNode->getFuncName());
  645. ContextNode->setFunctionSamples(FProfile);
  646. }
  647. // Update ContextWasInlined attribute for existing contexts.
  648. // The current function can be called in two ways:
  649. // - when processing a probe of the current frame
  650. // - when processing the entry probe of an inlinee's frame, which
  651. // is then used to update the callsite count of the current frame.
  652. // The two can happen in any order, hence here we are making sure
  653. // `ContextWasInlined` is always set as expected.
  654. // TODO: Note that the former does not always happen if no probes of the
  655. // current frame has samples, and if the latter happens, we could lose the
  656. // attribute. This should be fixed.
  657. if (WasLeafInlined)
  658. FProfile->getContext().setAttribute(ContextWasInlined);
  659. return FProfile;
  660. }
  661. ContextTrieNode *
  662. CSProfileGenerator::getOrCreateContextNode(const SampleContextFrames Context,
  663. bool WasLeafInlined) {
  664. ContextTrieNode *ContextNode =
  665. ContextTracker.getOrCreateContextPath(Context, true);
  666. getOrCreateFunctionSamples(ContextNode, WasLeafInlined);
  667. return ContextNode;
  668. }
  669. void CSProfileGenerator::generateProfile() {
  670. FunctionSamples::ProfileIsCS = true;
  671. collectProfiledFunctions();
  672. if (Binary->usePseudoProbes()) {
  673. Binary->decodePseudoProbe();
  674. if (InferMissingFrames)
  675. initializeMissingFrameInferrer();
  676. }
  677. if (SampleCounters) {
  678. if (Binary->usePseudoProbes()) {
  679. generateProbeBasedProfile();
  680. } else {
  681. generateLineNumBasedProfile();
  682. }
  683. }
  684. if (Binary->getTrackFuncContextSize())
  685. computeSizeForProfiledFunctions();
  686. postProcessProfiles();
  687. }
  688. void CSProfileGenerator::initializeMissingFrameInferrer() {
  689. Binary->getMissingContextInferrer()->initialize(SampleCounters);
  690. }
  691. void CSProfileGenerator::inferMissingFrames(
  692. const SmallVectorImpl<uint64_t> &Context,
  693. SmallVectorImpl<uint64_t> &NewContext) {
  694. Binary->inferMissingFrames(Context, NewContext);
  695. }
  696. void CSProfileGenerator::computeSizeForProfiledFunctions() {
  697. for (auto *Func : Binary->getProfiledFunctions())
  698. Binary->computeInlinedContextSizeForFunc(Func);
  699. // Flush the symbolizer to save memory.
  700. Binary->flushSymbolizer();
  701. }
  702. void CSProfileGenerator::updateFunctionSamples() {
  703. for (auto *Node : ContextTracker) {
  704. FunctionSamples *FSamples = Node->getFunctionSamples();
  705. if (FSamples) {
  706. if (UpdateTotalSamples)
  707. FSamples->updateTotalSamples();
  708. FSamples->updateCallsiteSamples();
  709. }
  710. }
  711. }
  712. void CSProfileGenerator::generateLineNumBasedProfile() {
  713. for (const auto &CI : *SampleCounters) {
  714. const auto *CtxKey = cast<StringBasedCtxKey>(CI.first.getPtr());
  715. ContextTrieNode *ContextNode = &getRootContext();
  716. // Sample context will be empty if the jump is an external-to-internal call
  717. // pattern, the head samples should be added for the internal function.
  718. if (!CtxKey->Context.empty()) {
  719. // Get or create function profile for the range
  720. ContextNode =
  721. getOrCreateContextNode(CtxKey->Context, CtxKey->WasLeafInlined);
  722. // Fill in function body samples
  723. populateBodySamplesForFunction(*ContextNode->getFunctionSamples(),
  724. CI.second.RangeCounter);
  725. }
  726. // Fill in boundary sample counts as well as call site samples for calls
  727. populateBoundarySamplesForFunction(ContextNode, CI.second.BranchCounter);
  728. }
  729. // Fill in call site value sample for inlined calls and also use context to
  730. // infer missing samples. Since we don't have call count for inlined
  731. // functions, we estimate it from inlinee's profile using the entry of the
  732. // body sample.
  733. populateInferredFunctionSamples(getRootContext());
  734. updateFunctionSamples();
  735. }
  736. void CSProfileGenerator::populateBodySamplesForFunction(
  737. FunctionSamples &FunctionProfile, const RangeSample &RangeCounter) {
  738. // Compute disjoint ranges first, so we can use MAX
  739. // for calculating count for each location.
  740. RangeSample Ranges;
  741. findDisjointRanges(Ranges, RangeCounter);
  742. for (const auto &Range : Ranges) {
  743. uint64_t RangeBegin = Range.first.first;
  744. uint64_t RangeEnd = Range.first.second;
  745. uint64_t Count = Range.second;
  746. // Disjoint ranges have introduce zero-filled gap that
  747. // doesn't belong to current context, filter them out.
  748. if (Count == 0)
  749. continue;
  750. InstructionPointer IP(Binary, RangeBegin, true);
  751. // Disjoint ranges may have range in the middle of two instr,
  752. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  753. // can be Addr1+1 to Addr2-1. We should ignore such range.
  754. if (IP.Address > RangeEnd)
  755. continue;
  756. do {
  757. auto LeafLoc = Binary->getInlineLeafFrameLoc(IP.Address);
  758. if (LeafLoc) {
  759. // Recording body sample for this specific context
  760. updateBodySamplesforFunctionProfile(FunctionProfile, *LeafLoc, Count);
  761. FunctionProfile.addTotalSamples(Count);
  762. }
  763. } while (IP.advance() && IP.Address <= RangeEnd);
  764. }
  765. }
  766. void CSProfileGenerator::populateBoundarySamplesForFunction(
  767. ContextTrieNode *Node, const BranchSample &BranchCounters) {
  768. for (const auto &Entry : BranchCounters) {
  769. uint64_t SourceAddress = Entry.first.first;
  770. uint64_t TargetAddress = Entry.first.second;
  771. uint64_t Count = Entry.second;
  772. assert(Count != 0 && "Unexpected zero weight branch");
  773. StringRef CalleeName = getCalleeNameForAddress(TargetAddress);
  774. if (CalleeName.size() == 0)
  775. continue;
  776. ContextTrieNode *CallerNode = Node;
  777. LineLocation CalleeCallSite(0, 0);
  778. if (CallerNode != &getRootContext()) {
  779. // Record called target sample and its count
  780. auto LeafLoc = Binary->getInlineLeafFrameLoc(SourceAddress);
  781. if (LeafLoc) {
  782. CallerNode->getFunctionSamples()->addCalledTargetSamples(
  783. LeafLoc->Location.LineOffset,
  784. getBaseDiscriminator(LeafLoc->Location.Discriminator), CalleeName,
  785. Count);
  786. // Record head sample for called target(callee)
  787. CalleeCallSite = LeafLoc->Location;
  788. }
  789. }
  790. ContextTrieNode *CalleeNode =
  791. CallerNode->getOrCreateChildContext(CalleeCallSite, CalleeName);
  792. FunctionSamples *CalleeProfile = getOrCreateFunctionSamples(CalleeNode);
  793. CalleeProfile->addHeadSamples(Count);
  794. }
  795. }
  796. void CSProfileGenerator::populateInferredFunctionSamples(
  797. ContextTrieNode &Node) {
  798. // There is no call jmp sample between the inliner and inlinee, we need to use
  799. // the inlinee's context to infer inliner's context, i.e. parent(inliner)'s
  800. // sample depends on child(inlinee)'s sample, so traverse the tree in
  801. // post-order.
  802. for (auto &It : Node.getAllChildContext())
  803. populateInferredFunctionSamples(It.second);
  804. FunctionSamples *CalleeProfile = Node.getFunctionSamples();
  805. if (!CalleeProfile)
  806. return;
  807. // If we already have head sample counts, we must have value profile
  808. // for call sites added already. Skip to avoid double counting.
  809. if (CalleeProfile->getHeadSamples())
  810. return;
  811. ContextTrieNode *CallerNode = Node.getParentContext();
  812. // If we don't have context, nothing to do for caller's call site.
  813. // This could happen for entry point function.
  814. if (CallerNode == &getRootContext())
  815. return;
  816. LineLocation CallerLeafFrameLoc = Node.getCallSiteLoc();
  817. FunctionSamples &CallerProfile = *getOrCreateFunctionSamples(CallerNode);
  818. // Since we don't have call count for inlined functions, we
  819. // estimate it from inlinee's profile using entry body sample.
  820. uint64_t EstimatedCallCount = CalleeProfile->getHeadSamplesEstimate();
  821. // If we don't have samples with location, use 1 to indicate live.
  822. if (!EstimatedCallCount && !CalleeProfile->getBodySamples().size())
  823. EstimatedCallCount = 1;
  824. CallerProfile.addCalledTargetSamples(CallerLeafFrameLoc.LineOffset,
  825. CallerLeafFrameLoc.Discriminator,
  826. Node.getFuncName(), EstimatedCallCount);
  827. CallerProfile.addBodySamples(CallerLeafFrameLoc.LineOffset,
  828. CallerLeafFrameLoc.Discriminator,
  829. EstimatedCallCount);
  830. CallerProfile.addTotalSamples(EstimatedCallCount);
  831. }
  832. void CSProfileGenerator::convertToProfileMap(
  833. ContextTrieNode &Node, SampleContextFrameVector &Context) {
  834. FunctionSamples *FProfile = Node.getFunctionSamples();
  835. if (FProfile) {
  836. Context.emplace_back(Node.getFuncName(), LineLocation(0, 0));
  837. // Save the new context for future references.
  838. SampleContextFrames NewContext = *Contexts.insert(Context).first;
  839. auto Ret = ProfileMap.emplace(NewContext, std::move(*FProfile));
  840. FunctionSamples &NewProfile = Ret.first->second;
  841. NewProfile.getContext().setContext(NewContext);
  842. Context.pop_back();
  843. }
  844. for (auto &It : Node.getAllChildContext()) {
  845. ContextTrieNode &ChildNode = It.second;
  846. Context.emplace_back(Node.getFuncName(), ChildNode.getCallSiteLoc());
  847. convertToProfileMap(ChildNode, Context);
  848. Context.pop_back();
  849. }
  850. }
  851. void CSProfileGenerator::convertToProfileMap() {
  852. assert(ProfileMap.empty() &&
  853. "ProfileMap should be empty before converting from the trie");
  854. assert(IsProfileValidOnTrie &&
  855. "Do not convert the trie twice, it's already destroyed");
  856. SampleContextFrameVector Context;
  857. for (auto &It : getRootContext().getAllChildContext())
  858. convertToProfileMap(It.second, Context);
  859. IsProfileValidOnTrie = false;
  860. }
  861. void CSProfileGenerator::postProcessProfiles() {
  862. // Compute hot/cold threshold based on profile. This will be used for cold
  863. // context profile merging/trimming.
  864. computeSummaryAndThreshold();
  865. // Run global pre-inliner to adjust/merge context profile based on estimated
  866. // inline decisions.
  867. if (EnableCSPreInliner) {
  868. ContextTracker.populateFuncToCtxtMap();
  869. CSPreInliner(ContextTracker, *Binary, Summary.get()).run();
  870. // Turn off the profile merger by default unless it is explicitly enabled.
  871. if (!CSProfMergeColdContext.getNumOccurrences())
  872. CSProfMergeColdContext = false;
  873. }
  874. convertToProfileMap();
  875. // Trim and merge cold context profile using cold threshold above.
  876. if (TrimColdProfile || CSProfMergeColdContext) {
  877. SampleContextTrimmer(ProfileMap)
  878. .trimAndMergeColdContextProfiles(
  879. HotCountThreshold, TrimColdProfile, CSProfMergeColdContext,
  880. CSProfMaxColdContextDepth, EnableCSPreInliner);
  881. }
  882. // Merge function samples of CS profile to calculate profile density.
  883. sampleprof::SampleProfileMap ContextLessProfiles;
  884. for (const auto &I : ProfileMap) {
  885. ContextLessProfiles[I.second.getName()].merge(I.second);
  886. }
  887. calculateAndShowDensity(ContextLessProfiles);
  888. if (GenCSNestedProfile) {
  889. CSProfileConverter CSConverter(ProfileMap);
  890. CSConverter.convertProfiles();
  891. FunctionSamples::ProfileIsCS = false;
  892. }
  893. }
  894. void ProfileGeneratorBase::computeSummaryAndThreshold(
  895. SampleProfileMap &Profiles) {
  896. SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
  897. Summary = Builder.computeSummaryForProfiles(Profiles);
  898. HotCountThreshold = ProfileSummaryBuilder::getHotCountThreshold(
  899. (Summary->getDetailedSummary()));
  900. ColdCountThreshold = ProfileSummaryBuilder::getColdCountThreshold(
  901. (Summary->getDetailedSummary()));
  902. }
  903. void CSProfileGenerator::computeSummaryAndThreshold() {
  904. // Always merge and use context-less profile map to compute summary.
  905. SampleProfileMap ContextLessProfiles;
  906. ContextTracker.createContextLessProfileMap(ContextLessProfiles);
  907. // Set the flag below to avoid merging the profile again in
  908. // computeSummaryAndThreshold
  909. FunctionSamples::ProfileIsCS = false;
  910. assert(
  911. (!UseContextLessSummary.getNumOccurrences() || UseContextLessSummary) &&
  912. "Don't set --profile-summary-contextless to false for profile "
  913. "generation");
  914. ProfileGeneratorBase::computeSummaryAndThreshold(ContextLessProfiles);
  915. // Recover the old value.
  916. FunctionSamples::ProfileIsCS = true;
  917. }
  918. void ProfileGeneratorBase::extractProbesFromRange(
  919. const RangeSample &RangeCounter, ProbeCounterMap &ProbeCounter,
  920. bool FindDisjointRanges) {
  921. const RangeSample *PRanges = &RangeCounter;
  922. RangeSample Ranges;
  923. if (FindDisjointRanges) {
  924. findDisjointRanges(Ranges, RangeCounter);
  925. PRanges = &Ranges;
  926. }
  927. for (const auto &Range : *PRanges) {
  928. uint64_t RangeBegin = Range.first.first;
  929. uint64_t RangeEnd = Range.first.second;
  930. uint64_t Count = Range.second;
  931. InstructionPointer IP(Binary, RangeBegin, true);
  932. // Disjoint ranges may have range in the middle of two instr,
  933. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  934. // can be Addr1+1 to Addr2-1. We should ignore such range.
  935. if (IP.Address > RangeEnd)
  936. continue;
  937. do {
  938. const AddressProbesMap &Address2ProbesMap =
  939. Binary->getAddress2ProbesMap();
  940. auto It = Address2ProbesMap.find(IP.Address);
  941. if (It != Address2ProbesMap.end()) {
  942. for (const auto &Probe : It->second) {
  943. ProbeCounter[&Probe] += Count;
  944. }
  945. }
  946. } while (IP.advance() && IP.Address <= RangeEnd);
  947. }
  948. }
  949. static void extractPrefixContextStack(SampleContextFrameVector &ContextStack,
  950. const SmallVectorImpl<uint64_t> &AddrVec,
  951. ProfiledBinary *Binary) {
  952. SmallVector<const MCDecodedPseudoProbe *, 16> Probes;
  953. for (auto Address : reverse(AddrVec)) {
  954. const MCDecodedPseudoProbe *CallProbe =
  955. Binary->getCallProbeForAddr(Address);
  956. // These could be the cases when a probe is not found at a calliste. Cutting
  957. // off the context from here since the inliner will not know how to consume
  958. // a context with unknown callsites.
  959. // 1. for functions that are not sampled when
  960. // --decode-probe-for-profiled-functions-only is on.
  961. // 2. for a merged callsite. Callsite merging may cause the loss of original
  962. // probe IDs.
  963. // 3. for an external callsite.
  964. if (!CallProbe)
  965. break;
  966. Probes.push_back(CallProbe);
  967. }
  968. std::reverse(Probes.begin(), Probes.end());
  969. // Extract context stack for reusing, leaf context stack will be added
  970. // compressed while looking up function profile.
  971. for (const auto *P : Probes) {
  972. Binary->getInlineContextForProbe(P, ContextStack, true);
  973. }
  974. }
  975. void CSProfileGenerator::generateProbeBasedProfile() {
  976. // Enable pseudo probe functionalities in SampleProf
  977. FunctionSamples::ProfileIsProbeBased = true;
  978. for (const auto &CI : *SampleCounters) {
  979. const AddrBasedCtxKey *CtxKey =
  980. dyn_cast<AddrBasedCtxKey>(CI.first.getPtr());
  981. // Fill in function body samples from probes, also infer caller's samples
  982. // from callee's probe
  983. populateBodySamplesWithProbes(CI.second.RangeCounter, CtxKey);
  984. // Fill in boundary samples for a call probe
  985. populateBoundarySamplesWithProbes(CI.second.BranchCounter, CtxKey);
  986. }
  987. }
  988. void CSProfileGenerator::populateBodySamplesWithProbes(
  989. const RangeSample &RangeCounter, const AddrBasedCtxKey *CtxKey) {
  990. ProbeCounterMap ProbeCounter;
  991. // Extract the top frame probes by looking up each address among the range in
  992. // the Address2ProbeMap
  993. extractProbesFromRange(RangeCounter, ProbeCounter);
  994. std::unordered_map<MCDecodedPseudoProbeInlineTree *,
  995. std::unordered_set<FunctionSamples *>>
  996. FrameSamples;
  997. for (const auto &PI : ProbeCounter) {
  998. const MCDecodedPseudoProbe *Probe = PI.first;
  999. uint64_t Count = PI.second;
  1000. // Disjoint ranges have introduce zero-filled gap that
  1001. // doesn't belong to current context, filter them out.
  1002. if (!Probe->isBlock() || Count == 0)
  1003. continue;
  1004. ContextTrieNode *ContextNode = getContextNodeForLeafProbe(CtxKey, Probe);
  1005. FunctionSamples &FunctionProfile = *ContextNode->getFunctionSamples();
  1006. // Record the current frame and FunctionProfile whenever samples are
  1007. // collected for non-danglie probes. This is for reporting all of the
  1008. // zero count probes of the frame later.
  1009. FrameSamples[Probe->getInlineTreeNode()].insert(&FunctionProfile);
  1010. FunctionProfile.addBodySamplesForProbe(Probe->getIndex(), Count);
  1011. FunctionProfile.addTotalSamples(Count);
  1012. if (Probe->isEntry()) {
  1013. FunctionProfile.addHeadSamples(Count);
  1014. // Look up for the caller's function profile
  1015. const auto *InlinerDesc = Binary->getInlinerDescForProbe(Probe);
  1016. ContextTrieNode *CallerNode = ContextNode->getParentContext();
  1017. if (InlinerDesc != nullptr && CallerNode != &getRootContext()) {
  1018. // Since the context id will be compressed, we have to use callee's
  1019. // context id to infer caller's context id to ensure they share the
  1020. // same context prefix.
  1021. uint64_t CallerIndex = ContextNode->getCallSiteLoc().LineOffset;
  1022. assert(CallerIndex &&
  1023. "Inferred caller's location index shouldn't be zero!");
  1024. FunctionSamples &CallerProfile =
  1025. *getOrCreateFunctionSamples(CallerNode);
  1026. CallerProfile.setFunctionHash(InlinerDesc->FuncHash);
  1027. CallerProfile.addBodySamples(CallerIndex, 0, Count);
  1028. CallerProfile.addTotalSamples(Count);
  1029. CallerProfile.addCalledTargetSamples(CallerIndex, 0,
  1030. ContextNode->getFuncName(), Count);
  1031. }
  1032. }
  1033. }
  1034. // Assign zero count for remaining probes without sample hits to
  1035. // differentiate from probes optimized away, of which the counts are unknown
  1036. // and will be inferred by the compiler.
  1037. for (auto &I : FrameSamples) {
  1038. for (auto *FunctionProfile : I.second) {
  1039. for (auto *Probe : I.first->getProbes()) {
  1040. FunctionProfile->addBodySamplesForProbe(Probe->getIndex(), 0);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. void CSProfileGenerator::populateBoundarySamplesWithProbes(
  1046. const BranchSample &BranchCounter, const AddrBasedCtxKey *CtxKey) {
  1047. for (const auto &BI : BranchCounter) {
  1048. uint64_t SourceAddress = BI.first.first;
  1049. uint64_t TargetAddress = BI.first.second;
  1050. uint64_t Count = BI.second;
  1051. const MCDecodedPseudoProbe *CallProbe =
  1052. Binary->getCallProbeForAddr(SourceAddress);
  1053. if (CallProbe == nullptr)
  1054. continue;
  1055. FunctionSamples &FunctionProfile =
  1056. getFunctionProfileForLeafProbe(CtxKey, CallProbe);
  1057. FunctionProfile.addBodySamples(CallProbe->getIndex(), 0, Count);
  1058. FunctionProfile.addTotalSamples(Count);
  1059. StringRef CalleeName = getCalleeNameForAddress(TargetAddress);
  1060. if (CalleeName.size() == 0)
  1061. continue;
  1062. FunctionProfile.addCalledTargetSamples(CallProbe->getIndex(), 0, CalleeName,
  1063. Count);
  1064. }
  1065. }
  1066. ContextTrieNode *CSProfileGenerator::getContextNodeForLeafProbe(
  1067. const AddrBasedCtxKey *CtxKey, const MCDecodedPseudoProbe *LeafProbe) {
  1068. const SmallVectorImpl<uint64_t> *PContext = &CtxKey->Context;
  1069. SmallVector<uint64_t, 16> NewContext;
  1070. if (InferMissingFrames) {
  1071. SmallVector<uint64_t, 16> Context = CtxKey->Context;
  1072. // Append leaf frame for a complete inference.
  1073. Context.push_back(LeafProbe->getAddress());
  1074. inferMissingFrames(Context, NewContext);
  1075. // Pop out the leaf probe that was pushed in above.
  1076. NewContext.pop_back();
  1077. PContext = &NewContext;
  1078. }
  1079. SampleContextFrameVector ContextStack;
  1080. extractPrefixContextStack(ContextStack, *PContext, Binary);
  1081. // Explicitly copy the context for appending the leaf context
  1082. SampleContextFrameVector NewContextStack(ContextStack.begin(),
  1083. ContextStack.end());
  1084. Binary->getInlineContextForProbe(LeafProbe, NewContextStack, true);
  1085. // For leaf inlined context with the top frame, we should strip off the top
  1086. // frame's probe id, like:
  1087. // Inlined stack: [foo:1, bar:2], the ContextId will be "foo:1 @ bar"
  1088. auto LeafFrame = NewContextStack.back();
  1089. LeafFrame.Location = LineLocation(0, 0);
  1090. NewContextStack.pop_back();
  1091. // Compress the context string except for the leaf frame
  1092. CSProfileGenerator::compressRecursionContext(NewContextStack);
  1093. CSProfileGenerator::trimContext(NewContextStack);
  1094. NewContextStack.push_back(LeafFrame);
  1095. const auto *FuncDesc = Binary->getFuncDescForGUID(LeafProbe->getGuid());
  1096. bool WasLeafInlined = LeafProbe->getInlineTreeNode()->hasInlineSite();
  1097. ContextTrieNode *ContextNode =
  1098. getOrCreateContextNode(NewContextStack, WasLeafInlined);
  1099. ContextNode->getFunctionSamples()->setFunctionHash(FuncDesc->FuncHash);
  1100. return ContextNode;
  1101. }
  1102. FunctionSamples &CSProfileGenerator::getFunctionProfileForLeafProbe(
  1103. const AddrBasedCtxKey *CtxKey, const MCDecodedPseudoProbe *LeafProbe) {
  1104. return *getContextNodeForLeafProbe(CtxKey, LeafProbe)->getFunctionSamples();
  1105. }
  1106. } // end namespace sampleprof
  1107. } // end namespace llvm