SampleProfWriter.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SampleProfWriter.h - Write LLVM sample profile data ------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file contains definitions needed for writing sample profiles.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  18. #define LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/IR/ProfileSummary.h"
  22. #include "llvm/ProfileData/SampleProf.h"
  23. #include "llvm/Support/ErrorOr.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <cstdint>
  26. #include <memory>
  27. #include <set>
  28. #include <system_error>
  29. namespace llvm {
  30. namespace sampleprof {
  31. enum SectionLayout {
  32. DefaultLayout,
  33. // The layout splits profile with context information from profile without
  34. // context information. When Thinlto is enabled, ThinLTO postlink phase only
  35. // has to load profile with context information and can skip the other part.
  36. CtxSplitLayout,
  37. NumOfLayout,
  38. };
  39. /// Sample-based profile writer. Base class.
  40. class SampleProfileWriter {
  41. public:
  42. virtual ~SampleProfileWriter() = default;
  43. /// Write sample profiles in \p S.
  44. ///
  45. /// \returns status code of the file update operation.
  46. virtual std::error_code writeSample(const FunctionSamples &S) = 0;
  47. /// Write all the sample profiles in the given map of samples.
  48. ///
  49. /// \returns status code of the file update operation.
  50. virtual std::error_code write(const SampleProfileMap &ProfileMap);
  51. raw_ostream &getOutputStream() { return *OutputStream; }
  52. /// Profile writer factory.
  53. ///
  54. /// Create a new file writer based on the value of \p Format.
  55. static ErrorOr<std::unique_ptr<SampleProfileWriter>>
  56. create(StringRef Filename, SampleProfileFormat Format);
  57. /// Create a new stream writer based on the value of \p Format.
  58. /// For testing.
  59. static ErrorOr<std::unique_ptr<SampleProfileWriter>>
  60. create(std::unique_ptr<raw_ostream> &OS, SampleProfileFormat Format);
  61. virtual void setProfileSymbolList(ProfileSymbolList *PSL) {}
  62. virtual void setToCompressAllSections() {}
  63. virtual void setUseMD5() {}
  64. virtual void setPartialProfile() {}
  65. virtual void resetSecLayout(SectionLayout SL) {}
  66. protected:
  67. SampleProfileWriter(std::unique_ptr<raw_ostream> &OS)
  68. : OutputStream(std::move(OS)) {}
  69. /// Write a file header for the profile file.
  70. virtual std::error_code writeHeader(const SampleProfileMap &ProfileMap) = 0;
  71. // Write function profiles to the profile file.
  72. virtual std::error_code writeFuncProfiles(const SampleProfileMap &ProfileMap);
  73. /// Output stream where to emit the profile to.
  74. std::unique_ptr<raw_ostream> OutputStream;
  75. /// Profile summary.
  76. std::unique_ptr<ProfileSummary> Summary;
  77. /// Compute summary for this profile.
  78. void computeSummary(const SampleProfileMap &ProfileMap);
  79. /// Profile format.
  80. SampleProfileFormat Format = SPF_None;
  81. };
  82. /// Sample-based profile writer (text format).
  83. class SampleProfileWriterText : public SampleProfileWriter {
  84. public:
  85. std::error_code writeSample(const FunctionSamples &S) override;
  86. protected:
  87. SampleProfileWriterText(std::unique_ptr<raw_ostream> &OS)
  88. : SampleProfileWriter(OS), Indent(0) {}
  89. std::error_code writeHeader(const SampleProfileMap &ProfileMap) override {
  90. return sampleprof_error::success;
  91. }
  92. private:
  93. /// Indent level to use when writing.
  94. ///
  95. /// This is used when printing inlined callees.
  96. unsigned Indent;
  97. friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
  98. SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
  99. SampleProfileFormat Format);
  100. };
  101. /// Sample-based profile writer (binary format).
  102. class SampleProfileWriterBinary : public SampleProfileWriter {
  103. public:
  104. SampleProfileWriterBinary(std::unique_ptr<raw_ostream> &OS)
  105. : SampleProfileWriter(OS) {}
  106. std::error_code writeSample(const FunctionSamples &S) override;
  107. protected:
  108. virtual MapVector<StringRef, uint32_t> &getNameTable() { return NameTable; }
  109. virtual std::error_code writeMagicIdent(SampleProfileFormat Format);
  110. virtual std::error_code writeNameTable();
  111. std::error_code writeHeader(const SampleProfileMap &ProfileMap) override;
  112. std::error_code writeSummary();
  113. virtual std::error_code writeContextIdx(const SampleContext &Context);
  114. std::error_code writeNameIdx(StringRef FName);
  115. std::error_code writeBody(const FunctionSamples &S);
  116. inline void stablizeNameTable(MapVector<StringRef, uint32_t> &NameTable,
  117. std::set<StringRef> &V);
  118. MapVector<StringRef, uint32_t> NameTable;
  119. void addName(StringRef FName);
  120. virtual void addContext(const SampleContext &Context);
  121. void addNames(const FunctionSamples &S);
  122. private:
  123. friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
  124. SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
  125. SampleProfileFormat Format);
  126. };
  127. class SampleProfileWriterRawBinary : public SampleProfileWriterBinary {
  128. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  129. };
  130. const std::array<SmallVector<SecHdrTableEntry, 8>, NumOfLayout>
  131. ExtBinaryHdrLayoutTable = {
  132. // Note that SecFuncOffsetTable section is written after SecLBRProfile
  133. // in the profile, but is put before SecLBRProfile in SectionHdrLayout.
  134. // This is because sample reader follows the order in SectionHdrLayout
  135. // to read each section. To read function profiles on demand, sample
  136. // reader need to get the offset of each function profile first.
  137. //
  138. // DefaultLayout
  139. SmallVector<SecHdrTableEntry, 8>({{SecProfSummary, 0, 0, 0, 0},
  140. {SecNameTable, 0, 0, 0, 0},
  141. {SecCSNameTable, 0, 0, 0, 0},
  142. {SecFuncOffsetTable, 0, 0, 0, 0},
  143. {SecLBRProfile, 0, 0, 0, 0},
  144. {SecProfileSymbolList, 0, 0, 0, 0},
  145. {SecFuncMetadata, 0, 0, 0, 0}}),
  146. // CtxSplitLayout
  147. SmallVector<SecHdrTableEntry, 8>({{SecProfSummary, 0, 0, 0, 0},
  148. {SecNameTable, 0, 0, 0, 0},
  149. // profile with context
  150. // for next two sections
  151. {SecFuncOffsetTable, 0, 0, 0, 0},
  152. {SecLBRProfile, 0, 0, 0, 0},
  153. // profile without context
  154. // for next two sections
  155. {SecFuncOffsetTable, 0, 0, 0, 0},
  156. {SecLBRProfile, 0, 0, 0, 0},
  157. {SecProfileSymbolList, 0, 0, 0, 0},
  158. {SecFuncMetadata, 0, 0, 0, 0}}),
  159. };
  160. class SampleProfileWriterExtBinaryBase : public SampleProfileWriterBinary {
  161. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  162. public:
  163. std::error_code write(const SampleProfileMap &ProfileMap) override;
  164. void setToCompressAllSections() override;
  165. void setToCompressSection(SecType Type);
  166. std::error_code writeSample(const FunctionSamples &S) override;
  167. // Set to use MD5 to represent string in NameTable.
  168. void setUseMD5() override {
  169. UseMD5 = true;
  170. addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagMD5Name);
  171. // MD5 will be stored as plain uint64_t instead of variable-length
  172. // quantity format in NameTable section.
  173. addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagFixedLengthMD5);
  174. }
  175. // Set the profile to be partial. It means the profile is for
  176. // common/shared code. The common profile is usually merged from
  177. // profiles collected from running other targets.
  178. void setPartialProfile() override {
  179. addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagPartial);
  180. }
  181. void setProfileSymbolList(ProfileSymbolList *PSL) override {
  182. ProfSymList = PSL;
  183. };
  184. void resetSecLayout(SectionLayout SL) override {
  185. verifySecLayout(SL);
  186. #ifndef NDEBUG
  187. // Make sure resetSecLayout is called before any flag setting.
  188. for (auto &Entry : SectionHdrLayout) {
  189. assert(Entry.Flags == 0 &&
  190. "resetSecLayout has to be called before any flag setting");
  191. }
  192. #endif
  193. SecLayout = SL;
  194. SectionHdrLayout = ExtBinaryHdrLayoutTable[SL];
  195. }
  196. protected:
  197. uint64_t markSectionStart(SecType Type, uint32_t LayoutIdx);
  198. std::error_code addNewSection(SecType Sec, uint32_t LayoutIdx,
  199. uint64_t SectionStart);
  200. template <class SecFlagType>
  201. void addSectionFlag(SecType Type, SecFlagType Flag) {
  202. for (auto &Entry : SectionHdrLayout) {
  203. if (Entry.Type == Type)
  204. addSecFlag(Entry, Flag);
  205. }
  206. }
  207. template <class SecFlagType>
  208. void addSectionFlag(uint32_t SectionIdx, SecFlagType Flag) {
  209. addSecFlag(SectionHdrLayout[SectionIdx], Flag);
  210. }
  211. void addContext(const SampleContext &Context) override;
  212. // placeholder for subclasses to dispatch their own section writers.
  213. virtual std::error_code writeCustomSection(SecType Type) = 0;
  214. // Verify the SecLayout is supported by the format.
  215. virtual void verifySecLayout(SectionLayout SL) = 0;
  216. // specify the order to write sections.
  217. virtual std::error_code writeSections(const SampleProfileMap &ProfileMap) = 0;
  218. // Dispatch section writer for each section. \p LayoutIdx is the sequence
  219. // number indicating where the section is located in SectionHdrLayout.
  220. virtual std::error_code writeOneSection(SecType Type, uint32_t LayoutIdx,
  221. const SampleProfileMap &ProfileMap);
  222. // Helper function to write name table.
  223. std::error_code writeNameTable() override;
  224. std::error_code writeContextIdx(const SampleContext &Context) override;
  225. std::error_code writeCSNameIdx(const SampleContext &Context);
  226. std::error_code writeCSNameTableSection();
  227. std::error_code writeFuncMetadata(const SampleProfileMap &Profiles);
  228. std::error_code writeFuncMetadata(const FunctionSamples &Profile);
  229. // Functions to write various kinds of sections.
  230. std::error_code writeNameTableSection(const SampleProfileMap &ProfileMap);
  231. std::error_code writeFuncOffsetTable();
  232. std::error_code writeProfileSymbolListSection();
  233. SectionLayout SecLayout = DefaultLayout;
  234. // Specifiy the order of sections in section header table. Note
  235. // the order of sections in SecHdrTable may be different that the
  236. // order in SectionHdrLayout. sample Reader will follow the order
  237. // in SectionHdrLayout to read each section.
  238. SmallVector<SecHdrTableEntry, 8> SectionHdrLayout =
  239. ExtBinaryHdrLayoutTable[DefaultLayout];
  240. // Save the start of SecLBRProfile so we can compute the offset to the
  241. // start of SecLBRProfile for each Function's Profile and will keep it
  242. // in FuncOffsetTable.
  243. uint64_t SecLBRProfileStart = 0;
  244. private:
  245. void allocSecHdrTable();
  246. std::error_code writeSecHdrTable();
  247. std::error_code writeHeader(const SampleProfileMap &ProfileMap) override;
  248. std::error_code compressAndOutput();
  249. // We will swap the raw_ostream held by LocalBufStream and that
  250. // held by OutputStream if we try to add a section which needs
  251. // compression. After the swap, all the data written to output
  252. // will be temporarily buffered into the underlying raw_string_ostream
  253. // originally held by LocalBufStream. After the data writing for the
  254. // section is completed, compress the data in the local buffer,
  255. // swap the raw_ostream back and write the compressed data to the
  256. // real output.
  257. std::unique_ptr<raw_ostream> LocalBufStream;
  258. // The location where the output stream starts.
  259. uint64_t FileStart;
  260. // The location in the output stream where the SecHdrTable should be
  261. // written to.
  262. uint64_t SecHdrTableOffset;
  263. // The table contains SecHdrTableEntry entries in order of how they are
  264. // populated in the writer. It may be different from the order in
  265. // SectionHdrLayout which specifies the sequence in which sections will
  266. // be read.
  267. std::vector<SecHdrTableEntry> SecHdrTable;
  268. // FuncOffsetTable maps function context to its profile offset in
  269. // SecLBRProfile section. It is used to load function profile on demand.
  270. MapVector<SampleContext, uint64_t> FuncOffsetTable;
  271. // Whether to use MD5 to represent string.
  272. bool UseMD5 = false;
  273. /// CSNameTable maps function context to its offset in SecCSNameTable section.
  274. /// The offset will be used everywhere where the context is referenced.
  275. MapVector<SampleContext, uint32_t> CSNameTable;
  276. ProfileSymbolList *ProfSymList = nullptr;
  277. };
  278. class SampleProfileWriterExtBinary : public SampleProfileWriterExtBinaryBase {
  279. public:
  280. SampleProfileWriterExtBinary(std::unique_ptr<raw_ostream> &OS)
  281. : SampleProfileWriterExtBinaryBase(OS) {}
  282. private:
  283. std::error_code writeDefaultLayout(const SampleProfileMap &ProfileMap);
  284. std::error_code writeCtxSplitLayout(const SampleProfileMap &ProfileMap);
  285. std::error_code writeSections(const SampleProfileMap &ProfileMap) override;
  286. std::error_code writeCustomSection(SecType Type) override {
  287. return sampleprof_error::success;
  288. };
  289. void verifySecLayout(SectionLayout SL) override {
  290. assert((SL == DefaultLayout || SL == CtxSplitLayout) &&
  291. "Unsupported layout");
  292. }
  293. };
  294. // CompactBinary is a compact format of binary profile which both reduces
  295. // the profile size and the load time needed when compiling. It has two
  296. // major difference with Binary format.
  297. // 1. It represents all the strings in name table using md5 hash.
  298. // 2. It saves a function offset table which maps function name index to
  299. // the offset of its function profile to the start of the binary profile,
  300. // so by using the function offset table, for those function profiles which
  301. // will not be needed when compiling a module, the profile reader does't
  302. // have to read them and it saves compile time if the profile size is huge.
  303. // The layout of the compact format is shown as follows:
  304. //
  305. // Part1: Profile header, the same as binary format, containing magic
  306. // number, version, summary, name table...
  307. // Part2: Function Offset Table Offset, which saves the position of
  308. // Part4.
  309. // Part3: Function profile collection
  310. // function1 profile start
  311. // ....
  312. // function2 profile start
  313. // ....
  314. // function3 profile start
  315. // ....
  316. // ......
  317. // Part4: Function Offset Table
  318. // function1 name index --> function1 profile start
  319. // function2 name index --> function2 profile start
  320. // function3 name index --> function3 profile start
  321. //
  322. // We need Part2 because profile reader can use it to find out and read
  323. // function offset table without reading Part3 first.
  324. class SampleProfileWriterCompactBinary : public SampleProfileWriterBinary {
  325. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  326. public:
  327. std::error_code writeSample(const FunctionSamples &S) override;
  328. std::error_code write(const SampleProfileMap &ProfileMap) override;
  329. protected:
  330. /// The table mapping from function name to the offset of its FunctionSample
  331. /// towards profile start.
  332. MapVector<StringRef, uint64_t> FuncOffsetTable;
  333. /// The offset of the slot to be filled with the offset of FuncOffsetTable
  334. /// towards profile start.
  335. uint64_t TableOffset;
  336. std::error_code writeNameTable() override;
  337. std::error_code writeHeader(const SampleProfileMap &ProfileMap) override;
  338. std::error_code writeFuncOffsetTable();
  339. };
  340. } // end namespace sampleprof
  341. } // end namespace llvm
  342. #endif // LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  343. #ifdef __GNUC__
  344. #pragma GCC diagnostic pop
  345. #endif