1 //=-- InstrProfWriter.cpp - Instrumented profiling writer -------------------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ProfileData/InstrProfWriter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/EndianStream.h"
18 #include "llvm/Support/OnDiskHashTable.h"
19 #include <tuple>
20 
21 using namespace llvm;
22 
23 // A struct to define how the data stream should be patched. For Indexed
24 // profiling, only uint64_t data type is needed.
25 struct PatchItem {
26   uint64_t Pos; // Where to patch.
27   uint64_t *D;  // Pointer to an array of source data.
28   int N;        // Number of elements in \c D array.
29 };
30 
31 namespace llvm {
32 // A wrapper class to abstract writer stream with support of bytes
33 // back patching.
34 class ProfOStream {
35 
36 public:
37   ProfOStream(llvm::raw_fd_ostream &FD) : IsFDOStream(true), OS(FD), LE(FD) {}
38   ProfOStream(llvm::raw_string_ostream &STR)
39       : IsFDOStream(false), OS(STR), LE(STR) {}
40 
41   uint64_t tell() { return OS.tell(); }
42   void write(uint64_t V) { LE.write<uint64_t>(V); }
43   // \c patch can only be called when all data is written and flushed.
44   // For raw_string_ostream, the patch is done on the target string
45   // directly and it won't be reflected in the stream's internal buffer.
46   void patch(PatchItem *P, int NItems) {
47     using namespace support;
48     if (IsFDOStream) {
49       llvm::raw_fd_ostream &FDOStream = static_cast<llvm::raw_fd_ostream &>(OS);
50       for (int K = 0; K < NItems; K++) {
51         FDOStream.seek(P[K].Pos);
52         for (int I = 0; I < P[K].N; I++)
53           write(P[K].D[I]);
54       }
55     } else {
56       llvm::raw_string_ostream &SOStream =
57           static_cast<llvm::raw_string_ostream &>(OS);
58       std::string &Data = SOStream.str(); // with flush
59       for (int K = 0; K < NItems; K++) {
60         for (int I = 0; I < P[K].N; I++) {
61           uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
62           Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
63                        (const char *)&Bytes, sizeof(uint64_t));
64         }
65       }
66     }
67   }
68   // If \c OS is an instance of \c raw_fd_ostream, this field will be
69   // true. Otherwise, \c OS will be an raw_string_ostream.
70   bool IsFDOStream;
71   raw_ostream &OS;
72   support::endian::Writer<support::little> LE;
73 };
74 
75 class InstrProfRecordWriterTrait {
76 public:
77   typedef StringRef key_type;
78   typedef StringRef key_type_ref;
79 
80   typedef const InstrProfWriter::ProfilingData *const data_type;
81   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
82 
83   typedef uint64_t hash_value_type;
84   typedef uint64_t offset_type;
85 
86   support::endianness ValueProfDataEndianness;
87 
88   InstrProfRecordWriterTrait() : ValueProfDataEndianness(support::little) {}
89   static hash_value_type ComputeHash(key_type_ref K) {
90     return IndexedInstrProf::ComputeHash(K);
91   }
92 
93   static std::pair<offset_type, offset_type>
94   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
95     using namespace llvm::support;
96     endian::Writer<little> LE(Out);
97 
98     offset_type N = K.size();
99     LE.write<offset_type>(N);
100 
101     offset_type M = 0;
102     for (const auto &ProfileData : *V) {
103       const InstrProfRecord &ProfRecord = ProfileData.second;
104       M += sizeof(uint64_t); // The function hash
105       M += sizeof(uint64_t); // The size of the Counts vector
106       M += ProfRecord.Counts.size() * sizeof(uint64_t);
107 
108       // Value data
109       M += ValueProfData::getSize(ProfileData.second);
110     }
111     LE.write<offset_type>(M);
112 
113     return std::make_pair(N, M);
114   }
115 
116   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
117     Out.write(K.data(), N);
118   }
119 
120   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
121     using namespace llvm::support;
122     endian::Writer<little> LE(Out);
123     for (const auto &ProfileData : *V) {
124       const InstrProfRecord &ProfRecord = ProfileData.second;
125 
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 
131       // Write value data
132       std::unique_ptr<ValueProfData> VDataPtr =
133           ValueProfData::serializeFrom(ProfileData.second);
134       uint32_t S = VDataPtr->getSize();
135       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
136       Out.write((const char *)VDataPtr.get(), S);
137     }
138   }
139 };
140 }
141 
142 InstrProfWriter::InstrProfWriter()
143     : FunctionData(), MaxFunctionCount(0),
144       InfoObj(new InstrProfRecordWriterTrait()) {}
145 
146 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
147 
148 // Internal interface for testing purpose only.
149 void InstrProfWriter::setValueProfDataEndianness(
150     support::endianness Endianness) {
151   InfoObj->ValueProfDataEndianness = Endianness;
152 }
153 
154 std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I,
155                                            uint64_t Weight) {
156   auto &ProfileDataMap = FunctionData[I.Name];
157 
158   bool NewFunc;
159   ProfilingData::iterator Where;
160   std::tie(Where, NewFunc) =
161       ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
162   InstrProfRecord &Dest = Where->second;
163 
164   instrprof_error Result = instrprof_error::success;
165   if (NewFunc) {
166     // We've never seen a function with this name and hash, add it.
167     Dest = std::move(I);
168     // Fix up the name to avoid dangling reference.
169     Dest.Name = FunctionData.find(Dest.Name)->getKey();
170     if (Weight > 1)
171       Result = Dest.scale(Weight);
172   } else {
173     // We're updating a function we've seen before.
174     Result = Dest.merge(I, Weight);
175   }
176 
177   Dest.sortValueData();
178 
179   // We keep track of the max function count as we go for simplicity.
180   // Update this statistic no matter the result of the merge.
181   if (Dest.Counts[0] > MaxFunctionCount)
182     MaxFunctionCount = Dest.Counts[0];
183 
184   return Result;
185 }
186 
187 void InstrProfWriter::writeImpl(ProfOStream &OS) {
188   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
189   // Populate the hash table generator.
190   for (const auto &I : FunctionData)
191     Generator.insert(I.getKey(), &I.getValue());
192   // Write the header.
193   IndexedInstrProf::Header Header;
194   Header.Magic = IndexedInstrProf::Magic;
195   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
196   Header.MaxFunctionCount = MaxFunctionCount;
197   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
198   Header.HashOffset = 0;
199   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
200 
201   // Only write out all the fields execpt 'HashOffset'. We need
202   // to remember the offset of that field to allow back patching
203   // later.
204   for (int I = 0; I < N - 1; I++)
205     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
206 
207   // Save a space to write the hash table start location.
208   uint64_t HashTableStartLoc = OS.tell();
209   // Reserve the space for HashOffset field.
210   OS.write(0);
211   // Write the hash table.
212   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
213 
214   // Now do the final patch:
215   PatchItem PatchItems[1] = {{HashTableStartLoc, &HashTableStart, 1}};
216   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
217 }
218 
219 void InstrProfWriter::write(raw_fd_ostream &OS) {
220   // Write the hash table.
221   ProfOStream POS(OS);
222   writeImpl(POS);
223 }
224 
225 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
226   std::string Data;
227   llvm::raw_string_ostream OS(Data);
228   ProfOStream POS(OS);
229   // Write the hash table.
230   writeImpl(POS);
231   // Return this in an aligned memory buffer.
232   return MemoryBuffer::getMemBufferCopy(Data);
233 }
234 
235 static const char *ValueProfKindStr[] = {
236 #define VALUE_PROF_KIND(Enumerator, Value) #Enumerator,
237 #include "llvm/ProfileData/InstrProfData.inc"
238 };
239 
240 void InstrProfWriter::writeRecordInText(const InstrProfRecord &Func,
241                                         InstrProfSymtab &Symtab,
242                                         raw_fd_ostream &OS) {
243   OS << Func.Name << "\n";
244   OS << "# Func Hash:\n" << Func.Hash << "\n";
245   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
246   OS << "# Counter Values:\n";
247   for (uint64_t Count : Func.Counts)
248     OS << Count << "\n";
249 
250   uint32_t NumValueKinds = Func.getNumValueKinds();
251   if (!NumValueKinds) {
252     OS << "\n";
253     return;
254   }
255 
256   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
257   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
258     uint32_t NS = Func.getNumValueSites(VK);
259     if (!NS)
260       continue;
261     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
262     OS << "# NumValueSites:\n" << NS << "\n";
263     for (uint32_t S = 0; S < NS; S++) {
264       uint32_t ND = Func.getNumValueDataForSite(VK, S);
265       OS << ND << "\n";
266       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
267       for (uint32_t I = 0; I < ND; I++) {
268         if (VK == IPVK_IndirectCallTarget)
269           OS << Symtab.getFuncName(VD[I].Value) << ":" << VD[I].Count << "\n";
270         else
271           OS << VD[I].Value << ":" << VD[I].Count << "\n";
272       }
273     }
274   }
275 
276   OS << "\n";
277 }
278 
279 void InstrProfWriter::writeText(raw_fd_ostream &OS) {
280   InstrProfSymtab Symtab;
281   for (const auto &I : FunctionData)
282     Symtab.addFuncName(I.getKey());
283   Symtab.finalizeSymtab();
284 
285   for (const auto &I : FunctionData)
286     for (const auto &Func : I.getValue())
287       writeRecordInText(Func.second, Symtab, OS);
288 }
289