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