LLVM API Documentation
00001 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains support for reading profiling data for clang's 00011 // instrumentation based PGO and coverage. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "llvm/ProfileData/InstrProfReader.h" 00016 #include "llvm/ProfileData/InstrProf.h" 00017 00018 #include "InstrProfIndexed.h" 00019 00020 #include <cassert> 00021 00022 using namespace llvm; 00023 00024 static std::error_code 00025 setupMemoryBuffer(std::string Path, std::unique_ptr<MemoryBuffer> &Buffer) { 00026 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 00027 MemoryBuffer::getFileOrSTDIN(Path); 00028 if (std::error_code EC = BufferOrErr.getError()) 00029 return EC; 00030 Buffer = std::move(BufferOrErr.get()); 00031 00032 // Sanity check the file. 00033 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max()) 00034 return instrprof_error::too_large; 00035 return instrprof_error::success; 00036 } 00037 00038 static std::error_code initializeReader(InstrProfReader &Reader) { 00039 return Reader.readHeader(); 00040 } 00041 00042 std::error_code 00043 InstrProfReader::create(std::string Path, 00044 std::unique_ptr<InstrProfReader> &Result) { 00045 // Set up the buffer to read. 00046 std::unique_ptr<MemoryBuffer> Buffer; 00047 if (std::error_code EC = setupMemoryBuffer(Path, Buffer)) 00048 return EC; 00049 00050 // Create the reader. 00051 if (IndexedInstrProfReader::hasFormat(*Buffer)) 00052 Result.reset(new IndexedInstrProfReader(std::move(Buffer))); 00053 else if (RawInstrProfReader64::hasFormat(*Buffer)) 00054 Result.reset(new RawInstrProfReader64(std::move(Buffer))); 00055 else if (RawInstrProfReader32::hasFormat(*Buffer)) 00056 Result.reset(new RawInstrProfReader32(std::move(Buffer))); 00057 else 00058 Result.reset(new TextInstrProfReader(std::move(Buffer))); 00059 00060 // Initialize the reader and return the result. 00061 return initializeReader(*Result); 00062 } 00063 00064 std::error_code IndexedInstrProfReader::create( 00065 std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) { 00066 // Set up the buffer to read. 00067 std::unique_ptr<MemoryBuffer> Buffer; 00068 if (std::error_code EC = setupMemoryBuffer(Path, Buffer)) 00069 return EC; 00070 00071 // Create the reader. 00072 if (!IndexedInstrProfReader::hasFormat(*Buffer)) 00073 return instrprof_error::bad_magic; 00074 Result.reset(new IndexedInstrProfReader(std::move(Buffer))); 00075 00076 // Initialize the reader and return the result. 00077 return initializeReader(*Result); 00078 } 00079 00080 void InstrProfIterator::Increment() { 00081 if (Reader->readNextRecord(Record)) 00082 *this = InstrProfIterator(); 00083 } 00084 00085 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) { 00086 // Skip empty lines and comments. 00087 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#"))) 00088 ++Line; 00089 // If we hit EOF while looking for a name, we're done. 00090 if (Line.is_at_end()) 00091 return error(instrprof_error::eof); 00092 00093 // Read the function name. 00094 Record.Name = *Line++; 00095 00096 // Read the function hash. 00097 if (Line.is_at_end()) 00098 return error(instrprof_error::truncated); 00099 if ((Line++)->getAsInteger(10, Record.Hash)) 00100 return error(instrprof_error::malformed); 00101 00102 // Read the number of counters. 00103 uint64_t NumCounters; 00104 if (Line.is_at_end()) 00105 return error(instrprof_error::truncated); 00106 if ((Line++)->getAsInteger(10, NumCounters)) 00107 return error(instrprof_error::malformed); 00108 if (NumCounters == 0) 00109 return error(instrprof_error::malformed); 00110 00111 // Read each counter and fill our internal storage with the values. 00112 Counts.clear(); 00113 Counts.reserve(NumCounters); 00114 for (uint64_t I = 0; I < NumCounters; ++I) { 00115 if (Line.is_at_end()) 00116 return error(instrprof_error::truncated); 00117 uint64_t Count; 00118 if ((Line++)->getAsInteger(10, Count)) 00119 return error(instrprof_error::malformed); 00120 Counts.push_back(Count); 00121 } 00122 // Give the record a reference to our internal counter storage. 00123 Record.Counts = Counts; 00124 00125 return success(); 00126 } 00127 00128 template <class IntPtrT> 00129 static uint64_t getRawMagic(); 00130 00131 template <> 00132 uint64_t getRawMagic<uint64_t>() { 00133 return 00134 uint64_t(255) << 56 | 00135 uint64_t('l') << 48 | 00136 uint64_t('p') << 40 | 00137 uint64_t('r') << 32 | 00138 uint64_t('o') << 24 | 00139 uint64_t('f') << 16 | 00140 uint64_t('r') << 8 | 00141 uint64_t(129); 00142 } 00143 00144 template <> 00145 uint64_t getRawMagic<uint32_t>() { 00146 return 00147 uint64_t(255) << 56 | 00148 uint64_t('l') << 48 | 00149 uint64_t('p') << 40 | 00150 uint64_t('r') << 32 | 00151 uint64_t('o') << 24 | 00152 uint64_t('f') << 16 | 00153 uint64_t('R') << 8 | 00154 uint64_t(129); 00155 } 00156 00157 template <class IntPtrT> 00158 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) { 00159 if (DataBuffer.getBufferSize() < sizeof(uint64_t)) 00160 return false; 00161 uint64_t Magic = 00162 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart()); 00163 return getRawMagic<IntPtrT>() == Magic || 00164 sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic; 00165 } 00166 00167 template <class IntPtrT> 00168 std::error_code RawInstrProfReader<IntPtrT>::readHeader() { 00169 if (!hasFormat(*DataBuffer)) 00170 return error(instrprof_error::bad_magic); 00171 if (DataBuffer->getBufferSize() < sizeof(RawHeader)) 00172 return error(instrprof_error::bad_header); 00173 auto *Header = 00174 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart()); 00175 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>(); 00176 return readHeader(*Header); 00177 } 00178 00179 template <class IntPtrT> 00180 std::error_code 00181 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) { 00182 const char *End = DataBuffer->getBufferEnd(); 00183 // Skip zero padding between profiles. 00184 while (CurrentPos != End && *CurrentPos == 0) 00185 ++CurrentPos; 00186 // If there's nothing left, we're done. 00187 if (CurrentPos == End) 00188 return instrprof_error::eof; 00189 // If there isn't enough space for another header, this is probably just 00190 // garbage at the end of the file. 00191 if (CurrentPos + sizeof(RawHeader) > End) 00192 return instrprof_error::malformed; 00193 // The writer ensures each profile is padded to start at an aligned address. 00194 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>()) 00195 return instrprof_error::malformed; 00196 // The magic should have the same byte order as in the previous header. 00197 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos); 00198 if (Magic != swap(getRawMagic<IntPtrT>())) 00199 return instrprof_error::bad_magic; 00200 00201 // There's another profile to read, so we need to process the header. 00202 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos); 00203 return readHeader(*Header); 00204 } 00205 00206 static uint64_t getRawVersion() { 00207 return 1; 00208 } 00209 00210 template <class IntPtrT> 00211 std::error_code 00212 RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) { 00213 if (swap(Header.Version) != getRawVersion()) 00214 return error(instrprof_error::unsupported_version); 00215 00216 CountersDelta = swap(Header.CountersDelta); 00217 NamesDelta = swap(Header.NamesDelta); 00218 auto DataSize = swap(Header.DataSize); 00219 auto CountersSize = swap(Header.CountersSize); 00220 auto NamesSize = swap(Header.NamesSize); 00221 00222 ptrdiff_t DataOffset = sizeof(RawHeader); 00223 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize; 00224 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize; 00225 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize; 00226 00227 auto *Start = reinterpret_cast<const char *>(&Header); 00228 if (Start + ProfileSize > DataBuffer->getBufferEnd()) 00229 return error(instrprof_error::bad_header); 00230 00231 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset); 00232 DataEnd = Data + DataSize; 00233 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset); 00234 NamesStart = Start + NamesOffset; 00235 ProfileEnd = Start + ProfileSize; 00236 00237 return success(); 00238 } 00239 00240 template <class IntPtrT> 00241 std::error_code 00242 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) { 00243 if (Data == DataEnd) 00244 if (std::error_code EC = readNextHeader(ProfileEnd)) 00245 return EC; 00246 00247 // Get the raw data. 00248 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize)); 00249 uint32_t NumCounters = swap(Data->NumCounters); 00250 if (NumCounters == 0) 00251 return error(instrprof_error::malformed); 00252 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters); 00253 00254 // Check bounds. 00255 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart); 00256 if (RawName.data() < NamesStart || 00257 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() || 00258 RawCounts.data() < CountersStart || 00259 RawCounts.data() + RawCounts.size() > NamesStartAsCounter) 00260 return error(instrprof_error::malformed); 00261 00262 // Store the data in Record, byte-swapping as necessary. 00263 Record.Hash = swap(Data->FuncHash); 00264 Record.Name = RawName; 00265 if (ShouldSwapBytes) { 00266 Counts.clear(); 00267 Counts.reserve(RawCounts.size()); 00268 for (uint64_t Count : RawCounts) 00269 Counts.push_back(swap(Count)); 00270 Record.Counts = Counts; 00271 } else 00272 Record.Counts = RawCounts; 00273 00274 // Iterate. 00275 ++Data; 00276 return success(); 00277 } 00278 00279 namespace llvm { 00280 template class RawInstrProfReader<uint32_t>; 00281 template class RawInstrProfReader<uint64_t>; 00282 } 00283 00284 InstrProfLookupTrait::hash_value_type 00285 InstrProfLookupTrait::ComputeHash(StringRef K) { 00286 return IndexedInstrProf::ComputeHash(HashType, K); 00287 } 00288 00289 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) { 00290 if (DataBuffer.getBufferSize() < 8) 00291 return false; 00292 using namespace support; 00293 uint64_t Magic = 00294 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart()); 00295 return Magic == IndexedInstrProf::Magic; 00296 } 00297 00298 std::error_code IndexedInstrProfReader::readHeader() { 00299 const unsigned char *Start = 00300 (const unsigned char *)DataBuffer->getBufferStart(); 00301 const unsigned char *Cur = Start; 00302 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24) 00303 return error(instrprof_error::truncated); 00304 00305 using namespace support; 00306 00307 // Check the magic number. 00308 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur); 00309 if (Magic != IndexedInstrProf::Magic) 00310 return error(instrprof_error::bad_magic); 00311 00312 // Read the version. 00313 FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur); 00314 if (FormatVersion > IndexedInstrProf::Version) 00315 return error(instrprof_error::unsupported_version); 00316 00317 // Read the maximal function count. 00318 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur); 00319 00320 // Read the hash type and start offset. 00321 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>( 00322 endian::readNext<uint64_t, little, unaligned>(Cur)); 00323 if (HashType > IndexedInstrProf::HashT::Last) 00324 return error(instrprof_error::unsupported_hash_type); 00325 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur); 00326 00327 // The rest of the file is an on disk hash table. 00328 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start, 00329 InstrProfLookupTrait(HashType))); 00330 // Set up our iterator for readNextRecord. 00331 RecordIterator = Index->data_begin(); 00332 00333 return success(); 00334 } 00335 00336 std::error_code IndexedInstrProfReader::getFunctionCounts( 00337 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) { 00338 auto Iter = Index->find(FuncName); 00339 if (Iter == Index->end()) 00340 return error(instrprof_error::unknown_function); 00341 00342 // Found it. Look for counters with the right hash. 00343 ArrayRef<uint64_t> Data = (*Iter).Data; 00344 uint64_t NumCounts; 00345 for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) { 00346 // The function hash comes first. 00347 uint64_t FoundHash = Data[I++]; 00348 // In v1, we have at least one count. Later, we have the number of counts. 00349 if (I == E) 00350 return error(instrprof_error::malformed); 00351 NumCounts = FormatVersion == 1 ? E - I : Data[I++]; 00352 // If we have more counts than data, this is bogus. 00353 if (I + NumCounts > E) 00354 return error(instrprof_error::malformed); 00355 // Check for a match and fill the vector if there is one. 00356 if (FoundHash == FuncHash) { 00357 Counts = Data.slice(I, NumCounts); 00358 return success(); 00359 } 00360 } 00361 return error(instrprof_error::hash_mismatch); 00362 } 00363 00364 std::error_code 00365 IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) { 00366 // Are we out of records? 00367 if (RecordIterator == Index->data_end()) 00368 return error(instrprof_error::eof); 00369 00370 // Record the current function name. 00371 Record.Name = (*RecordIterator).Name; 00372 00373 ArrayRef<uint64_t> Data = (*RecordIterator).Data; 00374 // Valid data starts with a hash and either a count or the number of counts. 00375 if (CurrentOffset + 1 > Data.size()) 00376 return error(instrprof_error::malformed); 00377 // First we have a function hash. 00378 Record.Hash = Data[CurrentOffset++]; 00379 // In version 1 we knew the number of counters implicitly, but in newer 00380 // versions we store the number of counters next. 00381 uint64_t NumCounts = 00382 FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++]; 00383 if (CurrentOffset + NumCounts > Data.size()) 00384 return error(instrprof_error::malformed); 00385 // And finally the counts themselves. 00386 Record.Counts = Data.slice(CurrentOffset, NumCounts); 00387 00388 // If we've exhausted this function's data, increment the record. 00389 CurrentOffset += NumCounts; 00390 if (CurrentOffset == Data.size()) { 00391 ++RecordIterator; 00392 CurrentOffset = 0; 00393 } 00394 00395 return success(); 00396 }