465a4ea9e00a4dce0d1d9b753866555e2dd38468
[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
20 using namespace llvm;
21
22 namespace {
23 static support::endianness ValueProfDataEndianness = support::little;
24
25 class InstrProfRecordTrait {
26 public:
27   typedef StringRef key_type;
28   typedef StringRef key_type_ref;
29
30   typedef const InstrProfWriter::ProfilingData *const data_type;
31   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
32
33   typedef uint64_t hash_value_type;
34   typedef uint64_t offset_type;
35
36   static hash_value_type ComputeHash(key_type_ref K) {
37     return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType, K);
38   }
39
40   static std::pair<offset_type, offset_type>
41   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
42     using namespace llvm::support;
43     endian::Writer<little> LE(Out);
44
45     offset_type N = K.size();
46     LE.write<offset_type>(N);
47
48     offset_type M = 0;
49     for (const auto &ProfileData : *V) {
50       const InstrProfRecord &ProfRecord = ProfileData.second;
51       M += sizeof(uint64_t); // The function hash
52       M += sizeof(uint64_t); // The size of the Counts vector
53       M += ProfRecord.Counts.size() * sizeof(uint64_t);
54
55       // Value data
56       M += ValueProfData::getSize(ProfileData.second);
57     }
58     LE.write<offset_type>(M);
59
60     return std::make_pair(N, M);
61   }
62
63   static void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N){
64     Out.write(K.data(), N);
65   }
66
67   static void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V,
68                        offset_type) {
69     using namespace llvm::support;
70     endian::Writer<little> LE(Out);
71     for (const auto &ProfileData : *V) {
72       const InstrProfRecord &ProfRecord = ProfileData.second;
73
74       LE.write<uint64_t>(ProfileData.first); // Function hash
75       LE.write<uint64_t>(ProfRecord.Counts.size());
76       for (uint64_t I : ProfRecord.Counts)
77         LE.write<uint64_t>(I);
78
79       // Write value data
80       std::unique_ptr<ValueProfData> VDataPtr =
81           ValueProfData::serializeFrom(ProfileData.second);
82       uint32_t S = VDataPtr->getSize();
83       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
84       Out.write((const char *)VDataPtr.get(), S);
85     }
86   }
87 };
88 }
89
90 // Internal interface for testing purpose only.
91 void InstrProfWriter::setValueProfDataEndianness(
92     support::endianness Endianness) {
93   ValueProfDataEndianness = Endianness;
94 }
95
96 void InstrProfWriter::updateStringTableReferences(InstrProfRecord &I) {
97   I.updateStrings(&StringTable);
98 }
99
100 std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I) {
101   updateStringTableReferences(I);
102   auto &ProfileDataMap = FunctionData[I.Name];
103
104   bool NewFunc;
105   ProfilingData::iterator Where;
106   std::tie(Where, NewFunc) =
107       ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
108   InstrProfRecord &Dest = Where->second;
109   if (NewFunc) {
110     // We've never seen a function with this name and hash, add it.
111     Dest = std::move(I);
112   } else {
113     // We're updating a function we've seen before.
114     instrprof_error MergeResult = Dest.merge(I);
115     if (MergeResult != instrprof_error::success) {
116       return MergeResult;
117     }
118   }
119
120   // We keep track of the max function count as we go for simplicity.
121   if (Dest.Counts[0] > MaxFunctionCount)
122     MaxFunctionCount = Dest.Counts[0];
123
124   return instrprof_error::success;
125 }
126
127 std::pair<uint64_t, uint64_t> InstrProfWriter::writeImpl(raw_ostream &OS) {
128   OnDiskChainedHashTableGenerator<InstrProfRecordTrait> Generator;
129
130   // Populate the hash table generator.
131   for (const auto &I : FunctionData)
132     Generator.insert(I.getKey(), &I.getValue());
133
134   using namespace llvm::support;
135   endian::Writer<little> LE(OS);
136
137   // Write the header.
138   IndexedInstrProf::Header Header;
139   Header.Magic = IndexedInstrProf::Magic;
140   Header.Version = IndexedInstrProf::Version;
141   Header.MaxFunctionCount = MaxFunctionCount;
142   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
143   Header.HashOffset = 0;
144   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
145
146   // Only write out all the fields execpt 'HashOffset'. We need
147   // to remember the offset of that field to allow back patching
148   // later.
149   for (int I = 0; I < N - 1; I++)
150     LE.write<uint64_t>(reinterpret_cast<uint64_t *>(&Header)[I]);
151
152   // Save a space to write the hash table start location.
153   uint64_t HashTableStartLoc = OS.tell();
154   // Reserve the space for HashOffset field.
155   LE.write<uint64_t>(0);
156   // Write the hash table.
157   uint64_t HashTableStart = Generator.Emit(OS);
158
159   return std::make_pair(HashTableStartLoc, HashTableStart);
160 }
161
162 void InstrProfWriter::write(raw_fd_ostream &OS) {
163   // Write the hash table.
164   auto TableStart = writeImpl(OS);
165
166   // Go back and fill in the hash table start.
167   using namespace support;
168   OS.seek(TableStart.first);
169   // Now patch the HashOffset field previously reserved.
170   endian::Writer<little>(OS).write<uint64_t>(TableStart.second);
171 }
172
173 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
174   std::string Data;
175   llvm::raw_string_ostream OS(Data);
176   // Write the hash table.
177   auto TableStart = writeImpl(OS);
178   OS.flush();
179
180   // Go back and fill in the hash table start.
181   using namespace support;
182   uint64_t Bytes = endian::byte_swap<uint64_t, little>(TableStart.second);
183   Data.replace(TableStart.first, sizeof(uint64_t), (const char *)&Bytes,
184                sizeof(uint64_t));
185
186   // Return this in an aligned memory buffer.
187   return MemoryBuffer::getMemBufferCopy(Data);
188 }