[PGO] Fix a bug in InstProfWriter addRecord
[oota-llvm.git] / lib / ProfileData / InstrProfWriter.cpp
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 namespace {
24 static support::endianness ValueProfDataEndianness = support::little;
25
26 class InstrProfRecordTrait {
27 public:
28   typedef StringRef key_type;
29   typedef StringRef key_type_ref;
30
31   typedef const InstrProfWriter::ProfilingData *const data_type;
32   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
33
34   typedef uint64_t hash_value_type;
35   typedef uint64_t offset_type;
36
37   static hash_value_type ComputeHash(key_type_ref K) {
38     return IndexedInstrProf::ComputeHash(K);
39   }
40
41   static std::pair<offset_type, offset_type>
42   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
43     using namespace llvm::support;
44     endian::Writer<little> LE(Out);
45
46     offset_type N = K.size();
47     LE.write<offset_type>(N);
48
49     offset_type M = 0;
50     for (const auto &ProfileData : *V) {
51       const InstrProfRecord &ProfRecord = ProfileData.second;
52       M += sizeof(uint64_t); // The function hash
53       M += sizeof(uint64_t); // The size of the Counts vector
54       M += ProfRecord.Counts.size() * sizeof(uint64_t);
55
56       // Value data
57       M += ValueProfData::getSize(ProfileData.second);
58     }
59     LE.write<offset_type>(M);
60
61     return std::make_pair(N, M);
62   }
63
64   static void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N){
65     Out.write(K.data(), N);
66   }
67
68   static void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V,
69                        offset_type) {
70     using namespace llvm::support;
71     endian::Writer<little> LE(Out);
72     for (const auto &ProfileData : *V) {
73       const InstrProfRecord &ProfRecord = ProfileData.second;
74
75       LE.write<uint64_t>(ProfileData.first); // Function hash
76       LE.write<uint64_t>(ProfRecord.Counts.size());
77       for (uint64_t I : ProfRecord.Counts)
78         LE.write<uint64_t>(I);
79
80       // Write value data
81       std::unique_ptr<ValueProfData> VDataPtr =
82           ValueProfData::serializeFrom(ProfileData.second);
83       uint32_t S = VDataPtr->getSize();
84       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
85       Out.write((const char *)VDataPtr.get(), S);
86     }
87   }
88 };
89 }
90
91 // Internal interface for testing purpose only.
92 void InstrProfWriter::setValueProfDataEndianness(
93     support::endianness Endianness) {
94   ValueProfDataEndianness = Endianness;
95 }
96
97 std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I,
98                                            uint64_t Weight) {
99   auto &ProfileDataMap = FunctionData[I.Name];
100
101   bool NewFunc;
102   ProfilingData::iterator Where;
103   std::tie(Where, NewFunc) =
104       ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
105   InstrProfRecord &Dest = Where->second;
106
107   instrprof_error Result = instrprof_error::success;
108   if (NewFunc) {
109     // We've never seen a function with this name and hash, add it.
110     Dest = std::move(I);
111     // Fix up the name to avoid dangling reference.
112     Dest.Name = FunctionData.find(Dest.Name)->getKey();
113     if (Weight > 1)
114       Result = Dest.scale(Weight);
115   } else {
116     // We're updating a function we've seen before.
117     Result = Dest.merge(I, Weight);
118   }
119
120   // We keep track of the max function count as we go for simplicity.
121   // Update this statistic no matter the result of the merge.
122   if (Dest.Counts[0] > MaxFunctionCount)
123     MaxFunctionCount = Dest.Counts[0];
124
125   return Result;
126 }
127
128 std::pair<uint64_t, uint64_t> InstrProfWriter::writeImpl(raw_ostream &OS) {
129   OnDiskChainedHashTableGenerator<InstrProfRecordTrait> Generator;
130
131   // Populate the hash table generator.
132   for (const auto &I : FunctionData)
133     Generator.insert(I.getKey(), &I.getValue());
134
135   using namespace llvm::support;
136   endian::Writer<little> LE(OS);
137
138   // Write the header.
139   IndexedInstrProf::Header Header;
140   Header.Magic = IndexedInstrProf::Magic;
141   Header.Version = IndexedInstrProf::Version;
142   Header.MaxFunctionCount = MaxFunctionCount;
143   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
144   Header.HashOffset = 0;
145   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
146
147   // Only write out all the fields execpt 'HashOffset'. We need
148   // to remember the offset of that field to allow back patching
149   // later.
150   for (int I = 0; I < N - 1; I++)
151     LE.write<uint64_t>(reinterpret_cast<uint64_t *>(&Header)[I]);
152
153   // Save a space to write the hash table start location.
154   uint64_t HashTableStartLoc = OS.tell();
155   // Reserve the space for HashOffset field.
156   LE.write<uint64_t>(0);
157   // Write the hash table.
158   uint64_t HashTableStart = Generator.Emit(OS);
159
160   return std::make_pair(HashTableStartLoc, HashTableStart);
161 }
162
163 void InstrProfWriter::write(raw_fd_ostream &OS) {
164   // Write the hash table.
165   auto TableStart = writeImpl(OS);
166
167   // Go back and fill in the hash table start.
168   using namespace support;
169   OS.seek(TableStart.first);
170   // Now patch the HashOffset field previously reserved.
171   endian::Writer<little>(OS).write<uint64_t>(TableStart.second);
172 }
173
174 static const char *ValueProfKindStr[] = {
175 #define VALUE_PROF_KIND(Enumerator, Value) #Enumerator,
176 #include "llvm/ProfileData/InstrProfData.inc"
177 };
178
179 void InstrProfWriter::writeRecordInText(const InstrProfRecord &Func,
180                                         InstrProfSymtab &Symtab,
181                                         raw_fd_ostream &OS) {
182   OS << Func.Name << "\n";
183   OS << "# Func Hash:\n" << Func.Hash << "\n";
184   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
185   OS << "# Counter Values:\n";
186   for (uint64_t Count : Func.Counts)
187     OS << Count << "\n";
188
189   uint32_t NumValueKinds = Func.getNumValueKinds();
190   if (!NumValueKinds) {
191     OS << "\n";
192     return;
193   }
194
195   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
196   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
197     uint32_t NS = Func.getNumValueSites(VK);
198     if (!NS)
199       continue;
200     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
201     OS << "# NumValueSites:\n" << NS << "\n";
202     for (uint32_t S = 0; S < NS; S++) {
203       uint32_t ND = Func.getNumValueDataForSite(VK, S);
204       OS << ND << "\n";
205       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
206       for (uint32_t I = 0; I < ND; I++) {
207         if (VK == IPVK_IndirectCallTarget)
208           OS << Symtab.getFuncName(VD[I].Value) << ":" << VD[I].Count << "\n";
209         else
210           OS << VD[I].Value << ":" << VD[I].Count << "\n";
211       }
212     }
213   }
214
215   OS << "\n";
216 }
217
218 void InstrProfWriter::writeText(raw_fd_ostream &OS) {
219   InstrProfSymtab Symtab;
220   for (const auto &I : FunctionData)
221     Symtab.addFuncName(I.getKey());
222   Symtab.finalizeSymtab();
223
224   for (const auto &I : FunctionData)
225     for (const auto &Func : I.getValue())
226       writeRecordInText(Func.second, Symtab, OS);
227 }
228
229 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
230   std::string Data;
231   llvm::raw_string_ostream OS(Data);
232   // Write the hash table.
233   auto TableStart = writeImpl(OS);
234   OS.flush();
235
236   // Go back and fill in the hash table start.
237   using namespace support;
238   uint64_t Bytes = endian::byte_swap<uint64_t, little>(TableStart.second);
239   Data.replace(TableStart.first, sizeof(uint64_t), (const char *)&Bytes,
240                sizeof(uint64_t));
241
242   // Return this in an aligned memory buffer.
243   return MemoryBuffer::getMemBufferCopy(Data);
244 }