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