1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
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 implements the class that reads LLVM sample profiles. It
11 // supports three file formats: text, binary and gcov.
13 // The textual representation is useful for debugging and testing purposes. The
14 // binary representation is more compact, resulting in smaller file sizes.
16 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17 // tool (https://github.com/google/autofdo)
19 // All three encodings can be used interchangeably as an input sample profile.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ProfileData/SampleProfReader.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorOr.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/LineIterator.h"
30 #include "llvm/Support/MemoryBuffer.h"
32 using namespace llvm::sampleprof;
35 /// \brief Print the samples collected for a function on stream \p OS.
37 /// \param OS Stream to emit the output to.
38 void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
39 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
40 << " sampled lines\n";
41 for (const auto &SI : BodySamples) {
42 LineLocation Loc = SI.first;
43 const SampleRecord &Sample = SI.second;
45 OS << "line offset: " << Loc.LineOffset
46 << ", discriminator: " << Loc.Discriminator
47 << ", number of samples: " << Sample.getSamples();
48 if (Sample.hasCalls()) {
50 for (const auto &I : Sample.getCallTargets())
51 OS << " " << I.first() << ":" << I.second;
55 for (const auto &CS : CallsiteSamples) {
56 CallsiteLocation Loc = CS.first;
57 const FunctionSamples &CalleeSamples = CS.second;
59 OS << "line offset: " << Loc.LineOffset
60 << ", discriminator: " << Loc.Discriminator
61 << ", inlined callee: " << Loc.CalleeName << ": ";
62 CalleeSamples.print(OS, Indent + 2);
66 /// \brief Dump the function profile for \p FName.
68 /// \param FName Name of the function to print.
69 /// \param OS Stream to emit the output to.
70 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
72 OS << "Function: " << FName << ": ";
73 Profiles[FName].print(OS);
76 /// \brief Dump all the function profiles found on stream \p OS.
77 void SampleProfileReader::dump(raw_ostream &OS) {
78 for (const auto &I : Profiles)
79 dumpFunctionProfile(I.getKey(), OS);
82 /// \brief Parse \p Input as function head.
84 /// Parse one line of \p Input, and update function name in \p FName,
85 /// function's total sample count in \p NumSamples, function's entry
86 /// count in \p NumHeadSamples.
88 /// \returns true if parsing is successful.
89 static bool ParseHead(const StringRef &Input, StringRef &FName,
90 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
93 size_t n2 = Input.rfind(':');
94 size_t n1 = Input.rfind(':', n2 - 1);
95 FName = Input.substr(0, n1);
96 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
98 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
103 /// \brief Parse \p Input as line sample.
105 /// \param Input input line.
106 /// \param IsCallsite true if the line represents an inlined callsite.
107 /// \param Depth the depth of the inline stack.
108 /// \param NumSamples total samples of the line/inlined callsite.
109 /// \param LineOffset line offset to the start of the function.
110 /// \param Discriminator discriminator of the line.
111 /// \param TargetCountMap map from indirect call target to count.
113 /// returns true if parsing is successful.
114 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
115 uint64_t &NumSamples, uint32_t &LineOffset,
116 uint32_t &Discriminator, StringRef &CalleeName,
117 DenseMap<StringRef, uint64_t> &TargetCountMap) {
118 for (Depth = 0; Input[Depth] == ' '; Depth++)
123 size_t n1 = Input.find(':');
124 StringRef Loc = Input.substr(Depth, n1 - Depth);
125 size_t n2 = Loc.find('.');
126 if (n2 == StringRef::npos) {
127 if (Loc.getAsInteger(10, LineOffset))
131 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
133 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
137 StringRef Rest = Input.substr(n1 + 2);
138 if (Rest[0] >= '0' && Rest[0] <= '9') {
140 size_t n3 = Rest.find(' ');
141 if (n3 == StringRef::npos) {
142 if (Rest.getAsInteger(10, NumSamples))
145 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
148 while (n3 != StringRef::npos) {
149 n3 += Rest.substr(n3).find_first_not_of(' ');
150 Rest = Rest.substr(n3);
152 StringRef pair = Rest;
153 if (n3 != StringRef::npos) {
154 pair = Rest.substr(0, n3);
156 size_t n4 = pair.find(':');
158 if (pair.substr(n4 + 1).getAsInteger(10, count))
160 TargetCountMap[pair.substr(0, n4)] = count;
164 size_t n3 = Rest.find_last_of(':');
165 CalleeName = Rest.substr(0, n3);
166 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
172 /// \brief Load samples from a text file.
174 /// See the documentation at the top of the file for an explanation of
175 /// the expected format.
177 /// \returns true if the file was loaded successfully, false otherwise.
178 std::error_code SampleProfileReaderText::read() {
179 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
181 InlineCallStack InlineStack;
183 for (; !LineIt.is_at_eof(); ++LineIt) {
184 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
186 // Read the header of each function.
188 // Note that for function identifiers we are actually expecting
189 // mangled names, but we may not always get them. This happens when
190 // the compiler decides not to emit the function (e.g., it was inlined
191 // and removed). In this case, the binary will not have the linkage
192 // name for the function, so the profiler will emit the function's
193 // unmangled name, which may contain characters like ':' and '>' in its
194 // name (member functions, templates, etc).
196 // The only requirement we place on the identifier, then, is that it
197 // should not begin with a number.
198 if ((*LineIt)[0] != ' ') {
199 uint64_t NumSamples, NumHeadSamples;
201 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
202 reportError(LineIt.line_number(),
203 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
204 return sampleprof_error::malformed;
206 Profiles[FName] = FunctionSamples();
207 FunctionSamples &FProfile = Profiles[FName];
208 FProfile.addTotalSamples(NumSamples);
209 FProfile.addHeadSamples(NumHeadSamples);
211 InlineStack.push_back(&FProfile);
215 DenseMap<StringRef, uint64_t> TargetCountMap;
217 uint32_t Depth, LineOffset, Discriminator;
218 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
219 Discriminator, FName, TargetCountMap)) {
220 reportError(LineIt.line_number(),
221 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
223 return sampleprof_error::malformed;
226 while (InlineStack.size() > Depth) {
227 InlineStack.pop_back();
229 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
230 CallsiteLocation(LineOffset, Discriminator, FName));
231 FSamples.addTotalSamples(NumSamples);
232 InlineStack.push_back(&FSamples);
234 while (InlineStack.size() > Depth) {
235 InlineStack.pop_back();
237 FunctionSamples &FProfile = *InlineStack.back();
238 for (const auto &name_count : TargetCountMap) {
239 FProfile.addCalledTargetSamples(LineOffset, Discriminator,
240 name_count.first, name_count.second);
242 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
247 return sampleprof_error::success;
250 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
251 unsigned NumBytesRead = 0;
253 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
255 if (Val > std::numeric_limits<T>::max())
256 EC = sampleprof_error::malformed;
257 else if (Data + NumBytesRead > End)
258 EC = sampleprof_error::truncated;
260 EC = sampleprof_error::success;
263 reportError(0, EC.message());
267 Data += NumBytesRead;
268 return static_cast<T>(Val);
271 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
273 StringRef Str(reinterpret_cast<const char *>(Data));
274 if (Data + Str.size() + 1 > End) {
275 EC = sampleprof_error::truncated;
276 reportError(0, EC.message());
280 Data += Str.size() + 1;
284 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
286 auto Idx = readNumber<uint32_t>();
287 if (std::error_code EC = Idx.getError())
289 if (*Idx >= NameTable.size())
290 return sampleprof_error::truncated_name_table;
291 return NameTable[*Idx];
295 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
296 auto NumSamples = readNumber<uint64_t>();
297 if (std::error_code EC = NumSamples.getError())
299 FProfile.addTotalSamples(*NumSamples);
301 // Read the samples in the body.
302 auto NumRecords = readNumber<uint32_t>();
303 if (std::error_code EC = NumRecords.getError())
306 for (uint32_t I = 0; I < *NumRecords; ++I) {
307 auto LineOffset = readNumber<uint64_t>();
308 if (std::error_code EC = LineOffset.getError())
311 auto Discriminator = readNumber<uint64_t>();
312 if (std::error_code EC = Discriminator.getError())
315 auto NumSamples = readNumber<uint64_t>();
316 if (std::error_code EC = NumSamples.getError())
319 auto NumCalls = readNumber<uint32_t>();
320 if (std::error_code EC = NumCalls.getError())
323 for (uint32_t J = 0; J < *NumCalls; ++J) {
324 auto CalledFunction(readStringFromTable());
325 if (std::error_code EC = CalledFunction.getError())
328 auto CalledFunctionSamples = readNumber<uint64_t>();
329 if (std::error_code EC = CalledFunctionSamples.getError())
332 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
333 *CalledFunction, *CalledFunctionSamples);
336 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
339 // Read all the samples for inlined function calls.
340 auto NumCallsites = readNumber<uint32_t>();
341 if (std::error_code EC = NumCallsites.getError())
344 for (uint32_t J = 0; J < *NumCallsites; ++J) {
345 auto LineOffset = readNumber<uint64_t>();
346 if (std::error_code EC = LineOffset.getError())
349 auto Discriminator = readNumber<uint64_t>();
350 if (std::error_code EC = Discriminator.getError())
353 auto FName(readStringFromTable());
354 if (std::error_code EC = FName.getError())
357 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
358 CallsiteLocation(*LineOffset, *Discriminator, *FName));
359 if (std::error_code EC = readProfile(CalleeProfile))
363 return sampleprof_error::success;
366 std::error_code SampleProfileReaderBinary::read() {
368 auto NumHeadSamples = readNumber<uint64_t>();
369 if (std::error_code EC = NumHeadSamples.getError())
372 auto FName(readStringFromTable());
373 if (std::error_code EC = FName.getError())
376 Profiles[*FName] = FunctionSamples();
377 FunctionSamples &FProfile = Profiles[*FName];
379 FProfile.addHeadSamples(*NumHeadSamples);
381 if (std::error_code EC = readProfile(FProfile))
385 return sampleprof_error::success;
388 std::error_code SampleProfileReaderBinary::readHeader() {
389 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
390 End = Data + Buffer->getBufferSize();
392 // Read and check the magic identifier.
393 auto Magic = readNumber<uint64_t>();
394 if (std::error_code EC = Magic.getError())
396 else if (*Magic != SPMagic())
397 return sampleprof_error::bad_magic;
399 // Read the version number.
400 auto Version = readNumber<uint64_t>();
401 if (std::error_code EC = Version.getError())
403 else if (*Version != SPVersion())
404 return sampleprof_error::unsupported_version;
406 // Read the name table.
407 auto Size = readNumber<uint32_t>();
408 if (std::error_code EC = Size.getError())
410 NameTable.reserve(*Size);
411 for (uint32_t I = 0; I < *Size; ++I) {
412 auto Name(readString());
413 if (std::error_code EC = Name.getError())
415 NameTable.push_back(*Name);
418 return sampleprof_error::success;
421 bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
422 const uint8_t *Data =
423 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
424 uint64_t Magic = decodeULEB128(Data);
425 return Magic == SPMagic();
428 std::error_code SampleProfileReaderGCC::skipNextWord() {
430 if (!GcovBuffer.readInt(dummy))
431 return sampleprof_error::truncated;
432 return sampleprof_error::success;
435 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
436 if (sizeof(T) <= sizeof(uint32_t)) {
438 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
439 return static_cast<T>(Val);
440 } else if (sizeof(T) <= sizeof(uint64_t)) {
442 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
443 return static_cast<T>(Val);
446 std::error_code EC = sampleprof_error::malformed;
447 reportError(0, EC.message());
451 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
453 if (!GcovBuffer.readString(Str))
454 return sampleprof_error::truncated;
458 std::error_code SampleProfileReaderGCC::readHeader() {
459 // Read the magic identifier.
460 if (!GcovBuffer.readGCDAFormat())
461 return sampleprof_error::unrecognized_format;
463 // Read the version number. Note - the GCC reader does not validate this
464 // version, but the profile creator generates v704.
465 GCOV::GCOVVersion version;
466 if (!GcovBuffer.readGCOVVersion(version))
467 return sampleprof_error::unrecognized_format;
469 if (version != GCOV::V704)
470 return sampleprof_error::unsupported_version;
472 // Skip the empty integer.
473 if (std::error_code EC = skipNextWord())
476 return sampleprof_error::success;
479 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
481 if (!GcovBuffer.readInt(Tag))
482 return sampleprof_error::truncated;
485 return sampleprof_error::malformed;
487 if (std::error_code EC = skipNextWord())
490 return sampleprof_error::success;
493 std::error_code SampleProfileReaderGCC::readNameTable() {
494 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
498 if (!GcovBuffer.readInt(Size))
499 return sampleprof_error::truncated;
501 for (uint32_t I = 0; I < Size; ++I) {
503 if (!GcovBuffer.readString(Str))
504 return sampleprof_error::truncated;
505 Names.push_back(Str);
508 return sampleprof_error::success;
511 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
512 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
515 uint32_t NumFunctions;
516 if (!GcovBuffer.readInt(NumFunctions))
517 return sampleprof_error::truncated;
519 InlineCallStack Stack;
520 for (uint32_t I = 0; I < NumFunctions; ++I)
521 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
524 return sampleprof_error::success;
527 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
528 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
529 uint64_t HeadCount = 0;
530 if (InlineStack.size() == 0)
531 if (!GcovBuffer.readInt64(HeadCount))
532 return sampleprof_error::truncated;
535 if (!GcovBuffer.readInt(NameIdx))
536 return sampleprof_error::truncated;
538 StringRef Name(Names[NameIdx]);
540 uint32_t NumPosCounts;
541 if (!GcovBuffer.readInt(NumPosCounts))
542 return sampleprof_error::truncated;
544 uint32_t NumCallsites;
545 if (!GcovBuffer.readInt(NumCallsites))
546 return sampleprof_error::truncated;
548 FunctionSamples *FProfile = nullptr;
549 if (InlineStack.size() == 0) {
550 // If this is a top function that we have already processed, do not
551 // update its profile again. This happens in the presence of
552 // function aliases. Since these aliases share the same function
553 // body, there will be identical replicated profiles for the
554 // original function. In this case, we simply not bother updating
555 // the profile of the original function.
556 FProfile = &Profiles[Name];
557 FProfile->addHeadSamples(HeadCount);
558 if (FProfile->getTotalSamples() > 0)
561 // Otherwise, we are reading an inlined instance. The top of the
562 // inline stack contains the profile of the caller. Insert this
563 // callee in the caller's CallsiteMap.
564 FunctionSamples *CallerProfile = InlineStack.front();
565 uint32_t LineOffset = Offset >> 16;
566 uint32_t Discriminator = Offset & 0xffff;
567 FProfile = &CallerProfile->functionSamplesAt(
568 CallsiteLocation(LineOffset, Discriminator, Name));
571 for (uint32_t I = 0; I < NumPosCounts; ++I) {
573 if (!GcovBuffer.readInt(Offset))
574 return sampleprof_error::truncated;
577 if (!GcovBuffer.readInt(NumTargets))
578 return sampleprof_error::truncated;
581 if (!GcovBuffer.readInt64(Count))
582 return sampleprof_error::truncated;
584 // The line location is encoded in the offset as:
585 // high 16 bits: line offset to the start of the function.
586 // low 16 bits: discriminator.
587 uint32_t LineOffset = Offset >> 16;
588 uint32_t Discriminator = Offset & 0xffff;
590 InlineCallStack NewStack;
591 NewStack.push_back(FProfile);
592 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
594 // Walk up the inline stack, adding the samples on this line to
595 // the total sample count of the callers in the chain.
596 for (auto CallerProfile : NewStack)
597 CallerProfile->addTotalSamples(Count);
599 // Update the body samples for the current profile.
600 FProfile->addBodySamples(LineOffset, Discriminator, Count);
603 // Process the list of functions called at an indirect call site.
604 // These are all the targets that a function pointer (or virtual
605 // function) resolved at runtime.
606 for (uint32_t J = 0; J < NumTargets; J++) {
608 if (!GcovBuffer.readInt(HistVal))
609 return sampleprof_error::truncated;
611 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
612 return sampleprof_error::malformed;
615 if (!GcovBuffer.readInt64(TargetIdx))
616 return sampleprof_error::truncated;
617 StringRef TargetName(Names[TargetIdx]);
619 uint64_t TargetCount;
620 if (!GcovBuffer.readInt64(TargetCount))
621 return sampleprof_error::truncated;
624 FunctionSamples &TargetProfile = Profiles[TargetName];
625 TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
626 TargetName, TargetCount);
631 // Process all the inlined callers into the current function. These
632 // are all the callsites that were inlined into this function.
633 for (uint32_t I = 0; I < NumCallsites; I++) {
634 // The offset is encoded as:
635 // high 16 bits: line offset to the start of the function.
636 // low 16 bits: discriminator.
638 if (!GcovBuffer.readInt(Offset))
639 return sampleprof_error::truncated;
640 InlineCallStack NewStack;
641 NewStack.push_back(FProfile);
642 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
643 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
647 return sampleprof_error::success;
650 /// \brief Read a GCC AutoFDO profile.
652 /// This format is generated by the Linux Perf conversion tool at
653 /// https://github.com/google/autofdo.
654 std::error_code SampleProfileReaderGCC::read() {
655 // Read the string table.
656 if (std::error_code EC = readNameTable())
659 // Read the source profile.
660 if (std::error_code EC = readFunctionProfiles())
663 return sampleprof_error::success;
666 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
667 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
668 return Magic == "adcg*704";
671 /// \brief Prepare a memory buffer for the contents of \p Filename.
673 /// \returns an error code indicating the status of the buffer.
674 static ErrorOr<std::unique_ptr<MemoryBuffer>>
675 setupMemoryBuffer(std::string Filename) {
676 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
677 if (std::error_code EC = BufferOrErr.getError())
679 auto Buffer = std::move(BufferOrErr.get());
681 // Sanity check the file.
682 if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
683 return sampleprof_error::too_large;
685 return std::move(Buffer);
688 /// \brief Create a sample profile reader based on the format of the input file.
690 /// \param Filename The file to open.
692 /// \param Reader The reader to instantiate according to \p Filename's format.
694 /// \param C The LLVM context to use to emit diagnostics.
696 /// \returns an error code indicating the status of the created reader.
697 ErrorOr<std::unique_ptr<SampleProfileReader>>
698 SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
699 auto BufferOrError = setupMemoryBuffer(Filename);
700 if (std::error_code EC = BufferOrError.getError())
703 auto Buffer = std::move(BufferOrError.get());
704 std::unique_ptr<SampleProfileReader> Reader;
705 if (SampleProfileReaderBinary::hasFormat(*Buffer))
706 Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
707 else if (SampleProfileReaderGCC::hasFormat(*Buffer))
708 Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
710 Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
712 if (std::error_code EC = Reader->readHeader())
715 return std::move(Reader);