1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
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 implements the class that reads LLVM sample profiles. It
11 // supports three file formats: text, binary and gcov.
12 //
13 // The textual representation is useful for debugging and testing purposes. The
14 // binary representation is more compact, resulting in smaller file sizes.
15 //
16 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17 // tool (https://github.com/google/autofdo)
18 //
19 // All three encodings can be used interchangeably as an input sample profile.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/ProfileData/SampleProfReader.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorOr.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/LineIterator.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 
33 using namespace llvm::sampleprof;
34 using namespace llvm;
35 
36 /// \brief Dump the function profile for \p FName.
37 ///
38 /// \param FName Name of the function to print.
39 /// \param OS Stream to emit the output to.
40 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
41                                               raw_ostream &OS) {
42   OS << "Function: " << FName << ": " << Profiles[FName];
43 }
44 
45 /// \brief Dump all the function profiles found on stream \p OS.
46 void SampleProfileReader::dump(raw_ostream &OS) {
47   for (const auto &I : Profiles)
48     dumpFunctionProfile(I.getKey(), OS);
49 }
50 
51 /// \brief Parse \p Input as function head.
52 ///
53 /// Parse one line of \p Input, and update function name in \p FName,
54 /// function's total sample count in \p NumSamples, function's entry
55 /// count in \p NumHeadSamples.
56 ///
57 /// \returns true if parsing is successful.
58 static bool ParseHead(const StringRef &Input, StringRef &FName,
59                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
60   if (Input[0] == ' ')
61     return false;
62   size_t n2 = Input.rfind(':');
63   size_t n1 = Input.rfind(':', n2 - 1);
64   FName = Input.substr(0, n1);
65   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
66     return false;
67   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
68     return false;
69   return true;
70 }
71 
72 
73 /// \brief Returns true if line offset \p L is legal (only has 16 bits).
74 static bool isOffsetLegal(unsigned L) {
75   return (L & 0xffff) == L;
76 }
77 
78 /// \brief Parse \p Input as line sample.
79 ///
80 /// \param Input input line.
81 /// \param IsCallsite true if the line represents an inlined callsite.
82 /// \param Depth the depth of the inline stack.
83 /// \param NumSamples total samples of the line/inlined callsite.
84 /// \param LineOffset line offset to the start of the function.
85 /// \param Discriminator discriminator of the line.
86 /// \param TargetCountMap map from indirect call target to count.
87 ///
88 /// returns true if parsing is successful.
89 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
90                       uint64_t &NumSamples, uint32_t &LineOffset,
91                       uint32_t &Discriminator, StringRef &CalleeName,
92                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
93   for (Depth = 0; Input[Depth] == ' '; Depth++)
94     ;
95   if (Depth == 0)
96     return false;
97 
98   size_t n1 = Input.find(':');
99   StringRef Loc = Input.substr(Depth, n1 - Depth);
100   size_t n2 = Loc.find('.');
101   if (n2 == StringRef::npos) {
102     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
103       return false;
104     Discriminator = 0;
105   } else {
106     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
107       return false;
108     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
109       return false;
110   }
111 
112   StringRef Rest = Input.substr(n1 + 2);
113   if (Rest[0] >= '0' && Rest[0] <= '9') {
114     IsCallsite = false;
115     size_t n3 = Rest.find(' ');
116     if (n3 == StringRef::npos) {
117       if (Rest.getAsInteger(10, NumSamples))
118         return false;
119     } else {
120       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
121         return false;
122     }
123     while (n3 != StringRef::npos) {
124       n3 += Rest.substr(n3).find_first_not_of(' ');
125       Rest = Rest.substr(n3);
126       n3 = Rest.find(' ');
127       StringRef pair = Rest;
128       if (n3 != StringRef::npos) {
129         pair = Rest.substr(0, n3);
130       }
131       size_t n4 = pair.find(':');
132       uint64_t count;
133       if (pair.substr(n4 + 1).getAsInteger(10, count))
134         return false;
135       TargetCountMap[pair.substr(0, n4)] = count;
136     }
137   } else {
138     IsCallsite = true;
139     size_t n3 = Rest.find_last_of(':');
140     CalleeName = Rest.substr(0, n3);
141     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
142       return false;
143   }
144   return true;
145 }
146 
147 /// \brief Load samples from a text file.
148 ///
149 /// See the documentation at the top of the file for an explanation of
150 /// the expected format.
151 ///
152 /// \returns true if the file was loaded successfully, false otherwise.
153 std::error_code SampleProfileReaderText::read() {
154   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
155   sampleprof_error Result = sampleprof_error::success;
156 
157   InlineCallStack InlineStack;
158 
159   for (; !LineIt.is_at_eof(); ++LineIt) {
160     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
161       continue;
162     // Read the header of each function.
163     //
164     // Note that for function identifiers we are actually expecting
165     // mangled names, but we may not always get them. This happens when
166     // the compiler decides not to emit the function (e.g., it was inlined
167     // and removed). In this case, the binary will not have the linkage
168     // name for the function, so the profiler will emit the function's
169     // unmangled name, which may contain characters like ':' and '>' in its
170     // name (member functions, templates, etc).
171     //
172     // The only requirement we place on the identifier, then, is that it
173     // should not begin with a number.
174     if ((*LineIt)[0] != ' ') {
175       uint64_t NumSamples, NumHeadSamples;
176       StringRef FName;
177       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
178         reportError(LineIt.line_number(),
179                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
180         return sampleprof_error::malformed;
181       }
182       Profiles[FName] = FunctionSamples();
183       FunctionSamples &FProfile = Profiles[FName];
184       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
185       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
186       InlineStack.clear();
187       InlineStack.push_back(&FProfile);
188     } else {
189       uint64_t NumSamples;
190       StringRef FName;
191       DenseMap<StringRef, uint64_t> TargetCountMap;
192       bool IsCallsite;
193       uint32_t Depth, LineOffset, Discriminator;
194       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
195                      Discriminator, FName, TargetCountMap)) {
196         reportError(LineIt.line_number(),
197                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
198                         *LineIt);
199         return sampleprof_error::malformed;
200       }
201       if (IsCallsite) {
202         while (InlineStack.size() > Depth) {
203           InlineStack.pop_back();
204         }
205         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
206             CallsiteLocation(LineOffset, Discriminator, FName));
207         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
208         InlineStack.push_back(&FSamples);
209       } else {
210         while (InlineStack.size() > Depth) {
211           InlineStack.pop_back();
212         }
213         FunctionSamples &FProfile = *InlineStack.back();
214         for (const auto &name_count : TargetCountMap) {
215           MergeResult(Result, FProfile.addCalledTargetSamples(
216                                   LineOffset, Discriminator, name_count.first,
217                                   name_count.second));
218         }
219         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
220                                                     NumSamples));
221       }
222     }
223   }
224   if (Result == sampleprof_error::success)
225     computeSummary();
226 
227   return Result;
228 }
229 
230 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
231   bool result = false;
232 
233   // Check that the first non-comment line is a valid function header.
234   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
235   if (!LineIt.is_at_eof()) {
236     if ((*LineIt)[0] != ' ') {
237       uint64_t NumSamples, NumHeadSamples;
238       StringRef FName;
239       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
240     }
241   }
242 
243   return result;
244 }
245 
246 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
247   unsigned NumBytesRead = 0;
248   std::error_code EC;
249   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
250 
251   if (Val > std::numeric_limits<T>::max())
252     EC = sampleprof_error::malformed;
253   else if (Data + NumBytesRead > End)
254     EC = sampleprof_error::truncated;
255   else
256     EC = sampleprof_error::success;
257 
258   if (EC) {
259     reportError(0, EC.message());
260     return EC;
261   }
262 
263   Data += NumBytesRead;
264   return static_cast<T>(Val);
265 }
266 
267 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
268   std::error_code EC;
269   StringRef Str(reinterpret_cast<const char *>(Data));
270   if (Data + Str.size() + 1 > End) {
271     EC = sampleprof_error::truncated;
272     reportError(0, EC.message());
273     return EC;
274   }
275 
276   Data += Str.size() + 1;
277   return Str;
278 }
279 
280 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
281   std::error_code EC;
282   auto Idx = readNumber<uint32_t>();
283   if (std::error_code EC = Idx.getError())
284     return EC;
285   if (*Idx >= NameTable.size())
286     return sampleprof_error::truncated_name_table;
287   return NameTable[*Idx];
288 }
289 
290 std::error_code
291 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
292   auto NumSamples = readNumber<uint64_t>();
293   if (std::error_code EC = NumSamples.getError())
294     return EC;
295   FProfile.addTotalSamples(*NumSamples);
296 
297   // Read the samples in the body.
298   auto NumRecords = readNumber<uint32_t>();
299   if (std::error_code EC = NumRecords.getError())
300     return EC;
301 
302   for (uint32_t I = 0; I < *NumRecords; ++I) {
303     auto LineOffset = readNumber<uint64_t>();
304     if (std::error_code EC = LineOffset.getError())
305       return EC;
306 
307     if (!isOffsetLegal(*LineOffset)) {
308       return std::error_code();
309     }
310 
311     auto Discriminator = readNumber<uint64_t>();
312     if (std::error_code EC = Discriminator.getError())
313       return EC;
314 
315     auto NumSamples = readNumber<uint64_t>();
316     if (std::error_code EC = NumSamples.getError())
317       return EC;
318 
319     auto NumCalls = readNumber<uint32_t>();
320     if (std::error_code EC = NumCalls.getError())
321       return EC;
322 
323     for (uint32_t J = 0; J < *NumCalls; ++J) {
324       auto CalledFunction(readStringFromTable());
325       if (std::error_code EC = CalledFunction.getError())
326         return EC;
327 
328       auto CalledFunctionSamples = readNumber<uint64_t>();
329       if (std::error_code EC = CalledFunctionSamples.getError())
330         return EC;
331 
332       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
333                                       *CalledFunction, *CalledFunctionSamples);
334     }
335 
336     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
337   }
338 
339   // Read all the samples for inlined function calls.
340   auto NumCallsites = readNumber<uint32_t>();
341   if (std::error_code EC = NumCallsites.getError())
342     return EC;
343 
344   for (uint32_t J = 0; J < *NumCallsites; ++J) {
345     auto LineOffset = readNumber<uint64_t>();
346     if (std::error_code EC = LineOffset.getError())
347       return EC;
348 
349     auto Discriminator = readNumber<uint64_t>();
350     if (std::error_code EC = Discriminator.getError())
351       return EC;
352 
353     auto FName(readStringFromTable());
354     if (std::error_code EC = FName.getError())
355       return EC;
356 
357     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
358         CallsiteLocation(*LineOffset, *Discriminator, *FName));
359     if (std::error_code EC = readProfile(CalleeProfile))
360       return EC;
361   }
362 
363   return sampleprof_error::success;
364 }
365 
366 std::error_code SampleProfileReaderBinary::read() {
367   while (!at_eof()) {
368     auto NumHeadSamples = readNumber<uint64_t>();
369     if (std::error_code EC = NumHeadSamples.getError())
370       return EC;
371 
372     auto FName(readStringFromTable());
373     if (std::error_code EC = FName.getError())
374       return EC;
375 
376     Profiles[*FName] = FunctionSamples();
377     FunctionSamples &FProfile = Profiles[*FName];
378 
379     FProfile.addHeadSamples(*NumHeadSamples);
380 
381     if (std::error_code EC = readProfile(FProfile))
382       return EC;
383   }
384 
385   return sampleprof_error::success;
386 }
387 
388 std::error_code SampleProfileReaderBinary::readHeader() {
389   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
390   End = Data + Buffer->getBufferSize();
391 
392   // Read and check the magic identifier.
393   auto Magic = readNumber<uint64_t>();
394   if (std::error_code EC = Magic.getError())
395     return EC;
396   else if (*Magic != SPMagic())
397     return sampleprof_error::bad_magic;
398 
399   // Read the version number.
400   auto Version = readNumber<uint64_t>();
401   if (std::error_code EC = Version.getError())
402     return EC;
403   else if (*Version != SPVersion())
404     return sampleprof_error::unsupported_version;
405 
406   if (std::error_code EC = readSummary())
407     return EC;
408 
409   // Read the name table.
410   auto Size = readNumber<uint32_t>();
411   if (std::error_code EC = Size.getError())
412     return EC;
413   NameTable.reserve(*Size);
414   for (uint32_t I = 0; I < *Size; ++I) {
415     auto Name(readString());
416     if (std::error_code EC = Name.getError())
417       return EC;
418     NameTable.push_back(*Name);
419   }
420 
421   return sampleprof_error::success;
422 }
423 
424 std::error_code SampleProfileReaderBinary::readSummaryEntry(
425     std::vector<ProfileSummaryEntry> &Entries) {
426   auto Cutoff = readNumber<uint64_t>();
427   if (std::error_code EC = Cutoff.getError())
428     return EC;
429 
430   auto MinBlockCount = readNumber<uint64_t>();
431   if (std::error_code EC = MinBlockCount.getError())
432     return EC;
433 
434   auto NumBlocks = readNumber<uint64_t>();
435   if (std::error_code EC = NumBlocks.getError())
436     return EC;
437 
438   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
439   return sampleprof_error::success;
440 }
441 
442 std::error_code SampleProfileReaderBinary::readSummary() {
443   auto TotalCount = readNumber<uint64_t>();
444   if (std::error_code EC = TotalCount.getError())
445     return EC;
446 
447   auto MaxBlockCount = readNumber<uint64_t>();
448   if (std::error_code EC = MaxBlockCount.getError())
449     return EC;
450 
451   auto MaxFunctionCount = readNumber<uint64_t>();
452   if (std::error_code EC = MaxFunctionCount.getError())
453     return EC;
454 
455   auto NumBlocks = readNumber<uint64_t>();
456   if (std::error_code EC = NumBlocks.getError())
457     return EC;
458 
459   auto NumFunctions = readNumber<uint64_t>();
460   if (std::error_code EC = NumFunctions.getError())
461     return EC;
462 
463   auto NumSummaryEntries = readNumber<uint64_t>();
464   if (std::error_code EC = NumSummaryEntries.getError())
465     return EC;
466 
467   std::vector<ProfileSummaryEntry> Entries;
468   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
469     std::error_code EC = readSummaryEntry(Entries);
470     if (EC != sampleprof_error::success)
471       return EC;
472   }
473   Summary = llvm::make_unique<SampleProfileSummary>(
474       *TotalCount, *MaxBlockCount, *MaxFunctionCount, *NumBlocks, *NumFunctions,
475       Entries);
476 
477   return sampleprof_error::success;
478 }
479 
480 bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
481   const uint8_t *Data =
482       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
483   uint64_t Magic = decodeULEB128(Data);
484   return Magic == SPMagic();
485 }
486 
487 std::error_code SampleProfileReaderGCC::skipNextWord() {
488   uint32_t dummy;
489   if (!GcovBuffer.readInt(dummy))
490     return sampleprof_error::truncated;
491   return sampleprof_error::success;
492 }
493 
494 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
495   if (sizeof(T) <= sizeof(uint32_t)) {
496     uint32_t Val;
497     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
498       return static_cast<T>(Val);
499   } else if (sizeof(T) <= sizeof(uint64_t)) {
500     uint64_t Val;
501     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
502       return static_cast<T>(Val);
503   }
504 
505   std::error_code EC = sampleprof_error::malformed;
506   reportError(0, EC.message());
507   return EC;
508 }
509 
510 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
511   StringRef Str;
512   if (!GcovBuffer.readString(Str))
513     return sampleprof_error::truncated;
514   return Str;
515 }
516 
517 std::error_code SampleProfileReaderGCC::readHeader() {
518   // Read the magic identifier.
519   if (!GcovBuffer.readGCDAFormat())
520     return sampleprof_error::unrecognized_format;
521 
522   // Read the version number. Note - the GCC reader does not validate this
523   // version, but the profile creator generates v704.
524   GCOV::GCOVVersion version;
525   if (!GcovBuffer.readGCOVVersion(version))
526     return sampleprof_error::unrecognized_format;
527 
528   if (version != GCOV::V704)
529     return sampleprof_error::unsupported_version;
530 
531   // Skip the empty integer.
532   if (std::error_code EC = skipNextWord())
533     return EC;
534 
535   return sampleprof_error::success;
536 }
537 
538 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
539   uint32_t Tag;
540   if (!GcovBuffer.readInt(Tag))
541     return sampleprof_error::truncated;
542 
543   if (Tag != Expected)
544     return sampleprof_error::malformed;
545 
546   if (std::error_code EC = skipNextWord())
547     return EC;
548 
549   return sampleprof_error::success;
550 }
551 
552 std::error_code SampleProfileReaderGCC::readNameTable() {
553   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
554     return EC;
555 
556   uint32_t Size;
557   if (!GcovBuffer.readInt(Size))
558     return sampleprof_error::truncated;
559 
560   for (uint32_t I = 0; I < Size; ++I) {
561     StringRef Str;
562     if (!GcovBuffer.readString(Str))
563       return sampleprof_error::truncated;
564     Names.push_back(Str);
565   }
566 
567   return sampleprof_error::success;
568 }
569 
570 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
571   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
572     return EC;
573 
574   uint32_t NumFunctions;
575   if (!GcovBuffer.readInt(NumFunctions))
576     return sampleprof_error::truncated;
577 
578   InlineCallStack Stack;
579   for (uint32_t I = 0; I < NumFunctions; ++I)
580     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
581       return EC;
582 
583   computeSummary();
584   return sampleprof_error::success;
585 }
586 
587 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
588     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
589   uint64_t HeadCount = 0;
590   if (InlineStack.size() == 0)
591     if (!GcovBuffer.readInt64(HeadCount))
592       return sampleprof_error::truncated;
593 
594   uint32_t NameIdx;
595   if (!GcovBuffer.readInt(NameIdx))
596     return sampleprof_error::truncated;
597 
598   StringRef Name(Names[NameIdx]);
599 
600   uint32_t NumPosCounts;
601   if (!GcovBuffer.readInt(NumPosCounts))
602     return sampleprof_error::truncated;
603 
604   uint32_t NumCallsites;
605   if (!GcovBuffer.readInt(NumCallsites))
606     return sampleprof_error::truncated;
607 
608   FunctionSamples *FProfile = nullptr;
609   if (InlineStack.size() == 0) {
610     // If this is a top function that we have already processed, do not
611     // update its profile again.  This happens in the presence of
612     // function aliases.  Since these aliases share the same function
613     // body, there will be identical replicated profiles for the
614     // original function.  In this case, we simply not bother updating
615     // the profile of the original function.
616     FProfile = &Profiles[Name];
617     FProfile->addHeadSamples(HeadCount);
618     if (FProfile->getTotalSamples() > 0)
619       Update = false;
620   } else {
621     // Otherwise, we are reading an inlined instance. The top of the
622     // inline stack contains the profile of the caller. Insert this
623     // callee in the caller's CallsiteMap.
624     FunctionSamples *CallerProfile = InlineStack.front();
625     uint32_t LineOffset = Offset >> 16;
626     uint32_t Discriminator = Offset & 0xffff;
627     FProfile = &CallerProfile->functionSamplesAt(
628         CallsiteLocation(LineOffset, Discriminator, Name));
629   }
630 
631   for (uint32_t I = 0; I < NumPosCounts; ++I) {
632     uint32_t Offset;
633     if (!GcovBuffer.readInt(Offset))
634       return sampleprof_error::truncated;
635 
636     uint32_t NumTargets;
637     if (!GcovBuffer.readInt(NumTargets))
638       return sampleprof_error::truncated;
639 
640     uint64_t Count;
641     if (!GcovBuffer.readInt64(Count))
642       return sampleprof_error::truncated;
643 
644     // The line location is encoded in the offset as:
645     //   high 16 bits: line offset to the start of the function.
646     //   low 16 bits: discriminator.
647     uint32_t LineOffset = Offset >> 16;
648     uint32_t Discriminator = Offset & 0xffff;
649 
650     InlineCallStack NewStack;
651     NewStack.push_back(FProfile);
652     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
653     if (Update) {
654       // Walk up the inline stack, adding the samples on this line to
655       // the total sample count of the callers in the chain.
656       for (auto CallerProfile : NewStack)
657         CallerProfile->addTotalSamples(Count);
658 
659       // Update the body samples for the current profile.
660       FProfile->addBodySamples(LineOffset, Discriminator, Count);
661     }
662 
663     // Process the list of functions called at an indirect call site.
664     // These are all the targets that a function pointer (or virtual
665     // function) resolved at runtime.
666     for (uint32_t J = 0; J < NumTargets; J++) {
667       uint32_t HistVal;
668       if (!GcovBuffer.readInt(HistVal))
669         return sampleprof_error::truncated;
670 
671       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
672         return sampleprof_error::malformed;
673 
674       uint64_t TargetIdx;
675       if (!GcovBuffer.readInt64(TargetIdx))
676         return sampleprof_error::truncated;
677       StringRef TargetName(Names[TargetIdx]);
678 
679       uint64_t TargetCount;
680       if (!GcovBuffer.readInt64(TargetCount))
681         return sampleprof_error::truncated;
682 
683       if (Update) {
684         FunctionSamples &TargetProfile = Profiles[TargetName];
685         TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
686                                              TargetName, TargetCount);
687       }
688     }
689   }
690 
691   // Process all the inlined callers into the current function. These
692   // are all the callsites that were inlined into this function.
693   for (uint32_t I = 0; I < NumCallsites; I++) {
694     // The offset is encoded as:
695     //   high 16 bits: line offset to the start of the function.
696     //   low 16 bits: discriminator.
697     uint32_t Offset;
698     if (!GcovBuffer.readInt(Offset))
699       return sampleprof_error::truncated;
700     InlineCallStack NewStack;
701     NewStack.push_back(FProfile);
702     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
703     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
704       return EC;
705   }
706 
707   return sampleprof_error::success;
708 }
709 
710 /// \brief Read a GCC AutoFDO profile.
711 ///
712 /// This format is generated by the Linux Perf conversion tool at
713 /// https://github.com/google/autofdo.
714 std::error_code SampleProfileReaderGCC::read() {
715   // Read the string table.
716   if (std::error_code EC = readNameTable())
717     return EC;
718 
719   // Read the source profile.
720   if (std::error_code EC = readFunctionProfiles())
721     return EC;
722 
723   return sampleprof_error::success;
724 }
725 
726 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
727   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
728   return Magic == "adcg*704";
729 }
730 
731 /// \brief Prepare a memory buffer for the contents of \p Filename.
732 ///
733 /// \returns an error code indicating the status of the buffer.
734 static ErrorOr<std::unique_ptr<MemoryBuffer>>
735 setupMemoryBuffer(std::string Filename) {
736   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
737   if (std::error_code EC = BufferOrErr.getError())
738     return EC;
739   auto Buffer = std::move(BufferOrErr.get());
740 
741   // Sanity check the file.
742   if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
743     return sampleprof_error::too_large;
744 
745   return std::move(Buffer);
746 }
747 
748 /// \brief Create a sample profile reader based on the format of the input file.
749 ///
750 /// \param Filename The file to open.
751 ///
752 /// \param Reader The reader to instantiate according to \p Filename's format.
753 ///
754 /// \param C The LLVM context to use to emit diagnostics.
755 ///
756 /// \returns an error code indicating the status of the created reader.
757 ErrorOr<std::unique_ptr<SampleProfileReader>>
758 SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
759   auto BufferOrError = setupMemoryBuffer(Filename);
760   if (std::error_code EC = BufferOrError.getError())
761     return EC;
762   return create(BufferOrError.get(), C);
763 }
764 
765 /// \brief Create a sample profile reader based on the format of the input data.
766 ///
767 /// \param B The memory buffer to create the reader from (assumes ownership).
768 ///
769 /// \param Reader The reader to instantiate according to \p Filename's format.
770 ///
771 /// \param C The LLVM context to use to emit diagnostics.
772 ///
773 /// \returns an error code indicating the status of the created reader.
774 ErrorOr<std::unique_ptr<SampleProfileReader>>
775 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
776   std::unique_ptr<SampleProfileReader> Reader;
777   if (SampleProfileReaderBinary::hasFormat(*B))
778     Reader.reset(new SampleProfileReaderBinary(std::move(B), C));
779   else if (SampleProfileReaderGCC::hasFormat(*B))
780     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
781   else if (SampleProfileReaderText::hasFormat(*B))
782     Reader.reset(new SampleProfileReaderText(std::move(B), C));
783   else
784     return sampleprof_error::unrecognized_format;
785 
786   if (std::error_code EC = Reader->readHeader())
787     return EC;
788 
789   return std::move(Reader);
790 }
791 
792 // For text and GCC file formats, we compute the summary after reading the
793 // profile. Binary format has the profile summary in its header.
794 void SampleProfileReader::computeSummary() {
795   Summary.reset(new SampleProfileSummary(ProfileSummary::DefaultCutoffs));
796   for (const auto &I : Profiles) {
797     const FunctionSamples &Profile = I.second;
798     Summary->addRecord(Profile);
799   }
800   Summary->computeDetailedSummary();
801 }
802