1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for reading profiling data for clang's
11 // instrumentation based PGO and coverage.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "llvm/ProfileData/InstrProf.h"
18 #include "InstrProfIndexed.h"
24 static error_code setupMemoryBuffer(std::string Path,
25 std::unique_ptr<MemoryBuffer> &Buffer) {
26 if (error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer))
29 // Sanity check the file.
30 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
31 return instrprof_error::too_large;
32 return instrprof_error::success;
35 static error_code initializeReader(InstrProfReader &Reader) {
36 return Reader.readHeader();
39 error_code InstrProfReader::create(std::string Path,
40 std::unique_ptr<InstrProfReader> &Result) {
41 // Set up the buffer to read.
42 std::unique_ptr<MemoryBuffer> Buffer;
43 if (error_code EC = setupMemoryBuffer(Path, Buffer))
47 if (IndexedInstrProfReader::hasFormat(*Buffer))
48 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
49 else if (RawInstrProfReader64::hasFormat(*Buffer))
50 Result.reset(new RawInstrProfReader64(std::move(Buffer)));
51 else if (RawInstrProfReader32::hasFormat(*Buffer))
52 Result.reset(new RawInstrProfReader32(std::move(Buffer)));
54 Result.reset(new TextInstrProfReader(std::move(Buffer)));
56 // Initialize the reader and return the result.
57 return initializeReader(*Result);
60 error_code IndexedInstrProfReader::create(
61 std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) {
62 // Set up the buffer to read.
63 std::unique_ptr<MemoryBuffer> Buffer;
64 if (error_code EC = setupMemoryBuffer(Path, Buffer))
68 if (!IndexedInstrProfReader::hasFormat(*Buffer))
69 return instrprof_error::bad_magic;
70 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
72 // Initialize the reader and return the result.
73 return initializeReader(*Result);
76 void InstrProfIterator::Increment() {
77 if (Reader->readNextRecord(Record))
78 *this = InstrProfIterator();
81 error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
83 while (!Line.is_at_end() && Line->empty())
85 // If we hit EOF while looking for a name, we're done.
87 return error(instrprof_error::eof);
89 // Read the function name.
90 Record.Name = *Line++;
92 // Read the function hash.
94 return error(instrprof_error::truncated);
95 if ((Line++)->getAsInteger(10, Record.Hash))
96 return error(instrprof_error::malformed);
98 // Read the number of counters.
100 if (Line.is_at_end())
101 return error(instrprof_error::truncated);
102 if ((Line++)->getAsInteger(10, NumCounters))
103 return error(instrprof_error::malformed);
105 // Read each counter and fill our internal storage with the values.
107 Counts.reserve(NumCounters);
108 for (uint64_t I = 0; I < NumCounters; ++I) {
109 if (Line.is_at_end())
110 return error(instrprof_error::truncated);
112 if ((Line++)->getAsInteger(10, Count))
113 return error(instrprof_error::malformed);
114 Counts.push_back(Count);
116 // Give the record a reference to our internal counter storage.
117 Record.Counts = Counts;
122 template <class IntPtrT>
123 static uint64_t getRawMagic();
126 uint64_t getRawMagic<uint64_t>() {
128 uint64_t(255) << 56 |
129 uint64_t('l') << 48 |
130 uint64_t('p') << 40 |
131 uint64_t('r') << 32 |
132 uint64_t('o') << 24 |
133 uint64_t('f') << 16 |
139 uint64_t getRawMagic<uint32_t>() {
141 uint64_t(255) << 56 |
142 uint64_t('l') << 48 |
143 uint64_t('p') << 40 |
144 uint64_t('r') << 32 |
145 uint64_t('o') << 24 |
146 uint64_t('f') << 16 |
151 template <class IntPtrT>
152 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
153 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
156 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
157 return getRawMagic<IntPtrT>() == Magic ||
158 sys::SwapByteOrder(getRawMagic<IntPtrT>()) == Magic;
161 template <class IntPtrT>
162 error_code RawInstrProfReader<IntPtrT>::readHeader() {
163 if (!hasFormat(*DataBuffer))
164 return error(instrprof_error::bad_magic);
165 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
166 return error(instrprof_error::bad_header);
168 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
169 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
170 return readHeader(*Header);
173 static uint64_t getRawVersion() {
177 template <class IntPtrT>
178 error_code RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
179 if (swap(Header.Version) != getRawVersion())
180 return error(instrprof_error::unsupported_version);
182 CountersDelta = swap(Header.CountersDelta);
183 NamesDelta = swap(Header.NamesDelta);
184 auto DataSize = swap(Header.DataSize);
185 auto CountersSize = swap(Header.CountersSize);
186 auto NamesSize = swap(Header.NamesSize);
188 ptrdiff_t DataOffset = sizeof(RawHeader);
189 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
190 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
191 size_t FileSize = NamesOffset + sizeof(char) * NamesSize;
193 if (FileSize != DataBuffer->getBufferSize())
194 return error(instrprof_error::bad_header);
196 const char *Start = DataBuffer->getBufferStart();
197 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
198 DataEnd = Data + DataSize;
199 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
200 NamesStart = Start + NamesOffset;
205 template <class IntPtrT>
207 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
209 return error(instrprof_error::eof);
212 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
213 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr),
214 swap(Data->NumCounters));
217 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
218 if (RawName.data() < NamesStart ||
219 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
220 RawCounts.data() < CountersStart ||
221 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
222 return error(instrprof_error::malformed);
224 // Store the data in Record, byte-swapping as necessary.
225 Record.Hash = swap(Data->FuncHash);
226 Record.Name = RawName;
227 if (ShouldSwapBytes) {
229 Counts.reserve(RawCounts.size());
230 for (uint64_t Count : RawCounts)
231 Counts.push_back(swap(Count));
232 Record.Counts = Counts;
234 Record.Counts = RawCounts;
242 template class RawInstrProfReader<uint32_t>;
243 template class RawInstrProfReader<uint64_t>;
246 InstrProfLookupTrait::hash_value_type
247 InstrProfLookupTrait::ComputeHash(StringRef K) {
248 return IndexedInstrProf::ComputeHash(HashType, K);
251 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
252 if (DataBuffer.getBufferSize() < 8)
254 using namespace support;
256 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
257 return Magic == IndexedInstrProf::Magic;
260 error_code IndexedInstrProfReader::readHeader() {
261 const unsigned char *Start = (unsigned char *)DataBuffer->getBufferStart();
262 const unsigned char *Cur = Start;
263 if ((unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
264 return error(instrprof_error::truncated);
266 using namespace support;
268 // Check the magic number.
269 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
270 if (Magic != IndexedInstrProf::Magic)
271 return error(instrprof_error::bad_magic);
274 uint64_t Version = endian::readNext<uint64_t, little, unaligned>(Cur);
275 if (Version != IndexedInstrProf::Version)
276 return error(instrprof_error::unsupported_version);
278 // Read the maximal function count.
279 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
281 // Read the hash type and start offset.
282 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
283 endian::readNext<uint64_t, little, unaligned>(Cur));
284 if (HashType > IndexedInstrProf::HashT::Last)
285 return error(instrprof_error::unsupported_hash_type);
286 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
288 // The rest of the file is an on disk hash table.
289 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
290 InstrProfLookupTrait(HashType)));
291 // Set up our iterator for readNextRecord.
292 RecordIterator = Index->data_begin();
297 error_code IndexedInstrProfReader::getFunctionCounts(
298 StringRef FuncName, uint64_t &FuncHash, std::vector<uint64_t> &Counts) {
299 const auto &Iter = Index->find(FuncName);
300 if (Iter == Index->end())
301 return error(instrprof_error::unknown_function);
303 // Found it. Make sure it's valid before giving back a result.
304 const InstrProfRecord &Record = *Iter;
305 if (Record.Name.empty())
306 return error(instrprof_error::malformed);
307 FuncHash = Record.Hash;
308 Counts = Record.Counts;
312 error_code IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
313 // Are we out of records?
314 if (RecordIterator == Index->data_end())
315 return error(instrprof_error::eof);
317 // Read the next one.
318 Record = *RecordIterator;
320 if (Record.Name.empty())
321 return error(instrprof_error::malformed);