SampleProfReader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 two file formats: text and binary. The textual representation
  12. // is useful for debugging and testing purposes. The binary representation
  13. // is more compact, resulting in smaller file sizes. However, they can
  14. // both be used interchangeably.
  15. //
  16. // NOTE: If you are making changes to the file format, please remember
  17. // to document them in the Clang documentation at
  18. // tools/clang/docs/UsersManual.rst.
  19. //
  20. // Text format
  21. // -----------
  22. //
  23. // Sample profiles are written as ASCII text. The file is divided into
  24. // sections, which correspond to each of the functions executed at runtime.
  25. // Each section has the following format
  26. //
  27. // function1:total_samples:total_head_samples
  28. // offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
  29. // offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
  30. // ...
  31. // offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
  32. //
  33. // The file may contain blank lines between sections and within a
  34. // section. However, the spacing within a single line is fixed. Additional
  35. // spaces will result in an error while reading the file.
  36. //
  37. // Function names must be mangled in order for the profile loader to
  38. // match them in the current translation unit. The two numbers in the
  39. // function header specify how many total samples were accumulated in the
  40. // function (first number), and the total number of samples accumulated
  41. // in the prologue of the function (second number). This head sample
  42. // count provides an indicator of how frequently the function is invoked.
  43. //
  44. // Each sampled line may contain several items. Some are optional (marked
  45. // below):
  46. //
  47. // a. Source line offset. This number represents the line number
  48. // in the function where the sample was collected. The line number is
  49. // always relative to the line where symbol of the function is
  50. // defined. So, if the function has its header at line 280, the offset
  51. // 13 is at line 293 in the file.
  52. //
  53. // Note that this offset should never be a negative number. This could
  54. // happen in cases like macros. The debug machinery will register the
  55. // line number at the point of macro expansion. So, if the macro was
  56. // expanded in a line before the start of the function, the profile
  57. // converter should emit a 0 as the offset (this means that the optimizers
  58. // will not be able to associate a meaningful weight to the instructions
  59. // in the macro).
  60. //
  61. // b. [OPTIONAL] Discriminator. This is used if the sampled program
  62. // was compiled with DWARF discriminator support
  63. // (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
  64. // DWARF discriminators are unsigned integer values that allow the
  65. // compiler to distinguish between multiple execution paths on the
  66. // same source line location.
  67. //
  68. // For example, consider the line of code ``if (cond) foo(); else bar();``.
  69. // If the predicate ``cond`` is true 80% of the time, then the edge
  70. // into function ``foo`` should be considered to be taken most of the
  71. // time. But both calls to ``foo`` and ``bar`` are at the same source
  72. // line, so a sample count at that line is not sufficient. The
  73. // compiler needs to know which part of that line is taken more
  74. // frequently.
  75. //
  76. // This is what discriminators provide. In this case, the calls to
  77. // ``foo`` and ``bar`` will be at the same line, but will have
  78. // different discriminator values. This allows the compiler to correctly
  79. // set edge weights into ``foo`` and ``bar``.
  80. //
  81. // c. Number of samples. This is an integer quantity representing the
  82. // number of samples collected by the profiler at this source
  83. // location.
  84. //
  85. // d. [OPTIONAL] Potential call targets and samples. If present, this
  86. // line contains a call instruction. This models both direct and
  87. // number of samples. For example,
  88. //
  89. // 130: 7 foo:3 bar:2 baz:7
  90. //
  91. // The above means that at relative line offset 130 there is a call
  92. // instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
  93. // with ``baz()`` being the relatively more frequently called target.
  94. //
  95. //===----------------------------------------------------------------------===//
  96. #include "llvm/ProfileData/SampleProfReader.h"
  97. #include "llvm/Support/Debug.h"
  98. #include "llvm/Support/ErrorOr.h"
  99. #include "llvm/Support/LEB128.h"
  100. #include "llvm/Support/LineIterator.h"
  101. #include "llvm/Support/MemoryBuffer.h"
  102. #include "llvm/Support/Regex.h"
  103. using namespace llvm::sampleprof;
  104. using namespace llvm;
  105. /// \brief Print the samples collected for a function on stream \p OS.
  106. ///
  107. /// \param OS Stream to emit the output to.
  108. void FunctionSamples::print(raw_ostream &OS) {
  109. OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
  110. << " sampled lines\n";
  111. for (const auto &SI : BodySamples) {
  112. LineLocation Loc = SI.first;
  113. const SampleRecord &Sample = SI.second;
  114. OS << "\tline offset: " << Loc.LineOffset
  115. << ", discriminator: " << Loc.Discriminator
  116. << ", number of samples: " << Sample.getSamples();
  117. if (Sample.hasCalls()) {
  118. OS << ", calls:";
  119. for (const auto &I : Sample.getCallTargets())
  120. OS << " " << I.first() << ":" << I.second;
  121. }
  122. OS << "\n";
  123. }
  124. OS << "\n";
  125. }
  126. /// \brief Dump the function profile for \p FName.
  127. ///
  128. /// \param FName Name of the function to print.
  129. /// \param OS Stream to emit the output to.
  130. void SampleProfileReader::dumpFunctionProfile(StringRef FName,
  131. raw_ostream &OS) {
  132. OS << "Function: " << FName << ": ";
  133. Profiles[FName].print(OS);
  134. }
  135. /// \brief Dump all the function profiles found on stream \p OS.
  136. void SampleProfileReader::dump(raw_ostream &OS) {
  137. for (const auto &I : Profiles)
  138. dumpFunctionProfile(I.getKey(), OS);
  139. }
  140. /// \brief Load samples from a text file.
  141. ///
  142. /// See the documentation at the top of the file for an explanation of
  143. /// the expected format.
  144. ///
  145. /// \returns true if the file was loaded successfully, false otherwise.
  146. std::error_code SampleProfileReaderText::read() {
  147. line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
  148. // Read the profile of each function. Since each function may be
  149. // mentioned more than once, and we are collecting flat profiles,
  150. // accumulate samples as we parse them.
  151. Regex HeadRE("^([^0-9].*):([0-9]+):([0-9]+)$");
  152. Regex LineSampleRE("^([0-9]+)\\.?([0-9]+)?: ([0-9]+)(.*)$");
  153. Regex CallSampleRE(" +([^0-9 ][^ ]*):([0-9]+)");
  154. while (!LineIt.is_at_eof()) {
  155. // Read the header of each function.
  156. //
  157. // Note that for function identifiers we are actually expecting
  158. // mangled names, but we may not always get them. This happens when
  159. // the compiler decides not to emit the function (e.g., it was inlined
  160. // and removed). In this case, the binary will not have the linkage
  161. // name for the function, so the profiler will emit the function's
  162. // unmangled name, which may contain characters like ':' and '>' in its
  163. // name (member functions, templates, etc).
  164. //
  165. // The only requirement we place on the identifier, then, is that it
  166. // should not begin with a number.
  167. SmallVector<StringRef, 4> Matches;
  168. if (!HeadRE.match(*LineIt, &Matches)) {
  169. reportParseError(LineIt.line_number(),
  170. "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
  171. return sampleprof_error::malformed;
  172. }
  173. assert(Matches.size() == 4);
  174. StringRef FName = Matches[1];
  175. unsigned NumSamples, NumHeadSamples;
  176. Matches[2].getAsInteger(10, NumSamples);
  177. Matches[3].getAsInteger(10, NumHeadSamples);
  178. Profiles[FName] = FunctionSamples();
  179. FunctionSamples &FProfile = Profiles[FName];
  180. FProfile.addTotalSamples(NumSamples);
  181. FProfile.addHeadSamples(NumHeadSamples);
  182. ++LineIt;
  183. // Now read the body. The body of the function ends when we reach
  184. // EOF or when we see the start of the next function.
  185. while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
  186. if (!LineSampleRE.match(*LineIt, &Matches)) {
  187. reportParseError(
  188. LineIt.line_number(),
  189. "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
  190. return sampleprof_error::malformed;
  191. }
  192. assert(Matches.size() == 5);
  193. unsigned LineOffset, NumSamples, Discriminator = 0;
  194. Matches[1].getAsInteger(10, LineOffset);
  195. if (Matches[2] != "")
  196. Matches[2].getAsInteger(10, Discriminator);
  197. Matches[3].getAsInteger(10, NumSamples);
  198. // If there are function calls in this line, generate a call sample
  199. // entry for each call.
  200. std::string CallsLine(Matches[4]);
  201. while (CallsLine != "") {
  202. SmallVector<StringRef, 3> CallSample;
  203. if (!CallSampleRE.match(CallsLine, &CallSample)) {
  204. reportParseError(LineIt.line_number(),
  205. "Expected 'mangled_name:NUM', found " + CallsLine);
  206. return sampleprof_error::malformed;
  207. }
  208. StringRef CalledFunction = CallSample[1];
  209. unsigned CalledFunctionSamples;
  210. CallSample[2].getAsInteger(10, CalledFunctionSamples);
  211. FProfile.addCalledTargetSamples(LineOffset, Discriminator,
  212. CalledFunction, CalledFunctionSamples);
  213. CallsLine = CallSampleRE.sub("", CallsLine);
  214. }
  215. FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
  216. ++LineIt;
  217. }
  218. }
  219. return sampleprof_error::success;
  220. }
  221. template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
  222. unsigned NumBytesRead = 0;
  223. std::error_code EC;
  224. uint64_t Val = decodeULEB128(Data, &NumBytesRead);
  225. if (Val > std::numeric_limits<T>::max())
  226. EC = sampleprof_error::malformed;
  227. else if (Data + NumBytesRead > End)
  228. EC = sampleprof_error::truncated;
  229. else
  230. EC = sampleprof_error::success;
  231. if (EC) {
  232. reportParseError(0, EC.message());
  233. return EC;
  234. }
  235. Data += NumBytesRead;
  236. return static_cast<T>(Val);
  237. }
  238. ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
  239. std::error_code EC;
  240. StringRef Str(reinterpret_cast<const char *>(Data));
  241. if (Data + Str.size() + 1 > End) {
  242. EC = sampleprof_error::truncated;
  243. reportParseError(0, EC.message());
  244. return EC;
  245. }
  246. Data += Str.size() + 1;
  247. return Str;
  248. }
  249. std::error_code SampleProfileReaderBinary::read() {
  250. while (!at_eof()) {
  251. auto FName(readString());
  252. if (std::error_code EC = FName.getError())
  253. return EC;
  254. Profiles[*FName] = FunctionSamples();
  255. FunctionSamples &FProfile = Profiles[*FName];
  256. auto Val = readNumber<unsigned>();
  257. if (std::error_code EC = Val.getError())
  258. return EC;
  259. FProfile.addTotalSamples(*Val);
  260. Val = readNumber<unsigned>();
  261. if (std::error_code EC = Val.getError())
  262. return EC;
  263. FProfile.addHeadSamples(*Val);
  264. // Read the samples in the body.
  265. auto NumRecords = readNumber<unsigned>();
  266. if (std::error_code EC = NumRecords.getError())
  267. return EC;
  268. for (unsigned I = 0; I < *NumRecords; ++I) {
  269. auto LineOffset = readNumber<uint64_t>();
  270. if (std::error_code EC = LineOffset.getError())
  271. return EC;
  272. auto Discriminator = readNumber<uint64_t>();
  273. if (std::error_code EC = Discriminator.getError())
  274. return EC;
  275. auto NumSamples = readNumber<uint64_t>();
  276. if (std::error_code EC = NumSamples.getError())
  277. return EC;
  278. auto NumCalls = readNumber<unsigned>();
  279. if (std::error_code EC = NumCalls.getError())
  280. return EC;
  281. for (unsigned J = 0; J < *NumCalls; ++J) {
  282. auto CalledFunction(readString());
  283. if (std::error_code EC = CalledFunction.getError())
  284. return EC;
  285. auto CalledFunctionSamples = readNumber<uint64_t>();
  286. if (std::error_code EC = CalledFunctionSamples.getError())
  287. return EC;
  288. FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
  289. *CalledFunction,
  290. *CalledFunctionSamples);
  291. }
  292. FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
  293. }
  294. }
  295. return sampleprof_error::success;
  296. }
  297. std::error_code SampleProfileReaderBinary::readHeader() {
  298. Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
  299. End = Data + Buffer->getBufferSize();
  300. // Read and check the magic identifier.
  301. auto Magic = readNumber<uint64_t>();
  302. if (std::error_code EC = Magic.getError())
  303. return EC;
  304. else if (*Magic != SPMagic())
  305. return sampleprof_error::bad_magic;
  306. // Read the version number.
  307. auto Version = readNumber<uint64_t>();
  308. if (std::error_code EC = Version.getError())
  309. return EC;
  310. else if (*Version != SPVersion())
  311. return sampleprof_error::unsupported_version;
  312. return sampleprof_error::success;
  313. }
  314. bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
  315. const uint8_t *Data =
  316. reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
  317. uint64_t Magic = decodeULEB128(Data);
  318. return Magic == SPMagic();
  319. }
  320. /// \brief Prepare a memory buffer for the contents of \p Filename.
  321. ///
  322. /// \returns an error code indicating the status of the buffer.
  323. static ErrorOr<std::unique_ptr<MemoryBuffer>>
  324. setupMemoryBuffer(std::string Filename) {
  325. auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
  326. if (std::error_code EC = BufferOrErr.getError())
  327. return EC;
  328. auto Buffer = std::move(BufferOrErr.get());
  329. // Sanity check the file.
  330. if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
  331. return sampleprof_error::too_large;
  332. return std::move(Buffer);
  333. }
  334. /// \brief Create a sample profile reader based on the format of the input file.
  335. ///
  336. /// \param Filename The file to open.
  337. ///
  338. /// \param Reader The reader to instantiate according to \p Filename's format.
  339. ///
  340. /// \param C The LLVM context to use to emit diagnostics.
  341. ///
  342. /// \returns an error code indicating the status of the created reader.
  343. ErrorOr<std::unique_ptr<SampleProfileReader>>
  344. SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
  345. auto BufferOrError = setupMemoryBuffer(Filename);
  346. if (std::error_code EC = BufferOrError.getError())
  347. return EC;
  348. auto Buffer = std::move(BufferOrError.get());
  349. std::unique_ptr<SampleProfileReader> Reader;
  350. if (SampleProfileReaderBinary::hasFormat(*Buffer))
  351. Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
  352. else
  353. Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
  354. if (std::error_code EC = Reader->readHeader())
  355. return EC;
  356. return std::move(Reader);
  357. }