SampleProfWriter.h 16 KB

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