SampleProfReader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
  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 file implements the class that reads LLVM sample profiles. It
  11. // supports three file formats: text, binary and gcov.
  12. //
  13. // The textual representation is useful for debugging and testing purposes. The
  14. // binary representation is more compact, resulting in smaller file sizes.
  15. //
  16. // The gcov encoding is the one generated by GCC's AutoFDO profile creation
  17. // tool (https://github.com/google/autofdo)
  18. //
  19. // All three encodings can be used interchangeably as an input sample profile.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ProfileData/SampleProfReader.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/IR/ProfileSummary.h"
  27. #include "llvm/ProfileData/ProfileCommon.h"
  28. #include "llvm/ProfileData/SampleProf.h"
  29. #include "llvm/Support/ErrorOr.h"
  30. #include "llvm/Support/LEB128.h"
  31. #include "llvm/Support/LineIterator.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <algorithm>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <limits>
  38. #include <memory>
  39. #include <system_error>
  40. #include <vector>
  41. using namespace llvm;
  42. using namespace sampleprof;
  43. /// Dump the function profile for \p FName.
  44. ///
  45. /// \param FName Name of the function to print.
  46. /// \param OS Stream to emit the output to.
  47. void SampleProfileReader::dumpFunctionProfile(StringRef FName,
  48. raw_ostream &OS) {
  49. OS << "Function: " << FName << ": " << Profiles[FName];
  50. }
  51. /// Dump all the function profiles found on stream \p OS.
  52. void SampleProfileReader::dump(raw_ostream &OS) {
  53. for (const auto &I : Profiles)
  54. dumpFunctionProfile(I.getKey(), OS);
  55. }
  56. /// Parse \p Input as function head.
  57. ///
  58. /// Parse one line of \p Input, and update function name in \p FName,
  59. /// function's total sample count in \p NumSamples, function's entry
  60. /// count in \p NumHeadSamples.
  61. ///
  62. /// \returns true if parsing is successful.
  63. static bool ParseHead(const StringRef &Input, StringRef &FName,
  64. uint64_t &NumSamples, uint64_t &NumHeadSamples) {
  65. if (Input[0] == ' ')
  66. return false;
  67. size_t n2 = Input.rfind(':');
  68. size_t n1 = Input.rfind(':', n2 - 1);
  69. FName = Input.substr(0, n1);
  70. if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
  71. return false;
  72. if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
  73. return false;
  74. return true;
  75. }
  76. /// Returns true if line offset \p L is legal (only has 16 bits).
  77. static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
  78. /// Parse \p Input as line sample.
  79. ///
  80. /// \param Input input line.
  81. /// \param IsCallsite true if the line represents an inlined callsite.
  82. /// \param Depth the depth of the inline stack.
  83. /// \param NumSamples total samples of the line/inlined callsite.
  84. /// \param LineOffset line offset to the start of the function.
  85. /// \param Discriminator discriminator of the line.
  86. /// \param TargetCountMap map from indirect call target to count.
  87. ///
  88. /// returns true if parsing is successful.
  89. static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
  90. uint64_t &NumSamples, uint32_t &LineOffset,
  91. uint32_t &Discriminator, StringRef &CalleeName,
  92. DenseMap<StringRef, uint64_t> &TargetCountMap) {
  93. for (Depth = 0; Input[Depth] == ' '; Depth++)
  94. ;
  95. if (Depth == 0)
  96. return false;
  97. size_t n1 = Input.find(':');
  98. StringRef Loc = Input.substr(Depth, n1 - Depth);
  99. size_t n2 = Loc.find('.');
  100. if (n2 == StringRef::npos) {
  101. if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
  102. return false;
  103. Discriminator = 0;
  104. } else {
  105. if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
  106. return false;
  107. if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
  108. return false;
  109. }
  110. StringRef Rest = Input.substr(n1 + 2);
  111. if (Rest[0] >= '0' && Rest[0] <= '9') {
  112. IsCallsite = false;
  113. size_t n3 = Rest.find(' ');
  114. if (n3 == StringRef::npos) {
  115. if (Rest.getAsInteger(10, NumSamples))
  116. return false;
  117. } else {
  118. if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
  119. return false;
  120. }
  121. // Find call targets and their sample counts.
  122. // Note: In some cases, there are symbols in the profile which are not
  123. // mangled. To accommodate such cases, use colon + integer pairs as the
  124. // anchor points.
  125. // An example:
  126. // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
  127. // ":1000" and ":437" are used as anchor points so the string above will
  128. // be interpreted as
  129. // target: _M_construct<char *>
  130. // count: 1000
  131. // target: string_view<std::allocator<char> >
  132. // count: 437
  133. while (n3 != StringRef::npos) {
  134. n3 += Rest.substr(n3).find_first_not_of(' ');
  135. Rest = Rest.substr(n3);
  136. n3 = Rest.find_first_of(':');
  137. if (n3 == StringRef::npos || n3 == 0)
  138. return false;
  139. StringRef Target;
  140. uint64_t count, n4;
  141. while (true) {
  142. // Get the segment after the current colon.
  143. StringRef AfterColon = Rest.substr(n3 + 1);
  144. // Get the target symbol before the current colon.
  145. Target = Rest.substr(0, n3);
  146. // Check if the word after the current colon is an integer.
  147. n4 = AfterColon.find_first_of(' ');
  148. n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
  149. StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
  150. if (!WordAfterColon.getAsInteger(10, count))
  151. break;
  152. // Try to find the next colon.
  153. uint64_t n5 = AfterColon.find_first_of(':');
  154. if (n5 == StringRef::npos)
  155. return false;
  156. n3 += n5 + 1;
  157. }
  158. // An anchor point is found. Save the {target, count} pair
  159. TargetCountMap[Target] = count;
  160. if (n4 == Rest.size())
  161. break;
  162. // Change n3 to the next blank space after colon + integer pair.
  163. n3 = n4;
  164. }
  165. } else {
  166. IsCallsite = true;
  167. size_t n3 = Rest.find_last_of(':');
  168. CalleeName = Rest.substr(0, n3);
  169. if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
  170. return false;
  171. }
  172. return true;
  173. }
  174. /// Load samples from a text file.
  175. ///
  176. /// See the documentation at the top of the file for an explanation of
  177. /// the expected format.
  178. ///
  179. /// \returns true if the file was loaded successfully, false otherwise.
  180. std::error_code SampleProfileReaderText::read() {
  181. line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
  182. sampleprof_error Result = sampleprof_error::success;
  183. InlineCallStack InlineStack;
  184. for (; !LineIt.is_at_eof(); ++LineIt) {
  185. if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
  186. continue;
  187. // Read the header of each function.
  188. //
  189. // Note that for function identifiers we are actually expecting
  190. // mangled names, but we may not always get them. This happens when
  191. // the compiler decides not to emit the function (e.g., it was inlined
  192. // and removed). In this case, the binary will not have the linkage
  193. // name for the function, so the profiler will emit the function's
  194. // unmangled name, which may contain characters like ':' and '>' in its
  195. // name (member functions, templates, etc).
  196. //
  197. // The only requirement we place on the identifier, then, is that it
  198. // should not begin with a number.
  199. if ((*LineIt)[0] != ' ') {
  200. uint64_t NumSamples, NumHeadSamples;
  201. StringRef FName;
  202. if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
  203. reportError(LineIt.line_number(),
  204. "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
  205. return sampleprof_error::malformed;
  206. }
  207. Profiles[FName] = FunctionSamples();
  208. FunctionSamples &FProfile = Profiles[FName];
  209. FProfile.setName(FName);
  210. MergeResult(Result, FProfile.addTotalSamples(NumSamples));
  211. MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
  212. InlineStack.clear();
  213. InlineStack.push_back(&FProfile);
  214. } else {
  215. uint64_t NumSamples;
  216. StringRef FName;
  217. DenseMap<StringRef, uint64_t> TargetCountMap;
  218. bool IsCallsite;
  219. uint32_t Depth, LineOffset, Discriminator;
  220. if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
  221. Discriminator, FName, TargetCountMap)) {
  222. reportError(LineIt.line_number(),
  223. "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
  224. *LineIt);
  225. return sampleprof_error::malformed;
  226. }
  227. if (IsCallsite) {
  228. while (InlineStack.size() > Depth) {
  229. InlineStack.pop_back();
  230. }
  231. FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
  232. LineLocation(LineOffset, Discriminator))[FName];
  233. FSamples.setName(FName);
  234. MergeResult(Result, FSamples.addTotalSamples(NumSamples));
  235. InlineStack.push_back(&FSamples);
  236. } else {
  237. while (InlineStack.size() > Depth) {
  238. InlineStack.pop_back();
  239. }
  240. FunctionSamples &FProfile = *InlineStack.back();
  241. for (const auto &name_count : TargetCountMap) {
  242. MergeResult(Result, FProfile.addCalledTargetSamples(
  243. LineOffset, Discriminator, name_count.first,
  244. name_count.second));
  245. }
  246. MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
  247. NumSamples));
  248. }
  249. }
  250. }
  251. if (Result == sampleprof_error::success)
  252. computeSummary();
  253. return Result;
  254. }
  255. bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
  256. bool result = false;
  257. // Check that the first non-comment line is a valid function header.
  258. line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
  259. if (!LineIt.is_at_eof()) {
  260. if ((*LineIt)[0] != ' ') {
  261. uint64_t NumSamples, NumHeadSamples;
  262. StringRef FName;
  263. result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
  264. }
  265. }
  266. return result;
  267. }
  268. template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
  269. unsigned NumBytesRead = 0;
  270. std::error_code EC;
  271. uint64_t Val = decodeULEB128(Data, &NumBytesRead);
  272. if (Val > std::numeric_limits<T>::max())
  273. EC = sampleprof_error::malformed;
  274. else if (Data + NumBytesRead > End)
  275. EC = sampleprof_error::truncated;
  276. else
  277. EC = sampleprof_error::success;
  278. if (EC) {
  279. reportError(0, EC.message());
  280. return EC;
  281. }
  282. Data += NumBytesRead;
  283. return static_cast<T>(Val);
  284. }
  285. ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
  286. std::error_code EC;
  287. StringRef Str(reinterpret_cast<const char *>(Data));
  288. if (Data + Str.size() + 1 > End) {
  289. EC = sampleprof_error::truncated;
  290. reportError(0, EC.message());
  291. return EC;
  292. }
  293. Data += Str.size() + 1;
  294. return Str;
  295. }
  296. template <typename T>
  297. inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
  298. std::error_code EC;
  299. auto Idx = readNumber<uint32_t>();
  300. if (std::error_code EC = Idx.getError())
  301. return EC;
  302. if (*Idx >= Table.size())
  303. return sampleprof_error::truncated_name_table;
  304. return *Idx;
  305. }
  306. ErrorOr<StringRef> SampleProfileReaderRawBinary::readStringFromTable() {
  307. auto Idx = readStringIndex(NameTable);
  308. if (std::error_code EC = Idx.getError())
  309. return EC;
  310. return NameTable[*Idx];
  311. }
  312. ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
  313. auto Idx = readStringIndex(NameTable);
  314. if (std::error_code EC = Idx.getError())
  315. return EC;
  316. return StringRef(NameTable[*Idx]);
  317. }
  318. std::error_code
  319. SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
  320. auto NumSamples = readNumber<uint64_t>();
  321. if (std::error_code EC = NumSamples.getError())
  322. return EC;
  323. FProfile.addTotalSamples(*NumSamples);
  324. // Read the samples in the body.
  325. auto NumRecords = readNumber<uint32_t>();
  326. if (std::error_code EC = NumRecords.getError())
  327. return EC;
  328. for (uint32_t I = 0; I < *NumRecords; ++I) {
  329. auto LineOffset = readNumber<uint64_t>();
  330. if (std::error_code EC = LineOffset.getError())
  331. return EC;
  332. if (!isOffsetLegal(*LineOffset)) {
  333. return std::error_code();
  334. }
  335. auto Discriminator = readNumber<uint64_t>();
  336. if (std::error_code EC = Discriminator.getError())
  337. return EC;
  338. auto NumSamples = readNumber<uint64_t>();
  339. if (std::error_code EC = NumSamples.getError())
  340. return EC;
  341. auto NumCalls = readNumber<uint32_t>();
  342. if (std::error_code EC = NumCalls.getError())
  343. return EC;
  344. for (uint32_t J = 0; J < *NumCalls; ++J) {
  345. auto CalledFunction(readStringFromTable());
  346. if (std::error_code EC = CalledFunction.getError())
  347. return EC;
  348. auto CalledFunctionSamples = readNumber<uint64_t>();
  349. if (std::error_code EC = CalledFunctionSamples.getError())
  350. return EC;
  351. FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
  352. *CalledFunction, *CalledFunctionSamples);
  353. }
  354. FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
  355. }
  356. // Read all the samples for inlined function calls.
  357. auto NumCallsites = readNumber<uint32_t>();
  358. if (std::error_code EC = NumCallsites.getError())
  359. return EC;
  360. for (uint32_t J = 0; J < *NumCallsites; ++J) {
  361. auto LineOffset = readNumber<uint64_t>();
  362. if (std::error_code EC = LineOffset.getError())
  363. return EC;
  364. auto Discriminator = readNumber<uint64_t>();
  365. if (std::error_code EC = Discriminator.getError())
  366. return EC;
  367. auto FName(readStringFromTable());
  368. if (std::error_code EC = FName.getError())
  369. return EC;
  370. FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
  371. LineLocation(*LineOffset, *Discriminator))[*FName];
  372. CalleeProfile.setName(*FName);
  373. if (std::error_code EC = readProfile(CalleeProfile))
  374. return EC;
  375. }
  376. return sampleprof_error::success;
  377. }
  378. std::error_code SampleProfileReaderBinary::read() {
  379. while (!at_eof()) {
  380. auto NumHeadSamples = readNumber<uint64_t>();
  381. if (std::error_code EC = NumHeadSamples.getError())
  382. return EC;
  383. auto FName(readStringFromTable());
  384. if (std::error_code EC = FName.getError())
  385. return EC;
  386. Profiles[*FName] = FunctionSamples();
  387. FunctionSamples &FProfile = Profiles[*FName];
  388. FProfile.setName(*FName);
  389. FProfile.addHeadSamples(*NumHeadSamples);
  390. if (std::error_code EC = readProfile(FProfile))
  391. return EC;
  392. }
  393. return sampleprof_error::success;
  394. }
  395. std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
  396. if (Magic == SPMagic())
  397. return sampleprof_error::success;
  398. return sampleprof_error::bad_magic;
  399. }
  400. std::error_code
  401. SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
  402. if (Magic == SPMagic(SPF_Compact_Binary))
  403. return sampleprof_error::success;
  404. return sampleprof_error::bad_magic;
  405. }
  406. std::error_code SampleProfileReaderRawBinary::readNameTable() {
  407. auto Size = readNumber<uint32_t>();
  408. if (std::error_code EC = Size.getError())
  409. return EC;
  410. NameTable.reserve(*Size);
  411. for (uint32_t I = 0; I < *Size; ++I) {
  412. auto Name(readString());
  413. if (std::error_code EC = Name.getError())
  414. return EC;
  415. NameTable.push_back(*Name);
  416. }
  417. return sampleprof_error::success;
  418. }
  419. std::error_code SampleProfileReaderCompactBinary::readNameTable() {
  420. auto Size = readNumber<uint64_t>();
  421. if (std::error_code EC = Size.getError())
  422. return EC;
  423. NameTable.reserve(*Size);
  424. for (uint32_t I = 0; I < *Size; ++I) {
  425. auto FID = readNumber<uint64_t>();
  426. if (std::error_code EC = FID.getError())
  427. return EC;
  428. NameTable.push_back(std::to_string(*FID));
  429. }
  430. return sampleprof_error::success;
  431. }
  432. std::error_code SampleProfileReaderBinary::readHeader() {
  433. Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
  434. End = Data + Buffer->getBufferSize();
  435. // Read and check the magic identifier.
  436. auto Magic = readNumber<uint64_t>();
  437. if (std::error_code EC = Magic.getError())
  438. return EC;
  439. else if (std::error_code EC = verifySPMagic(*Magic))
  440. return sampleprof_error::bad_magic;
  441. // Read the version number.
  442. auto Version = readNumber<uint64_t>();
  443. if (std::error_code EC = Version.getError())
  444. return EC;
  445. else if (*Version != SPVersion())
  446. return sampleprof_error::unsupported_version;
  447. if (std::error_code EC = readSummary())
  448. return EC;
  449. if (std::error_code EC = readNameTable())
  450. return EC;
  451. return sampleprof_error::success;
  452. }
  453. std::error_code SampleProfileReaderBinary::readSummaryEntry(
  454. std::vector<ProfileSummaryEntry> &Entries) {
  455. auto Cutoff = readNumber<uint64_t>();
  456. if (std::error_code EC = Cutoff.getError())
  457. return EC;
  458. auto MinBlockCount = readNumber<uint64_t>();
  459. if (std::error_code EC = MinBlockCount.getError())
  460. return EC;
  461. auto NumBlocks = readNumber<uint64_t>();
  462. if (std::error_code EC = NumBlocks.getError())
  463. return EC;
  464. Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
  465. return sampleprof_error::success;
  466. }
  467. std::error_code SampleProfileReaderBinary::readSummary() {
  468. auto TotalCount = readNumber<uint64_t>();
  469. if (std::error_code EC = TotalCount.getError())
  470. return EC;
  471. auto MaxBlockCount = readNumber<uint64_t>();
  472. if (std::error_code EC = MaxBlockCount.getError())
  473. return EC;
  474. auto MaxFunctionCount = readNumber<uint64_t>();
  475. if (std::error_code EC = MaxFunctionCount.getError())
  476. return EC;
  477. auto NumBlocks = readNumber<uint64_t>();
  478. if (std::error_code EC = NumBlocks.getError())
  479. return EC;
  480. auto NumFunctions = readNumber<uint64_t>();
  481. if (std::error_code EC = NumFunctions.getError())
  482. return EC;
  483. auto NumSummaryEntries = readNumber<uint64_t>();
  484. if (std::error_code EC = NumSummaryEntries.getError())
  485. return EC;
  486. std::vector<ProfileSummaryEntry> Entries;
  487. for (unsigned i = 0; i < *NumSummaryEntries; i++) {
  488. std::error_code EC = readSummaryEntry(Entries);
  489. if (EC != sampleprof_error::success)
  490. return EC;
  491. }
  492. Summary = llvm::make_unique<ProfileSummary>(
  493. ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
  494. *MaxFunctionCount, *NumBlocks, *NumFunctions);
  495. return sampleprof_error::success;
  496. }
  497. bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
  498. const uint8_t *Data =
  499. reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
  500. uint64_t Magic = decodeULEB128(Data);
  501. return Magic == SPMagic();
  502. }
  503. bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
  504. const uint8_t *Data =
  505. reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
  506. uint64_t Magic = decodeULEB128(Data);
  507. return Magic == SPMagic(SPF_Compact_Binary);
  508. }
  509. std::error_code SampleProfileReaderGCC::skipNextWord() {
  510. uint32_t dummy;
  511. if (!GcovBuffer.readInt(dummy))
  512. return sampleprof_error::truncated;
  513. return sampleprof_error::success;
  514. }
  515. template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
  516. if (sizeof(T) <= sizeof(uint32_t)) {
  517. uint32_t Val;
  518. if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
  519. return static_cast<T>(Val);
  520. } else if (sizeof(T) <= sizeof(uint64_t)) {
  521. uint64_t Val;
  522. if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
  523. return static_cast<T>(Val);
  524. }
  525. std::error_code EC = sampleprof_error::malformed;
  526. reportError(0, EC.message());
  527. return EC;
  528. }
  529. ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
  530. StringRef Str;
  531. if (!GcovBuffer.readString(Str))
  532. return sampleprof_error::truncated;
  533. return Str;
  534. }
  535. std::error_code SampleProfileReaderGCC::readHeader() {
  536. // Read the magic identifier.
  537. if (!GcovBuffer.readGCDAFormat())
  538. return sampleprof_error::unrecognized_format;
  539. // Read the version number. Note - the GCC reader does not validate this
  540. // version, but the profile creator generates v704.
  541. GCOV::GCOVVersion version;
  542. if (!GcovBuffer.readGCOVVersion(version))
  543. return sampleprof_error::unrecognized_format;
  544. if (version != GCOV::V704)
  545. return sampleprof_error::unsupported_version;
  546. // Skip the empty integer.
  547. if (std::error_code EC = skipNextWord())
  548. return EC;
  549. return sampleprof_error::success;
  550. }
  551. std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
  552. uint32_t Tag;
  553. if (!GcovBuffer.readInt(Tag))
  554. return sampleprof_error::truncated;
  555. if (Tag != Expected)
  556. return sampleprof_error::malformed;
  557. if (std::error_code EC = skipNextWord())
  558. return EC;
  559. return sampleprof_error::success;
  560. }
  561. std::error_code SampleProfileReaderGCC::readNameTable() {
  562. if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
  563. return EC;
  564. uint32_t Size;
  565. if (!GcovBuffer.readInt(Size))
  566. return sampleprof_error::truncated;
  567. for (uint32_t I = 0; I < Size; ++I) {
  568. StringRef Str;
  569. if (!GcovBuffer.readString(Str))
  570. return sampleprof_error::truncated;
  571. Names.push_back(Str);
  572. }
  573. return sampleprof_error::success;
  574. }
  575. std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
  576. if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
  577. return EC;
  578. uint32_t NumFunctions;
  579. if (!GcovBuffer.readInt(NumFunctions))
  580. return sampleprof_error::truncated;
  581. InlineCallStack Stack;
  582. for (uint32_t I = 0; I < NumFunctions; ++I)
  583. if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
  584. return EC;
  585. computeSummary();
  586. return sampleprof_error::success;
  587. }
  588. std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
  589. const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
  590. uint64_t HeadCount = 0;
  591. if (InlineStack.size() == 0)
  592. if (!GcovBuffer.readInt64(HeadCount))
  593. return sampleprof_error::truncated;
  594. uint32_t NameIdx;
  595. if (!GcovBuffer.readInt(NameIdx))
  596. return sampleprof_error::truncated;
  597. StringRef Name(Names[NameIdx]);
  598. uint32_t NumPosCounts;
  599. if (!GcovBuffer.readInt(NumPosCounts))
  600. return sampleprof_error::truncated;
  601. uint32_t NumCallsites;
  602. if (!GcovBuffer.readInt(NumCallsites))
  603. return sampleprof_error::truncated;
  604. FunctionSamples *FProfile = nullptr;
  605. if (InlineStack.size() == 0) {
  606. // If this is a top function that we have already processed, do not
  607. // update its profile again. This happens in the presence of
  608. // function aliases. Since these aliases share the same function
  609. // body, there will be identical replicated profiles for the
  610. // original function. In this case, we simply not bother updating
  611. // the profile of the original function.
  612. FProfile = &Profiles[Name];
  613. FProfile->addHeadSamples(HeadCount);
  614. if (FProfile->getTotalSamples() > 0)
  615. Update = false;
  616. } else {
  617. // Otherwise, we are reading an inlined instance. The top of the
  618. // inline stack contains the profile of the caller. Insert this
  619. // callee in the caller's CallsiteMap.
  620. FunctionSamples *CallerProfile = InlineStack.front();
  621. uint32_t LineOffset = Offset >> 16;
  622. uint32_t Discriminator = Offset & 0xffff;
  623. FProfile = &CallerProfile->functionSamplesAt(
  624. LineLocation(LineOffset, Discriminator))[Name];
  625. }
  626. FProfile->setName(Name);
  627. for (uint32_t I = 0; I < NumPosCounts; ++I) {
  628. uint32_t Offset;
  629. if (!GcovBuffer.readInt(Offset))
  630. return sampleprof_error::truncated;
  631. uint32_t NumTargets;
  632. if (!GcovBuffer.readInt(NumTargets))
  633. return sampleprof_error::truncated;
  634. uint64_t Count;
  635. if (!GcovBuffer.readInt64(Count))
  636. return sampleprof_error::truncated;
  637. // The line location is encoded in the offset as:
  638. // high 16 bits: line offset to the start of the function.
  639. // low 16 bits: discriminator.
  640. uint32_t LineOffset = Offset >> 16;
  641. uint32_t Discriminator = Offset & 0xffff;
  642. InlineCallStack NewStack;
  643. NewStack.push_back(FProfile);
  644. NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
  645. if (Update) {
  646. // Walk up the inline stack, adding the samples on this line to
  647. // the total sample count of the callers in the chain.
  648. for (auto CallerProfile : NewStack)
  649. CallerProfile->addTotalSamples(Count);
  650. // Update the body samples for the current profile.
  651. FProfile->addBodySamples(LineOffset, Discriminator, Count);
  652. }
  653. // Process the list of functions called at an indirect call site.
  654. // These are all the targets that a function pointer (or virtual
  655. // function) resolved at runtime.
  656. for (uint32_t J = 0; J < NumTargets; J++) {
  657. uint32_t HistVal;
  658. if (!GcovBuffer.readInt(HistVal))
  659. return sampleprof_error::truncated;
  660. if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
  661. return sampleprof_error::malformed;
  662. uint64_t TargetIdx;
  663. if (!GcovBuffer.readInt64(TargetIdx))
  664. return sampleprof_error::truncated;
  665. StringRef TargetName(Names[TargetIdx]);
  666. uint64_t TargetCount;
  667. if (!GcovBuffer.readInt64(TargetCount))
  668. return sampleprof_error::truncated;
  669. if (Update)
  670. FProfile->addCalledTargetSamples(LineOffset, Discriminator,
  671. TargetName, TargetCount);
  672. }
  673. }
  674. // Process all the inlined callers into the current function. These
  675. // are all the callsites that were inlined into this function.
  676. for (uint32_t I = 0; I < NumCallsites; I++) {
  677. // The offset is encoded as:
  678. // high 16 bits: line offset to the start of the function.
  679. // low 16 bits: discriminator.
  680. uint32_t Offset;
  681. if (!GcovBuffer.readInt(Offset))
  682. return sampleprof_error::truncated;
  683. InlineCallStack NewStack;
  684. NewStack.push_back(FProfile);
  685. NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
  686. if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
  687. return EC;
  688. }
  689. return sampleprof_error::success;
  690. }
  691. /// Read a GCC AutoFDO profile.
  692. ///
  693. /// This format is generated by the Linux Perf conversion tool at
  694. /// https://github.com/google/autofdo.
  695. std::error_code SampleProfileReaderGCC::read() {
  696. // Read the string table.
  697. if (std::error_code EC = readNameTable())
  698. return EC;
  699. // Read the source profile.
  700. if (std::error_code EC = readFunctionProfiles())
  701. return EC;
  702. return sampleprof_error::success;
  703. }
  704. bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
  705. StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
  706. return Magic == "adcg*704";
  707. }
  708. /// Prepare a memory buffer for the contents of \p Filename.
  709. ///
  710. /// \returns an error code indicating the status of the buffer.
  711. static ErrorOr<std::unique_ptr<MemoryBuffer>>
  712. setupMemoryBuffer(const Twine &Filename) {
  713. auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
  714. if (std::error_code EC = BufferOrErr.getError())
  715. return EC;
  716. auto Buffer = std::move(BufferOrErr.get());
  717. // Sanity check the file.
  718. if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
  719. return sampleprof_error::too_large;
  720. return std::move(Buffer);
  721. }
  722. /// Create a sample profile reader based on the format of the input file.
  723. ///
  724. /// \param Filename The file to open.
  725. ///
  726. /// \param C The LLVM context to use to emit diagnostics.
  727. ///
  728. /// \returns an error code indicating the status of the created reader.
  729. ErrorOr<std::unique_ptr<SampleProfileReader>>
  730. SampleProfileReader::create(const Twine &Filename, LLVMContext &C) {
  731. auto BufferOrError = setupMemoryBuffer(Filename);
  732. if (std::error_code EC = BufferOrError.getError())
  733. return EC;
  734. return create(BufferOrError.get(), C);
  735. }
  736. /// Create a sample profile reader based on the format of the input data.
  737. ///
  738. /// \param B The memory buffer to create the reader from (assumes ownership).
  739. ///
  740. /// \param C The LLVM context to use to emit diagnostics.
  741. ///
  742. /// \returns an error code indicating the status of the created reader.
  743. ErrorOr<std::unique_ptr<SampleProfileReader>>
  744. SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
  745. std::unique_ptr<SampleProfileReader> Reader;
  746. if (SampleProfileReaderRawBinary::hasFormat(*B))
  747. Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
  748. else if (SampleProfileReaderCompactBinary::hasFormat(*B))
  749. Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
  750. else if (SampleProfileReaderGCC::hasFormat(*B))
  751. Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
  752. else if (SampleProfileReaderText::hasFormat(*B))
  753. Reader.reset(new SampleProfileReaderText(std::move(B), C));
  754. else
  755. return sampleprof_error::unrecognized_format;
  756. if (std::error_code EC = Reader->readHeader())
  757. return EC;
  758. return std::move(Reader);
  759. }
  760. // For text and GCC file formats, we compute the summary after reading the
  761. // profile. Binary format has the profile summary in its header.
  762. void SampleProfileReader::computeSummary() {
  763. SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
  764. for (const auto &I : Profiles) {
  765. const FunctionSamples &Profile = I.second;
  766. Builder.addRecord(Profile);
  767. }
  768. Summary = Builder.getSummary();
  769. }