LLVM  5.0.0
InstrProfReader.cpp
Go to the documentation of this file.
1 //===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//
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 reading profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/IR/ProfileSummary.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorOr.h"
27 #include <algorithm>
28 #include <cctype>
29 #include <cstddef>
30 #include <cstdint>
31 #include <limits>
32 #include <memory>
33 #include <system_error>
34 #include <utility>
35 #include <vector>
36 
37 using namespace llvm;
38 
40 setupMemoryBuffer(const Twine &Path) {
43  if (std::error_code EC = BufferOrErr.getError())
44  return errorCodeToError(EC);
45  return std::move(BufferOrErr.get());
46 }
47 
49  return Reader.readHeader();
50 }
51 
54  // Set up the buffer to read.
55  auto BufferOrError = setupMemoryBuffer(Path);
56  if (Error E = BufferOrError.takeError())
57  return std::move(E);
58  return InstrProfReader::create(std::move(BufferOrError.get()));
59 }
60 
62 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
63  // Sanity check the buffer.
64  if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
65  return make_error<InstrProfError>(instrprof_error::too_large);
66 
67  if (Buffer->getBufferSize() == 0)
68  return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
69 
70  std::unique_ptr<InstrProfReader> Result;
71  // Create the reader.
73  Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
74  else if (RawInstrProfReader64::hasFormat(*Buffer))
75  Result.reset(new RawInstrProfReader64(std::move(Buffer)));
76  else if (RawInstrProfReader32::hasFormat(*Buffer))
77  Result.reset(new RawInstrProfReader32(std::move(Buffer)));
78  else if (TextInstrProfReader::hasFormat(*Buffer))
79  Result.reset(new TextInstrProfReader(std::move(Buffer)));
80  else
81  return make_error<InstrProfError>(instrprof_error::unrecognized_format);
82 
83  // Initialize the reader and return the result.
84  if (Error E = initializeReader(*Result))
85  return std::move(E);
86 
87  return std::move(Result);
88 }
89 
92  // Set up the buffer to read.
93  auto BufferOrError = setupMemoryBuffer(Path);
94  if (Error E = BufferOrError.takeError())
95  return std::move(E);
96  return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
97 }
98 
100 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
101  // Sanity check the buffer.
102  if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
103  return make_error<InstrProfError>(instrprof_error::too_large);
104 
105  // Create the reader.
106  if (!IndexedInstrProfReader::hasFormat(*Buffer))
107  return make_error<InstrProfError>(instrprof_error::bad_magic);
108  auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
109 
110  // Initialize the reader and return the result.
111  if (Error E = initializeReader(*Result))
112  return std::move(E);
113 
114  return std::move(Result);
115 }
116 
117 void InstrProfIterator::Increment() {
118  if (auto E = Reader->readNextRecord(Record)) {
119  // Handle errors in the reader.
120  InstrProfError::take(std::move(E));
121  *this = InstrProfIterator();
122  }
123 }
124 
126  // Verify that this really looks like plain ASCII text by checking a
127  // 'reasonable' number of characters (up to profile magic size).
128  size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
129  StringRef buffer = Buffer.getBufferStart();
130  return count == 0 ||
131  std::all_of(buffer.begin(), buffer.begin() + count,
132  [](char c) { return ::isprint(c) || ::isspace(c); });
133 }
134 
135 // Read the profile variant flag from the header: ":FE" means this is a FE
136 // generated profile. ":IR" means this is an IR level profile. Other strings
137 // with a leading ':' will be reported an error format.
139  Symtab.reset(new InstrProfSymtab());
140  bool IsIRInstr = false;
141  if (!Line->startswith(":")) {
142  IsIRLevelProfile = false;
143  return success();
144  }
145  StringRef Str = (Line)->substr(1);
146  if (Str.equals_lower("ir"))
147  IsIRInstr = true;
148  else if (Str.equals_lower("fe"))
149  IsIRInstr = false;
150  else
152 
153  ++Line;
154  IsIRLevelProfile = IsIRInstr;
155  return success();
156 }
157 
158 Error
159 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
160 
161 #define CHECK_LINE_END(Line) \
162  if (Line.is_at_end()) \
163  return error(instrprof_error::truncated);
164 #define READ_NUM(Str, Dst) \
165  if ((Str).getAsInteger(10, (Dst))) \
166  return error(instrprof_error::malformed);
167 #define VP_READ_ADVANCE(Val) \
168  CHECK_LINE_END(Line); \
169  uint32_t Val; \
170  READ_NUM((*Line), (Val)); \
171  Line++;
172 
173  if (Line.is_at_end())
174  return success();
175 
176  uint32_t NumValueKinds;
177  if (Line->getAsInteger(10, NumValueKinds)) {
178  // No value profile data
179  return success();
180  }
181  if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
183  Line++;
184 
185  for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
187  if (ValueKind > IPVK_Last)
189  VP_READ_ADVANCE(NumValueSites);
190  if (!NumValueSites)
191  continue;
192 
193  Record.reserveSites(VK, NumValueSites);
194  for (uint32_t S = 0; S < NumValueSites; S++) {
195  VP_READ_ADVANCE(NumValueData);
196 
197  std::vector<InstrProfValueData> CurrentValues;
198  for (uint32_t V = 0; V < NumValueData; V++) {
199  CHECK_LINE_END(Line);
200  std::pair<StringRef, StringRef> VD = Line->rsplit(':');
201  uint64_t TakenCount, Value;
202  if (ValueKind == IPVK_IndirectCallTarget) {
203  if (Error E = Symtab->addFuncName(VD.first))
204  return E;
205  Value = IndexedInstrProf::ComputeHash(VD.first);
206  } else {
207  READ_NUM(VD.first, Value);
208  }
209  READ_NUM(VD.second, TakenCount);
210  CurrentValues.push_back({Value, TakenCount});
211  Line++;
212  }
213  Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData,
214  nullptr);
215  }
216  }
217  return success();
218 
219 #undef CHECK_LINE_END
220 #undef READ_NUM
221 #undef VP_READ_ADVANCE
222 }
223 
225  // Skip empty lines and comments.
226  while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
227  ++Line;
228  // If we hit EOF while looking for a name, we're done.
229  if (Line.is_at_end()) {
230  Symtab->finalizeSymtab();
231  return error(instrprof_error::eof);
232  }
233 
234  // Read the function name.
235  Record.Name = *Line++;
236  if (Error E = Symtab->addFuncName(Record.Name))
237  return E;
238 
239  // Read the function hash.
240  if (Line.is_at_end())
242  if ((Line++)->getAsInteger(0, Record.Hash))
244 
245  // Read the number of counters.
246  uint64_t NumCounters;
247  if (Line.is_at_end())
249  if ((Line++)->getAsInteger(10, NumCounters))
251  if (NumCounters == 0)
253 
254  // Read each counter and fill our internal storage with the values.
255  Record.Clear();
256  Record.Counts.reserve(NumCounters);
257  for (uint64_t I = 0; I < NumCounters; ++I) {
258  if (Line.is_at_end())
260  uint64_t Count;
261  if ((Line++)->getAsInteger(10, Count))
263  Record.Counts.push_back(Count);
264  }
265 
266  // Check if value profile data exists and read it if so.
267  if (Error E = readValueProfileData(Record))
268  return E;
269 
270  // This is needed to avoid two pass parsing because llvm-profdata
271  // does dumping while reading.
272  Symtab->finalizeSymtab();
273  return success();
274 }
275 
276 template <class IntPtrT>
278  if (DataBuffer.getBufferSize() < sizeof(uint64_t))
279  return false;
280  uint64_t Magic =
281  *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
282  return RawInstrProf::getMagic<IntPtrT>() == Magic ||
283  sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
284 }
285 
286 template <class IntPtrT>
288  if (!hasFormat(*DataBuffer))
290  if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
292  auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
293  DataBuffer->getBufferStart());
294  ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
295  return readHeader(*Header);
296 }
297 
298 template <class IntPtrT>
299 Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
300  const char *End = DataBuffer->getBufferEnd();
301  // Skip zero padding between profiles.
302  while (CurrentPos != End && *CurrentPos == 0)
303  ++CurrentPos;
304  // If there's nothing left, we're done.
305  if (CurrentPos == End)
306  return make_error<InstrProfError>(instrprof_error::eof);
307  // If there isn't enough space for another header, this is probably just
308  // garbage at the end of the file.
309  if (CurrentPos + sizeof(RawInstrProf::Header) > End)
310  return make_error<InstrProfError>(instrprof_error::malformed);
311  // The writer ensures each profile is padded to start at an aligned address.
312  if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
313  return make_error<InstrProfError>(instrprof_error::malformed);
314  // The magic should have the same byte order as in the previous header.
315  uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
316  if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
317  return make_error<InstrProfError>(instrprof_error::bad_magic);
318 
319  // There's another profile to read, so we need to process the header.
320  auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
321  return readHeader(*Header);
322 }
323 
324 template <class IntPtrT>
326  if (Error E = Symtab.create(StringRef(NamesStart, NamesSize)))
327  return error(std::move(E));
328  for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
329  const IntPtrT FPtr = swap(I->FunctionPointer);
330  if (!FPtr)
331  continue;
332  Symtab.mapAddress(FPtr, I->NameRef);
333  }
334  Symtab.finalizeSymtab();
335  return success();
336 }
337 
338 template <class IntPtrT>
340  const RawInstrProf::Header &Header) {
341  Version = swap(Header.Version);
342  if (GET_VERSION(Version) != RawInstrProf::Version)
344 
345  CountersDelta = swap(Header.CountersDelta);
346  NamesDelta = swap(Header.NamesDelta);
347  auto DataSize = swap(Header.DataSize);
348  auto CountersSize = swap(Header.CountersSize);
349  NamesSize = swap(Header.NamesSize);
350  ValueKindLast = swap(Header.ValueKindLast);
351 
352  auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
353  auto PaddingSize = getNumPaddingBytes(NamesSize);
354 
355  ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
356  ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
357  ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
358  ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
359 
360  auto *Start = reinterpret_cast<const char *>(&Header);
361  if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
363 
364  Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
365  Start + DataOffset);
366  DataEnd = Data + DataSize;
367  CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
368  NamesStart = Start + NamesOffset;
369  ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
370 
371  std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
372  if (Error E = createSymtab(*NewSymtab.get()))
373  return E;
374 
375  Symtab = std::move(NewSymtab);
376  return success();
377 }
378 
379 template <class IntPtrT>
381  Record.Name = getName(Data->NameRef);
382  return success();
383 }
384 
385 template <class IntPtrT>
387  Record.Hash = swap(Data->FuncHash);
388  return success();
389 }
390 
391 template <class IntPtrT>
393  InstrProfRecord &Record) {
394  uint32_t NumCounters = swap(Data->NumCounters);
395  IntPtrT CounterPtr = Data->CounterPtr;
396  if (NumCounters == 0)
398 
399  auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
400  auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
401 
402  // Check bounds.
403  if (RawCounts.data() < CountersStart ||
404  RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
406 
407  if (ShouldSwapBytes) {
408  Record.Counts.clear();
409  Record.Counts.reserve(RawCounts.size());
410  for (uint64_t Count : RawCounts)
411  Record.Counts.push_back(swap(Count));
412  } else
413  Record.Counts = RawCounts;
414 
415  return success();
416 }
417 
418 template <class IntPtrT>
420  InstrProfRecord &Record) {
421  Record.clearValueData();
422  CurValueDataSize = 0;
423  // Need to match the logic in value profile dumper code in compiler-rt:
424  uint32_t NumValueKinds = 0;
425  for (uint32_t I = 0; I < IPVK_Last + 1; I++)
426  NumValueKinds += (Data->NumValueSites[I] != 0);
427 
428  if (!NumValueKinds)
429  return success();
430 
432  ValueProfData::getValueProfData(
433  ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
434  getDataEndianness());
435 
436  if (Error E = VDataPtrOrErr.takeError())
437  return E;
438 
439  // Note that besides deserialization, this also performs the conversion for
440  // indirect call targets. The function pointers from the raw profile are
441  // remapped into function name hashes.
442  VDataPtrOrErr.get()->deserializeTo(Record, &Symtab->getAddrHashMap());
443  CurValueDataSize = VDataPtrOrErr.get()->getSize();
444  return success();
445 }
446 
447 template <class IntPtrT>
449  if (atEnd())
450  // At this point, ValueDataStart field points to the next header.
451  if (Error E = readNextHeader(getNextHeaderPos()))
452  return E;
453 
454  // Read name ad set it in Record.
455  if (Error E = readName(Record))
456  return E;
457 
458  // Read FuncHash and set it in Record.
459  if (Error E = readFuncHash(Record))
460  return E;
461 
462  // Read raw counts and set Record.
463  if (Error E = readRawCounts(Record))
464  return E;
465 
466  // Read value data and set Record.
467  if (Error E = readValueProfilingData(Record))
468  return E;
469 
470  // Iterate.
471  advanceData();
472  return success();
473 }
474 
475 namespace llvm {
476 
477 template class RawInstrProfReader<uint32_t>;
478 template class RawInstrProfReader<uint64_t>;
479 
480 } // end namespace llvm
481 
484  return IndexedInstrProf::ComputeHash(HashType, K);
485 }
486 
489 
491  const unsigned char *&D, const unsigned char *const End) {
493  ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
494 
495  if (VDataPtrOrErr.takeError())
496  return false;
497 
498  VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
499  D += VDataPtrOrErr.get()->TotalSize;
500 
501  return true;
502 }
503 
505  offset_type N) {
506  using namespace support;
507 
508  // Check if the data is corrupt. If so, don't try to read it.
509  if (N % sizeof(uint64_t))
510  return data_type();
511 
512  DataBuffer.clear();
513  std::vector<uint64_t> CounterBuffer;
514 
515  const unsigned char *End = D + N;
516  while (D < End) {
517  // Read hash.
518  if (D + sizeof(uint64_t) >= End)
519  return data_type();
520  uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
521 
522  // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
523  uint64_t CountsSize = N / sizeof(uint64_t) - 1;
524  // If format version is different then read the number of counters.
525  if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
526  if (D + sizeof(uint64_t) > End)
527  return data_type();
528  CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
529  }
530  // Read counter values.
531  if (D + CountsSize * sizeof(uint64_t) > End)
532  return data_type();
533 
534  CounterBuffer.clear();
535  CounterBuffer.reserve(CountsSize);
536  for (uint64_t J = 0; J < CountsSize; ++J)
537  CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
538 
539  DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
540 
541  // Read value profiling data.
542  if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
543  !readValueProfilingData(D, End)) {
544  DataBuffer.clear();
545  return data_type();
546  }
547  }
548  return DataBuffer;
549 }
550 
551 template <typename HashTableImpl>
554  auto Iter = HashTable->find(FuncName);
555  if (Iter == HashTable->end())
556  return make_error<InstrProfError>(instrprof_error::unknown_function);
557 
558  Data = (*Iter);
559  if (Data.empty())
560  return make_error<InstrProfError>(instrprof_error::malformed);
561 
562  return Error::success();
563 }
564 
565 template <typename HashTableImpl>
568  if (atEnd())
569  return make_error<InstrProfError>(instrprof_error::eof);
570 
571  Data = *RecordIterator;
572 
573  if (Data.empty())
574  return make_error<InstrProfError>(instrprof_error::malformed);
575 
576  return Error::success();
577 }
578 
579 template <typename HashTableImpl>
581  const unsigned char *Buckets, const unsigned char *const Payload,
582  const unsigned char *const Base, IndexedInstrProf::HashT HashType,
583  uint64_t Version) {
584  FormatVersion = Version;
585  HashTable.reset(HashTableImpl::Create(
586  Buckets, Payload, Base,
587  typename HashTableImpl::InfoType(HashType, Version)));
588  RecordIterator = HashTable->data_begin();
589 }
590 
592  using namespace support;
593 
594  if (DataBuffer.getBufferSize() < 8)
595  return false;
596  uint64_t Magic =
597  endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
598  // Verify that it's magical.
599  return Magic == IndexedInstrProf::Magic;
600 }
601 
602 const unsigned char *
603 IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
604  const unsigned char *Cur) {
605  using namespace IndexedInstrProf;
606  using namespace support;
607 
608  if (Version >= IndexedInstrProf::Version4) {
609  const IndexedInstrProf::Summary *SummaryInLE =
610  reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
611  uint64_t NFields =
612  endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
613  uint64_t NEntries =
614  endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
615  uint32_t SummarySize =
616  IndexedInstrProf::Summary::getSize(NFields, NEntries);
617  std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
618  IndexedInstrProf::allocSummary(SummarySize);
619 
620  const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
621  uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
622  for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
623  Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
624 
625  SummaryEntryVector DetailedSummary;
626  for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
627  const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
628  DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
629  Ent.NumBlocks);
630  }
631  // initialize InstrProfSummary using the SummaryData from disk.
632  this->Summary = llvm::make_unique<ProfileSummary>(
633  ProfileSummary::PSK_Instr, DetailedSummary,
634  SummaryData->get(Summary::TotalBlockCount),
635  SummaryData->get(Summary::MaxBlockCount),
636  SummaryData->get(Summary::MaxInternalBlockCount),
637  SummaryData->get(Summary::MaxFunctionCount),
638  SummaryData->get(Summary::TotalNumBlocks),
639  SummaryData->get(Summary::TotalNumFunctions));
640  return Cur + SummarySize;
641  } else {
642  // For older version of profile data, we need to compute on the fly:
643  using namespace IndexedInstrProf;
644 
646  // FIXME: This only computes an empty summary. Need to call addRecord for
647  // all NamedInstrProfRecords to get the correct summary.
648  this->Summary = Builder.getSummary();
649  return Cur;
650  }
651 }
652 
654  using namespace support;
655 
656  const unsigned char *Start =
657  (const unsigned char *)DataBuffer->getBufferStart();
658  const unsigned char *Cur = Start;
659  if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
661 
662  auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
663  Cur += sizeof(IndexedInstrProf::Header);
664 
665  // Check the magic number.
666  uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
667  if (Magic != IndexedInstrProf::Magic)
669 
670  // Read the version.
671  uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
672  if (GET_VERSION(FormatVersion) >
675 
676  Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur);
677 
678  // Read the hash type and start offset.
679  IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
680  endian::byte_swap<uint64_t, little>(Header->HashType));
681  if (HashType > IndexedInstrProf::HashT::Last)
683 
684  uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
685 
686  // The rest of the file is an on disk hash table.
687  InstrProfReaderIndexBase *IndexPtr = nullptr;
689  Start + HashOffset, Cur, Start, HashType, FormatVersion);
690  Index.reset(IndexPtr);
691  return success();
692 }
693 
695  if (Symtab.get())
696  return *Symtab.get();
697 
698  std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
699  if (Error E = Index->populateSymtab(*NewSymtab.get())) {
701  }
702 
703  Symtab = std::move(NewSymtab);
704  return *Symtab.get();
705 }
706 
709  uint64_t FuncHash) {
711  Error Err = Index->getRecords(FuncName, Data);
712  if (Err)
713  return std::move(Err);
714  // Found it. Look for counters with the right hash.
715  for (unsigned I = 0, E = Data.size(); I < E; ++I) {
716  // Check for a match and fill the vector if there is one.
717  if (Data[I].Hash == FuncHash) {
718  return std::move(Data[I]);
719  }
720  }
722 }
723 
725  uint64_t FuncHash,
726  std::vector<uint64_t> &Counts) {
727  Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
728  if (Error E = Record.takeError())
729  return error(std::move(E));
730 
731  Counts = Record.get().Counts;
732  return success();
733 }
734 
736  static unsigned RecordIndex = 0;
737 
739 
740  Error E = Index->getRecords(Data);
741  if (E)
742  return error(std::move(E));
743 
744  Record = Data[RecordIndex++];
745  if (RecordIndex >= Data.size()) {
746  Index->advanceToNextKey();
747  RecordIndex = 0;
748  }
749  return success();
750 }
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:497
#define VP_READ_ADVANCE(Val)
std::error_code getError() const
Definition: ErrorOr.h:172
Represents either an error or a value T.
Definition: ErrorOr.h:69
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:410
Error readHeader() override
Read the header. Required before reading first record.
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition: InstrProf.h:921
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const char * getBufferStart() const
Definition: MemoryBuffer.h:55
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition: InstrProf.h:887
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static bool hasFormat(const MemoryBuffer &DataBuffer)
Return true if the given buffer is in an indexed instrprof format.
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
Definition: InstrProf.h:323
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
Definition: StringRef.h:176
Error error(instrprof_error Err)
Set the current error and return same.
AddrHashMap & getAddrHashMap()
Definition: InstrProf.h:482
#define error(X)
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition: InstrProf.h:961
static const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Definition: ProfileCommon.h:65
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:818
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
InstrProfLookupTrait::offset_type offset_type
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:802
Error readHeader() override
Read the header.
data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
const uint64_t Magic
Definition: InstrProf.h:842
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path)
Factory method to create an appropriately typed reader for the given instrprof file.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
static StringRef getName(Value *V)
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition: InstrProf.h:478
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:880
const uint64_t Version
Definition: InstrProf.h:977
Reader for the simple text based instrprof format.
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition: InstrProf.h:888
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static bool hasFormat(const MemoryBuffer &DataBuffer)
iterator begin() const
Definition: StringRef.h:106
hash_value_type ComputeHash(StringRef K)
ArrayRef< NamedInstrProfRecord > data_type
Base class and interface for reading profiling data of any known instrprof format.
uint64_t Cutoff
The required percentile of total execution count.
Definition: InstrProf.h:885
bool is_at_end() const
Return true if we're an "end" iterator or have reached EOF.
Definition: LineIterator.h:53
LLVM_NODISCARD std::pair< StringRef, StringRef > rsplit(char Separator) const
Split into two substrings around the last occurrence of a separator character.
Definition: StringRef.h:798
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
std::unique_ptr< InstrProfSymtab > Symtab
static const unsigned End
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
uint64_t ComputeHash(StringRef K)
Definition: InstrProf.h:868
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
#define CHECK_LINE_END(Line)
#define READ_NUM(Str, Dst)
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, ValueMapType *ValueMap)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:582
void clearValueData()
Clear value data entries.
Definition: InstrProf.h:676
static const char *const Magic
Definition: Archive.cpp:42
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Path)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
#define E
Definition: LargeTest.cpp:27
RawInstrProfReader< uint32_t > RawInstrProfReader32
const size_t N
Reader for the raw instrprof binary format from runtime.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:744
RawInstrProfReader< uint64_t > RawInstrProfReader64
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:40
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
unsigned char getSwappedBytes(unsigned char C)
Definition: SwapByteOrder.h:72
size_t getBufferSize() const
Definition: MemoryBuffer.h:57
success
Parameters (see the expansion example below): (the builder, addr, loaded, new_val, ordering, /* OUT.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
std::vector< uint64_t > Counts
Definition: InstrProf.h:592
Error readHeader() override
Read the file header.
virtual Error readHeader()=0
Read the header. Required before reading first record.
Profiling information for a single function.
Definition: InstrProf.h:591
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
#define I(x, y, z)
Definition: MD5.cpp:58
virtual Error readNextRecord(NamedInstrProfRecord &Record)=0
Read a single record.
Provides ErrorOr<T> smart pointer.
LLVM Value Representation.
Definition: Value.h:73
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
std::string Hash(const Unit &U)
Definition: FuzzerSHA1.cpp:216
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Reader for the indexed binary instrprof format.
std::vector< ProfileSummaryEntry > SummaryEntryVector
const uint64_t Version
Definition: InstrProf.h:864
void Clear()
Clear value data entries and edge counters.
Definition: InstrProf.h:670
#define D
Definition: LargeTest.cpp:26
reference get()
Definition: ErrorOr.h:169
Error success()
Clear the current error and return a successful one.
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
static Error initializeReader(InstrProfReader &Reader)