InstrProfWriter.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
  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. //
  9. // This file contains support for writing profiling data for clang's
  10. // instrumentation based PGO and coverage.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/InstrProfWriter.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/IR/ProfileSummary.h"
  17. #include "llvm/ProfileData/InstrProf.h"
  18. #include "llvm/ProfileData/ProfileCommon.h"
  19. #include "llvm/Support/Endian.h"
  20. #include "llvm/Support/EndianStream.h"
  21. #include "llvm/Support/Error.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. #include "llvm/Support/OnDiskHashTable.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <algorithm>
  26. #include <cstdint>
  27. #include <memory>
  28. #include <string>
  29. #include <tuple>
  30. #include <utility>
  31. #include <vector>
  32. using namespace llvm;
  33. // A struct to define how the data stream should be patched. For Indexed
  34. // profiling, only uint64_t data type is needed.
  35. struct PatchItem {
  36. uint64_t Pos; // Where to patch.
  37. uint64_t *D; // Pointer to an array of source data.
  38. int N; // Number of elements in \c D array.
  39. };
  40. namespace llvm {
  41. // A wrapper class to abstract writer stream with support of bytes
  42. // back patching.
  43. class ProfOStream {
  44. public:
  45. ProfOStream(raw_fd_ostream &FD)
  46. : IsFDOStream(true), OS(FD), LE(FD, support::little) {}
  47. ProfOStream(raw_string_ostream &STR)
  48. : IsFDOStream(false), OS(STR), LE(STR, support::little) {}
  49. uint64_t tell() { return OS.tell(); }
  50. void write(uint64_t V) { LE.write<uint64_t>(V); }
  51. // \c patch can only be called when all data is written and flushed.
  52. // For raw_string_ostream, the patch is done on the target string
  53. // directly and it won't be reflected in the stream's internal buffer.
  54. void patch(PatchItem *P, int NItems) {
  55. using namespace support;
  56. if (IsFDOStream) {
  57. raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
  58. for (int K = 0; K < NItems; K++) {
  59. FDOStream.seek(P[K].Pos);
  60. for (int I = 0; I < P[K].N; I++)
  61. write(P[K].D[I]);
  62. }
  63. } else {
  64. raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
  65. std::string &Data = SOStream.str(); // with flush
  66. for (int K = 0; K < NItems; K++) {
  67. for (int I = 0; I < P[K].N; I++) {
  68. uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
  69. Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
  70. (const char *)&Bytes, sizeof(uint64_t));
  71. }
  72. }
  73. }
  74. }
  75. // If \c OS is an instance of \c raw_fd_ostream, this field will be
  76. // true. Otherwise, \c OS will be an raw_string_ostream.
  77. bool IsFDOStream;
  78. raw_ostream &OS;
  79. support::endian::Writer LE;
  80. };
  81. class InstrProfRecordWriterTrait {
  82. public:
  83. using key_type = StringRef;
  84. using key_type_ref = StringRef;
  85. using data_type = const InstrProfWriter::ProfilingData *const;
  86. using data_type_ref = const InstrProfWriter::ProfilingData *const;
  87. using hash_value_type = uint64_t;
  88. using offset_type = uint64_t;
  89. support::endianness ValueProfDataEndianness = support::little;
  90. InstrProfSummaryBuilder *SummaryBuilder;
  91. InstrProfSummaryBuilder *CSSummaryBuilder;
  92. InstrProfRecordWriterTrait() = default;
  93. static hash_value_type ComputeHash(key_type_ref K) {
  94. return IndexedInstrProf::ComputeHash(K);
  95. }
  96. static std::pair<offset_type, offset_type>
  97. EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
  98. using namespace support;
  99. endian::Writer LE(Out, little);
  100. offset_type N = K.size();
  101. LE.write<offset_type>(N);
  102. offset_type M = 0;
  103. for (const auto &ProfileData : *V) {
  104. const InstrProfRecord &ProfRecord = ProfileData.second;
  105. M += sizeof(uint64_t); // The function hash
  106. M += sizeof(uint64_t); // The size of the Counts vector
  107. M += ProfRecord.Counts.size() * sizeof(uint64_t);
  108. // Value data
  109. M += ValueProfData::getSize(ProfileData.second);
  110. }
  111. LE.write<offset_type>(M);
  112. return std::make_pair(N, M);
  113. }
  114. void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
  115. Out.write(K.data(), N);
  116. }
  117. void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
  118. using namespace support;
  119. endian::Writer LE(Out, little);
  120. for (const auto &ProfileData : *V) {
  121. const InstrProfRecord &ProfRecord = ProfileData.second;
  122. if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
  123. CSSummaryBuilder->addRecord(ProfRecord);
  124. else
  125. SummaryBuilder->addRecord(ProfRecord);
  126. LE.write<uint64_t>(ProfileData.first); // Function hash
  127. LE.write<uint64_t>(ProfRecord.Counts.size());
  128. for (uint64_t I : ProfRecord.Counts)
  129. LE.write<uint64_t>(I);
  130. // Write value data
  131. std::unique_ptr<ValueProfData> VDataPtr =
  132. ValueProfData::serializeFrom(ProfileData.second);
  133. uint32_t S = VDataPtr->getSize();
  134. VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
  135. Out.write((const char *)VDataPtr.get(), S);
  136. }
  137. }
  138. };
  139. } // end namespace llvm
  140. InstrProfWriter::InstrProfWriter(bool Sparse, bool InstrEntryBBEnabled)
  141. : Sparse(Sparse), InstrEntryBBEnabled(InstrEntryBBEnabled),
  142. InfoObj(new InstrProfRecordWriterTrait()) {}
  143. InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
  144. // Internal interface for testing purpose only.
  145. void InstrProfWriter::setValueProfDataEndianness(
  146. support::endianness Endianness) {
  147. InfoObj->ValueProfDataEndianness = Endianness;
  148. }
  149. void InstrProfWriter::setOutputSparse(bool Sparse) {
  150. this->Sparse = Sparse;
  151. }
  152. void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
  153. function_ref<void(Error)> Warn) {
  154. auto Name = I.Name;
  155. auto Hash = I.Hash;
  156. addRecord(Name, Hash, std::move(I), Weight, Warn);
  157. }
  158. void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
  159. OverlapStats &Overlap,
  160. OverlapStats &FuncLevelOverlap,
  161. const OverlapFuncFilters &FuncFilter) {
  162. auto Name = Other.Name;
  163. auto Hash = Other.Hash;
  164. Other.accumulateCounts(FuncLevelOverlap.Test);
  165. if (FunctionData.find(Name) == FunctionData.end()) {
  166. Overlap.addOneUnique(FuncLevelOverlap.Test);
  167. return;
  168. }
  169. if (FuncLevelOverlap.Test.CountSum < 1.0f) {
  170. Overlap.Overlap.NumEntries += 1;
  171. return;
  172. }
  173. auto &ProfileDataMap = FunctionData[Name];
  174. bool NewFunc;
  175. ProfilingData::iterator Where;
  176. std::tie(Where, NewFunc) =
  177. ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
  178. if (NewFunc) {
  179. Overlap.addOneMismatch(FuncLevelOverlap.Test);
  180. return;
  181. }
  182. InstrProfRecord &Dest = Where->second;
  183. uint64_t ValueCutoff = FuncFilter.ValueCutoff;
  184. if (!FuncFilter.NameFilter.empty() &&
  185. Name.find(FuncFilter.NameFilter) != Name.npos)
  186. ValueCutoff = 0;
  187. Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
  188. }
  189. void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
  190. InstrProfRecord &&I, uint64_t Weight,
  191. function_ref<void(Error)> Warn) {
  192. auto &ProfileDataMap = FunctionData[Name];
  193. bool NewFunc;
  194. ProfilingData::iterator Where;
  195. std::tie(Where, NewFunc) =
  196. ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
  197. InstrProfRecord &Dest = Where->second;
  198. auto MapWarn = [&](instrprof_error E) {
  199. Warn(make_error<InstrProfError>(E));
  200. };
  201. if (NewFunc) {
  202. // We've never seen a function with this name and hash, add it.
  203. Dest = std::move(I);
  204. if (Weight > 1)
  205. Dest.scale(Weight, 1, MapWarn);
  206. } else {
  207. // We're updating a function we've seen before.
  208. Dest.merge(I, Weight, MapWarn);
  209. }
  210. Dest.sortValueData();
  211. }
  212. void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
  213. function_ref<void(Error)> Warn) {
  214. for (auto &I : IPW.FunctionData)
  215. for (auto &Func : I.getValue())
  216. addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
  217. }
  218. bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
  219. if (!Sparse)
  220. return true;
  221. for (const auto &Func : PD) {
  222. const InstrProfRecord &IPR = Func.second;
  223. if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
  224. return true;
  225. }
  226. return false;
  227. }
  228. static void setSummary(IndexedInstrProf::Summary *TheSummary,
  229. ProfileSummary &PS) {
  230. using namespace IndexedInstrProf;
  231. std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
  232. TheSummary->NumSummaryFields = Summary::NumKinds;
  233. TheSummary->NumCutoffEntries = Res.size();
  234. TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
  235. TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
  236. TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
  237. TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
  238. TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
  239. TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
  240. for (unsigned I = 0; I < Res.size(); I++)
  241. TheSummary->setEntry(I, Res[I]);
  242. }
  243. void InstrProfWriter::writeImpl(ProfOStream &OS) {
  244. using namespace IndexedInstrProf;
  245. OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
  246. InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
  247. InfoObj->SummaryBuilder = &ISB;
  248. InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
  249. InfoObj->CSSummaryBuilder = &CSISB;
  250. // Populate the hash table generator.
  251. for (const auto &I : FunctionData)
  252. if (shouldEncodeData(I.getValue()))
  253. Generator.insert(I.getKey(), &I.getValue());
  254. // Write the header.
  255. IndexedInstrProf::Header Header;
  256. Header.Magic = IndexedInstrProf::Magic;
  257. Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
  258. if (ProfileKind == PF_IRLevel)
  259. Header.Version |= VARIANT_MASK_IR_PROF;
  260. if (ProfileKind == PF_IRLevelWithCS) {
  261. Header.Version |= VARIANT_MASK_IR_PROF;
  262. Header.Version |= VARIANT_MASK_CSIR_PROF;
  263. }
  264. if (InstrEntryBBEnabled)
  265. Header.Version |= VARIANT_MASK_INSTR_ENTRY;
  266. Header.Unused = 0;
  267. Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
  268. Header.HashOffset = 0;
  269. int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
  270. // Only write out all the fields except 'HashOffset'. We need
  271. // to remember the offset of that field to allow back patching
  272. // later.
  273. for (int I = 0; I < N - 1; I++)
  274. OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
  275. // Save the location of Header.HashOffset field in \c OS.
  276. uint64_t HashTableStartFieldOffset = OS.tell();
  277. // Reserve the space for HashOffset field.
  278. OS.write(0);
  279. // Reserve space to write profile summary data.
  280. uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
  281. uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
  282. // Remember the summary offset.
  283. uint64_t SummaryOffset = OS.tell();
  284. for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
  285. OS.write(0);
  286. uint64_t CSSummaryOffset = 0;
  287. uint64_t CSSummarySize = 0;
  288. if (ProfileKind == PF_IRLevelWithCS) {
  289. CSSummaryOffset = OS.tell();
  290. CSSummarySize = SummarySize / sizeof(uint64_t);
  291. for (unsigned I = 0; I < CSSummarySize; I++)
  292. OS.write(0);
  293. }
  294. // Write the hash table.
  295. uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
  296. // Allocate space for data to be serialized out.
  297. std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
  298. IndexedInstrProf::allocSummary(SummarySize);
  299. // Compute the Summary and copy the data to the data
  300. // structure to be serialized out (to disk or buffer).
  301. std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
  302. setSummary(TheSummary.get(), *PS);
  303. InfoObj->SummaryBuilder = nullptr;
  304. // For Context Sensitive summary.
  305. std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
  306. if (ProfileKind == PF_IRLevelWithCS) {
  307. TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
  308. std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
  309. setSummary(TheCSSummary.get(), *CSPS);
  310. }
  311. InfoObj->CSSummaryBuilder = nullptr;
  312. // Now do the final patch:
  313. PatchItem PatchItems[] = {
  314. // Patch the Header.HashOffset field.
  315. {HashTableStartFieldOffset, &HashTableStart, 1},
  316. // Patch the summary data.
  317. {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
  318. (int)(SummarySize / sizeof(uint64_t))},
  319. {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
  320. (int)CSSummarySize}};
  321. OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
  322. }
  323. void InstrProfWriter::write(raw_fd_ostream &OS) {
  324. // Write the hash table.
  325. ProfOStream POS(OS);
  326. writeImpl(POS);
  327. }
  328. std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
  329. std::string Data;
  330. raw_string_ostream OS(Data);
  331. ProfOStream POS(OS);
  332. // Write the hash table.
  333. writeImpl(POS);
  334. // Return this in an aligned memory buffer.
  335. return MemoryBuffer::getMemBufferCopy(Data);
  336. }
  337. static const char *ValueProfKindStr[] = {
  338. #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
  339. #include "llvm/ProfileData/InstrProfData.inc"
  340. };
  341. void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
  342. const InstrProfRecord &Func,
  343. InstrProfSymtab &Symtab,
  344. raw_fd_ostream &OS) {
  345. OS << Name << "\n";
  346. OS << "# Func Hash:\n" << Hash << "\n";
  347. OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
  348. OS << "# Counter Values:\n";
  349. for (uint64_t Count : Func.Counts)
  350. OS << Count << "\n";
  351. uint32_t NumValueKinds = Func.getNumValueKinds();
  352. if (!NumValueKinds) {
  353. OS << "\n";
  354. return;
  355. }
  356. OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
  357. for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
  358. uint32_t NS = Func.getNumValueSites(VK);
  359. if (!NS)
  360. continue;
  361. OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
  362. OS << "# NumValueSites:\n" << NS << "\n";
  363. for (uint32_t S = 0; S < NS; S++) {
  364. uint32_t ND = Func.getNumValueDataForSite(VK, S);
  365. OS << ND << "\n";
  366. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
  367. for (uint32_t I = 0; I < ND; I++) {
  368. if (VK == IPVK_IndirectCallTarget)
  369. OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
  370. << VD[I].Count << "\n";
  371. else
  372. OS << VD[I].Value << ":" << VD[I].Count << "\n";
  373. }
  374. }
  375. }
  376. OS << "\n";
  377. }
  378. Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
  379. if (ProfileKind == PF_IRLevel)
  380. OS << "# IR level Instrumentation Flag\n:ir\n";
  381. else if (ProfileKind == PF_IRLevelWithCS)
  382. OS << "# CSIR level Instrumentation Flag\n:csir\n";
  383. if (InstrEntryBBEnabled)
  384. OS << "# Always instrument the function entry block\n:entry_first\n";
  385. InstrProfSymtab Symtab;
  386. using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
  387. using RecordType = std::pair<StringRef, FuncPair>;
  388. SmallVector<RecordType, 4> OrderedFuncData;
  389. for (const auto &I : FunctionData) {
  390. if (shouldEncodeData(I.getValue())) {
  391. if (Error E = Symtab.addFuncName(I.getKey()))
  392. return E;
  393. for (const auto &Func : I.getValue())
  394. OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
  395. }
  396. }
  397. llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
  398. return std::tie(A.first, A.second.first) <
  399. std::tie(B.first, B.second.first);
  400. });
  401. for (const auto &record : OrderedFuncData) {
  402. const StringRef &Name = record.first;
  403. const FuncPair &Func = record.second;
  404. writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
  405. }
  406. return Error::success();
  407. }