1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that reads LLVM sample profiles. It
10 // supports three file formats: text, binary and gcov.
11 //
12 // The textual representation is useful for debugging and testing purposes. The
13 // binary representation is more compact, resulting in smaller file sizes.
14 //
15 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
16 // tool (https://github.com/google/autofdo)
17 //
18 // All three encodings can be used interchangeably as an input sample profile.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "llvm/ProfileData/SampleProfReader.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/IR/ProfileSummary.h"
27 #include "llvm/ProfileData/ProfileCommon.h"
28 #include "llvm/ProfileData/SampleProf.h"
29 #include "llvm/Support/Compression.h"
30 #include "llvm/Support/ErrorOr.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/LineIterator.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cstddef>
38 #include <cstdint>
39 #include <limits>
40 #include <memory>
41 #include <system_error>
42 #include <vector>
43 
44 using namespace llvm;
45 using namespace sampleprof;
46 
47 /// Dump the function profile for \p FName.
48 ///
49 /// \param FName Name of the function to print.
50 /// \param OS Stream to emit the output to.
51 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
52                                               raw_ostream &OS) {
53   OS << "Function: " << FName << ": " << Profiles[FName];
54 }
55 
56 /// Dump all the function profiles found on stream \p OS.
57 void SampleProfileReader::dump(raw_ostream &OS) {
58   for (const auto &I : Profiles)
59     dumpFunctionProfile(I.getKey(), OS);
60 }
61 
62 /// Parse \p Input as function head.
63 ///
64 /// Parse one line of \p Input, and update function name in \p FName,
65 /// function's total sample count in \p NumSamples, function's entry
66 /// count in \p NumHeadSamples.
67 ///
68 /// \returns true if parsing is successful.
69 static bool ParseHead(const StringRef &Input, StringRef &FName,
70                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
71   if (Input[0] == ' ')
72     return false;
73   size_t n2 = Input.rfind(':');
74   size_t n1 = Input.rfind(':', n2 - 1);
75   FName = Input.substr(0, n1);
76   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
77     return false;
78   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
79     return false;
80   return true;
81 }
82 
83 /// Returns true if line offset \p L is legal (only has 16 bits).
84 static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
85 
86 /// Parse \p Input as line sample.
87 ///
88 /// \param Input input line.
89 /// \param IsCallsite true if the line represents an inlined callsite.
90 /// \param Depth the depth of the inline stack.
91 /// \param NumSamples total samples of the line/inlined callsite.
92 /// \param LineOffset line offset to the start of the function.
93 /// \param Discriminator discriminator of the line.
94 /// \param TargetCountMap map from indirect call target to count.
95 ///
96 /// returns true if parsing is successful.
97 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
98                       uint64_t &NumSamples, uint32_t &LineOffset,
99                       uint32_t &Discriminator, StringRef &CalleeName,
100                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
101   for (Depth = 0; Input[Depth] == ' '; Depth++)
102     ;
103   if (Depth == 0)
104     return false;
105 
106   size_t n1 = Input.find(':');
107   StringRef Loc = Input.substr(Depth, n1 - Depth);
108   size_t n2 = Loc.find('.');
109   if (n2 == StringRef::npos) {
110     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
111       return false;
112     Discriminator = 0;
113   } else {
114     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
115       return false;
116     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
117       return false;
118   }
119 
120   StringRef Rest = Input.substr(n1 + 2);
121   if (Rest[0] >= '0' && Rest[0] <= '9') {
122     IsCallsite = false;
123     size_t n3 = Rest.find(' ');
124     if (n3 == StringRef::npos) {
125       if (Rest.getAsInteger(10, NumSamples))
126         return false;
127     } else {
128       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
129         return false;
130     }
131     // Find call targets and their sample counts.
132     // Note: In some cases, there are symbols in the profile which are not
133     // mangled. To accommodate such cases, use colon + integer pairs as the
134     // anchor points.
135     // An example:
136     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
137     // ":1000" and ":437" are used as anchor points so the string above will
138     // be interpreted as
139     // target: _M_construct<char *>
140     // count: 1000
141     // target: string_view<std::allocator<char> >
142     // count: 437
143     while (n3 != StringRef::npos) {
144       n3 += Rest.substr(n3).find_first_not_of(' ');
145       Rest = Rest.substr(n3);
146       n3 = Rest.find_first_of(':');
147       if (n3 == StringRef::npos || n3 == 0)
148         return false;
149 
150       StringRef Target;
151       uint64_t count, n4;
152       while (true) {
153         // Get the segment after the current colon.
154         StringRef AfterColon = Rest.substr(n3 + 1);
155         // Get the target symbol before the current colon.
156         Target = Rest.substr(0, n3);
157         // Check if the word after the current colon is an integer.
158         n4 = AfterColon.find_first_of(' ');
159         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
160         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
161         if (!WordAfterColon.getAsInteger(10, count))
162           break;
163 
164         // Try to find the next colon.
165         uint64_t n5 = AfterColon.find_first_of(':');
166         if (n5 == StringRef::npos)
167           return false;
168         n3 += n5 + 1;
169       }
170 
171       // An anchor point is found. Save the {target, count} pair
172       TargetCountMap[Target] = count;
173       if (n4 == Rest.size())
174         break;
175       // Change n3 to the next blank space after colon + integer pair.
176       n3 = n4;
177     }
178   } else {
179     IsCallsite = true;
180     size_t n3 = Rest.find_last_of(':');
181     CalleeName = Rest.substr(0, n3);
182     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
183       return false;
184   }
185   return true;
186 }
187 
188 /// Load samples from a text file.
189 ///
190 /// See the documentation at the top of the file for an explanation of
191 /// the expected format.
192 ///
193 /// \returns true if the file was loaded successfully, false otherwise.
194 std::error_code SampleProfileReaderText::read() {
195   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
196   sampleprof_error Result = sampleprof_error::success;
197 
198   InlineCallStack InlineStack;
199 
200   for (; !LineIt.is_at_eof(); ++LineIt) {
201     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
202       continue;
203     // Read the header of each function.
204     //
205     // Note that for function identifiers we are actually expecting
206     // mangled names, but we may not always get them. This happens when
207     // the compiler decides not to emit the function (e.g., it was inlined
208     // and removed). In this case, the binary will not have the linkage
209     // name for the function, so the profiler will emit the function's
210     // unmangled name, which may contain characters like ':' and '>' in its
211     // name (member functions, templates, etc).
212     //
213     // The only requirement we place on the identifier, then, is that it
214     // should not begin with a number.
215     if ((*LineIt)[0] != ' ') {
216       uint64_t NumSamples, NumHeadSamples;
217       StringRef FName;
218       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
219         reportError(LineIt.line_number(),
220                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
221         return sampleprof_error::malformed;
222       }
223       Profiles[FName] = FunctionSamples();
224       FunctionSamples &FProfile = Profiles[FName];
225       FProfile.setName(FName);
226       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
227       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
228       InlineStack.clear();
229       InlineStack.push_back(&FProfile);
230     } else {
231       uint64_t NumSamples;
232       StringRef FName;
233       DenseMap<StringRef, uint64_t> TargetCountMap;
234       bool IsCallsite;
235       uint32_t Depth, LineOffset, Discriminator;
236       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
237                      Discriminator, FName, TargetCountMap)) {
238         reportError(LineIt.line_number(),
239                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
240                         *LineIt);
241         return sampleprof_error::malformed;
242       }
243       if (IsCallsite) {
244         while (InlineStack.size() > Depth) {
245           InlineStack.pop_back();
246         }
247         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
248             LineLocation(LineOffset, Discriminator))[FName];
249         FSamples.setName(FName);
250         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
251         InlineStack.push_back(&FSamples);
252       } else {
253         while (InlineStack.size() > Depth) {
254           InlineStack.pop_back();
255         }
256         FunctionSamples &FProfile = *InlineStack.back();
257         for (const auto &name_count : TargetCountMap) {
258           MergeResult(Result, FProfile.addCalledTargetSamples(
259                                   LineOffset, Discriminator, name_count.first,
260                                   name_count.second));
261         }
262         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
263                                                     NumSamples));
264       }
265     }
266   }
267   if (Result == sampleprof_error::success)
268     computeSummary();
269 
270   return Result;
271 }
272 
273 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
274   bool result = false;
275 
276   // Check that the first non-comment line is a valid function header.
277   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
278   if (!LineIt.is_at_eof()) {
279     if ((*LineIt)[0] != ' ') {
280       uint64_t NumSamples, NumHeadSamples;
281       StringRef FName;
282       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
283     }
284   }
285 
286   return result;
287 }
288 
289 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
290   unsigned NumBytesRead = 0;
291   std::error_code EC;
292   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
293 
294   if (Val > std::numeric_limits<T>::max())
295     EC = sampleprof_error::malformed;
296   else if (Data + NumBytesRead > End)
297     EC = sampleprof_error::truncated;
298   else
299     EC = sampleprof_error::success;
300 
301   if (EC) {
302     reportError(0, EC.message());
303     return EC;
304   }
305 
306   Data += NumBytesRead;
307   return static_cast<T>(Val);
308 }
309 
310 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
311   std::error_code EC;
312   StringRef Str(reinterpret_cast<const char *>(Data));
313   if (Data + Str.size() + 1 > End) {
314     EC = sampleprof_error::truncated;
315     reportError(0, EC.message());
316     return EC;
317   }
318 
319   Data += Str.size() + 1;
320   return Str;
321 }
322 
323 template <typename T>
324 ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
325   std::error_code EC;
326 
327   if (Data + sizeof(T) > End) {
328     EC = sampleprof_error::truncated;
329     reportError(0, EC.message());
330     return EC;
331   }
332 
333   using namespace support;
334   T Val = endian::readNext<T, little, unaligned>(Data);
335   return Val;
336 }
337 
338 template <typename T>
339 inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
340   std::error_code EC;
341   auto Idx = readNumber<uint32_t>();
342   if (std::error_code EC = Idx.getError())
343     return EC;
344   if (*Idx >= Table.size())
345     return sampleprof_error::truncated_name_table;
346   return *Idx;
347 }
348 
349 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
350   auto Idx = readStringIndex(NameTable);
351   if (std::error_code EC = Idx.getError())
352     return EC;
353 
354   return NameTable[*Idx];
355 }
356 
357 ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
358   auto Idx = readStringIndex(NameTable);
359   if (std::error_code EC = Idx.getError())
360     return EC;
361 
362   return StringRef(NameTable[*Idx]);
363 }
364 
365 std::error_code
366 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
367   auto NumSamples = readNumber<uint64_t>();
368   if (std::error_code EC = NumSamples.getError())
369     return EC;
370   FProfile.addTotalSamples(*NumSamples);
371 
372   // Read the samples in the body.
373   auto NumRecords = readNumber<uint32_t>();
374   if (std::error_code EC = NumRecords.getError())
375     return EC;
376 
377   for (uint32_t I = 0; I < *NumRecords; ++I) {
378     auto LineOffset = readNumber<uint64_t>();
379     if (std::error_code EC = LineOffset.getError())
380       return EC;
381 
382     if (!isOffsetLegal(*LineOffset)) {
383       return std::error_code();
384     }
385 
386     auto Discriminator = readNumber<uint64_t>();
387     if (std::error_code EC = Discriminator.getError())
388       return EC;
389 
390     auto NumSamples = readNumber<uint64_t>();
391     if (std::error_code EC = NumSamples.getError())
392       return EC;
393 
394     auto NumCalls = readNumber<uint32_t>();
395     if (std::error_code EC = NumCalls.getError())
396       return EC;
397 
398     for (uint32_t J = 0; J < *NumCalls; ++J) {
399       auto CalledFunction(readStringFromTable());
400       if (std::error_code EC = CalledFunction.getError())
401         return EC;
402 
403       auto CalledFunctionSamples = readNumber<uint64_t>();
404       if (std::error_code EC = CalledFunctionSamples.getError())
405         return EC;
406 
407       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
408                                       *CalledFunction, *CalledFunctionSamples);
409     }
410 
411     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
412   }
413 
414   // Read all the samples for inlined function calls.
415   auto NumCallsites = readNumber<uint32_t>();
416   if (std::error_code EC = NumCallsites.getError())
417     return EC;
418 
419   for (uint32_t J = 0; J < *NumCallsites; ++J) {
420     auto LineOffset = readNumber<uint64_t>();
421     if (std::error_code EC = LineOffset.getError())
422       return EC;
423 
424     auto Discriminator = readNumber<uint64_t>();
425     if (std::error_code EC = Discriminator.getError())
426       return EC;
427 
428     auto FName(readStringFromTable());
429     if (std::error_code EC = FName.getError())
430       return EC;
431 
432     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
433         LineLocation(*LineOffset, *Discriminator))[*FName];
434     CalleeProfile.setName(*FName);
435     if (std::error_code EC = readProfile(CalleeProfile))
436       return EC;
437   }
438 
439   return sampleprof_error::success;
440 }
441 
442 std::error_code
443 SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
444   Data = Start;
445   auto NumHeadSamples = readNumber<uint64_t>();
446   if (std::error_code EC = NumHeadSamples.getError())
447     return EC;
448 
449   auto FName(readStringFromTable());
450   if (std::error_code EC = FName.getError())
451     return EC;
452 
453   Profiles[*FName] = FunctionSamples();
454   FunctionSamples &FProfile = Profiles[*FName];
455   FProfile.setName(*FName);
456 
457   FProfile.addHeadSamples(*NumHeadSamples);
458 
459   if (std::error_code EC = readProfile(FProfile))
460     return EC;
461   return sampleprof_error::success;
462 }
463 
464 std::error_code SampleProfileReaderBinary::read() {
465   while (!at_eof()) {
466     if (std::error_code EC = readFuncProfile(Data))
467       return EC;
468   }
469 
470   return sampleprof_error::success;
471 }
472 
473 std::error_code
474 SampleProfileReaderExtBinary::readOneSection(const uint8_t *Start,
475                                              uint64_t Size, SecType Type) {
476   Data = Start;
477   End = Start + Size;
478   switch (Type) {
479   case SecProfSummary:
480     if (std::error_code EC = readSummary())
481       return EC;
482     break;
483   case SecNameTable:
484     if (std::error_code EC = readNameTable())
485       return EC;
486     break;
487   case SecLBRProfile:
488     if (std::error_code EC = readFuncProfiles())
489       return EC;
490     break;
491   case SecProfileSymbolList:
492     if (std::error_code EC = readProfileSymbolList())
493       return EC;
494     break;
495   case SecFuncOffsetTable:
496     if (std::error_code EC = readFuncOffsetTable())
497       return EC;
498     break;
499   default:
500     break;
501   }
502   return sampleprof_error::success;
503 }
504 
505 void SampleProfileReaderExtBinary::collectFuncsFrom(const Module &M) {
506   UseAllFuncs = false;
507   FuncsToUse.clear();
508   for (auto &F : M)
509     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
510 }
511 
512 std::error_code SampleProfileReaderExtBinary::readFuncOffsetTable() {
513   auto Size = readNumber<uint64_t>();
514   if (std::error_code EC = Size.getError())
515     return EC;
516 
517   FuncOffsetTable.reserve(*Size);
518   for (uint32_t I = 0; I < *Size; ++I) {
519     auto FName(readStringFromTable());
520     if (std::error_code EC = FName.getError())
521       return EC;
522 
523     auto Offset = readNumber<uint64_t>();
524     if (std::error_code EC = Offset.getError())
525       return EC;
526 
527     FuncOffsetTable[*FName] = *Offset;
528   }
529   return sampleprof_error::success;
530 }
531 
532 std::error_code SampleProfileReaderExtBinary::readFuncProfiles() {
533   const uint8_t *Start = Data;
534   if (UseAllFuncs) {
535     while (Data < End) {
536       if (std::error_code EC = readFuncProfile(Data))
537         return EC;
538     }
539     assert(Data == End && "More data is read than expected");
540     return sampleprof_error::success;
541   }
542 
543   for (auto Name : FuncsToUse) {
544     auto iter = FuncOffsetTable.find(Name);
545     if (iter == FuncOffsetTable.end())
546       continue;
547     const uint8_t *FuncProfileAddr = Start + iter->second;
548     assert(FuncProfileAddr < End && "out of LBRProfile section");
549     if (std::error_code EC = readFuncProfile(FuncProfileAddr))
550       return EC;
551   }
552   Data = End;
553   return sampleprof_error::success;
554 }
555 
556 std::error_code SampleProfileReaderExtBinary::readProfileSymbolList() {
557   if (!ProfSymList)
558     ProfSymList = std::make_unique<ProfileSymbolList>();
559 
560   if (std::error_code EC = ProfSymList->read(Data, End - Data))
561     return EC;
562 
563   Data = End;
564   return sampleprof_error::success;
565 }
566 
567 std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
568     const uint8_t *SecStart, const uint64_t SecSize,
569     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
570   Data = SecStart;
571   End = SecStart + SecSize;
572   auto DecompressSize = readNumber<uint64_t>();
573   if (std::error_code EC = DecompressSize.getError())
574     return EC;
575   DecompressBufSize = *DecompressSize;
576 
577   auto CompressSize = readNumber<uint64_t>();
578   if (std::error_code EC = CompressSize.getError())
579     return EC;
580 
581   if (!llvm::zlib::isAvailable())
582     return sampleprof_error::zlib_unavailable;
583 
584   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
585                               *CompressSize);
586   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
587   size_t UCSize = DecompressBufSize;
588   llvm::Error E =
589       zlib::uncompress(CompressedStrings, Buffer, UCSize);
590   if (E)
591     return sampleprof_error::uncompress_failed;
592   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
593   return sampleprof_error::success;
594 }
595 
596 std::error_code SampleProfileReaderExtBinaryBase::read() {
597   const uint8_t *BufStart =
598       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
599 
600   for (auto &Entry : SecHdrTable) {
601     // Skip empty section.
602     if (!Entry.Size)
603       continue;
604 
605     const uint8_t *SecStart = BufStart + Entry.Offset;
606     uint64_t SecSize = Entry.Size;
607 
608     // If the section is compressed, decompress it into a buffer
609     // DecompressBuf before reading the actual data. The pointee of
610     // 'Data' will be changed to buffer hold by DecompressBuf
611     // temporarily when reading the actual data.
612     bool isCompressed = hasSecFlag(Entry, SecFlagCompress);
613     if (isCompressed) {
614       const uint8_t *DecompressBuf;
615       uint64_t DecompressBufSize;
616       if (std::error_code EC = decompressSection(
617               SecStart, SecSize, DecompressBuf, DecompressBufSize))
618         return EC;
619       SecStart = DecompressBuf;
620       SecSize = DecompressBufSize;
621     }
622 
623     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry.Type))
624       return EC;
625     if (Data != SecStart + SecSize)
626       return sampleprof_error::malformed;
627 
628     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
629     if (isCompressed) {
630       Data = BufStart + Entry.Offset;
631       End = BufStart + Buffer->getBufferSize();
632     }
633   }
634 
635   return sampleprof_error::success;
636 }
637 
638 std::error_code SampleProfileReaderCompactBinary::read() {
639   std::vector<uint64_t> OffsetsToUse;
640   if (UseAllFuncs) {
641     for (auto FuncEntry : FuncOffsetTable) {
642       OffsetsToUse.push_back(FuncEntry.second);
643     }
644   }
645   else {
646     for (auto Name : FuncsToUse) {
647       auto GUID = std::to_string(MD5Hash(Name));
648       auto iter = FuncOffsetTable.find(StringRef(GUID));
649       if (iter == FuncOffsetTable.end())
650         continue;
651       OffsetsToUse.push_back(iter->second);
652     }
653   }
654 
655   for (auto Offset : OffsetsToUse) {
656     const uint8_t *SavedData = Data;
657     if (std::error_code EC = readFuncProfile(
658             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
659             Offset))
660       return EC;
661     Data = SavedData;
662   }
663   return sampleprof_error::success;
664 }
665 
666 std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
667   if (Magic == SPMagic())
668     return sampleprof_error::success;
669   return sampleprof_error::bad_magic;
670 }
671 
672 std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
673   if (Magic == SPMagic(SPF_Ext_Binary))
674     return sampleprof_error::success;
675   return sampleprof_error::bad_magic;
676 }
677 
678 std::error_code
679 SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
680   if (Magic == SPMagic(SPF_Compact_Binary))
681     return sampleprof_error::success;
682   return sampleprof_error::bad_magic;
683 }
684 
685 std::error_code SampleProfileReaderBinary::readNameTable() {
686   auto Size = readNumber<uint32_t>();
687   if (std::error_code EC = Size.getError())
688     return EC;
689   NameTable.reserve(*Size);
690   for (uint32_t I = 0; I < *Size; ++I) {
691     auto Name(readString());
692     if (std::error_code EC = Name.getError())
693       return EC;
694     NameTable.push_back(*Name);
695   }
696 
697   return sampleprof_error::success;
698 }
699 
700 std::error_code SampleProfileReaderCompactBinary::readNameTable() {
701   auto Size = readNumber<uint64_t>();
702   if (std::error_code EC = Size.getError())
703     return EC;
704   NameTable.reserve(*Size);
705   for (uint32_t I = 0; I < *Size; ++I) {
706     auto FID = readNumber<uint64_t>();
707     if (std::error_code EC = FID.getError())
708       return EC;
709     NameTable.push_back(std::to_string(*FID));
710   }
711   return sampleprof_error::success;
712 }
713 
714 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTableEntry() {
715   SecHdrTableEntry Entry;
716   auto Type = readUnencodedNumber<uint64_t>();
717   if (std::error_code EC = Type.getError())
718     return EC;
719   Entry.Type = static_cast<SecType>(*Type);
720 
721   auto Flags = readUnencodedNumber<uint64_t>();
722   if (std::error_code EC = Flags.getError())
723     return EC;
724   Entry.Flags = *Flags;
725 
726   auto Offset = readUnencodedNumber<uint64_t>();
727   if (std::error_code EC = Offset.getError())
728     return EC;
729   Entry.Offset = *Offset;
730 
731   auto Size = readUnencodedNumber<uint64_t>();
732   if (std::error_code EC = Size.getError())
733     return EC;
734   Entry.Size = *Size;
735 
736   SecHdrTable.push_back(std::move(Entry));
737   return sampleprof_error::success;
738 }
739 
740 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
741   auto EntryNum = readUnencodedNumber<uint64_t>();
742   if (std::error_code EC = EntryNum.getError())
743     return EC;
744 
745   for (uint32_t i = 0; i < (*EntryNum); i++)
746     if (std::error_code EC = readSecHdrTableEntry())
747       return EC;
748 
749   return sampleprof_error::success;
750 }
751 
752 std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
753   const uint8_t *BufStart =
754       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
755   Data = BufStart;
756   End = BufStart + Buffer->getBufferSize();
757 
758   if (std::error_code EC = readMagicIdent())
759     return EC;
760 
761   if (std::error_code EC = readSecHdrTable())
762     return EC;
763 
764   return sampleprof_error::success;
765 }
766 
767 uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
768   for (auto &Entry : SecHdrTable) {
769     if (Entry.Type == Type)
770       return Entry.Size;
771   }
772   return 0;
773 }
774 
775 uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
776   // Sections in SecHdrTable is not necessarily in the same order as
777   // sections in the profile because section like FuncOffsetTable needs
778   // to be written after section LBRProfile but needs to be read before
779   // section LBRProfile, so we cannot simply use the last entry in
780   // SecHdrTable to calculate the file size.
781   uint64_t FileSize = 0;
782   for (auto &Entry : SecHdrTable) {
783     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
784   }
785   return FileSize;
786 }
787 
788 bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
789   uint64_t TotalSecsSize = 0;
790   for (auto &Entry : SecHdrTable) {
791     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
792        << ", Size: " << Entry.Size << "\n";
793     TotalSecsSize += getSectionSize(Entry.Type);
794   }
795   uint64_t HeaderSize = SecHdrTable.front().Offset;
796   assert(HeaderSize + TotalSecsSize == getFileSize() &&
797          "Size of 'header + sections' doesn't match the total size of profile");
798 
799   OS << "Header Size: " << HeaderSize << "\n";
800   OS << "Total Sections Size: " << TotalSecsSize << "\n";
801   OS << "File Size: " << getFileSize() << "\n";
802   return true;
803 }
804 
805 std::error_code SampleProfileReaderBinary::readMagicIdent() {
806   // Read and check the magic identifier.
807   auto Magic = readNumber<uint64_t>();
808   if (std::error_code EC = Magic.getError())
809     return EC;
810   else if (std::error_code EC = verifySPMagic(*Magic))
811     return EC;
812 
813   // Read the version number.
814   auto Version = readNumber<uint64_t>();
815   if (std::error_code EC = Version.getError())
816     return EC;
817   else if (*Version != SPVersion())
818     return sampleprof_error::unsupported_version;
819 
820   return sampleprof_error::success;
821 }
822 
823 std::error_code SampleProfileReaderBinary::readHeader() {
824   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
825   End = Data + Buffer->getBufferSize();
826 
827   if (std::error_code EC = readMagicIdent())
828     return EC;
829 
830   if (std::error_code EC = readSummary())
831     return EC;
832 
833   if (std::error_code EC = readNameTable())
834     return EC;
835   return sampleprof_error::success;
836 }
837 
838 std::error_code SampleProfileReaderCompactBinary::readHeader() {
839   SampleProfileReaderBinary::readHeader();
840   if (std::error_code EC = readFuncOffsetTable())
841     return EC;
842   return sampleprof_error::success;
843 }
844 
845 std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
846   auto TableOffset = readUnencodedNumber<uint64_t>();
847   if (std::error_code EC = TableOffset.getError())
848     return EC;
849 
850   const uint8_t *SavedData = Data;
851   const uint8_t *TableStart =
852       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
853       *TableOffset;
854   Data = TableStart;
855 
856   auto Size = readNumber<uint64_t>();
857   if (std::error_code EC = Size.getError())
858     return EC;
859 
860   FuncOffsetTable.reserve(*Size);
861   for (uint32_t I = 0; I < *Size; ++I) {
862     auto FName(readStringFromTable());
863     if (std::error_code EC = FName.getError())
864       return EC;
865 
866     auto Offset = readNumber<uint64_t>();
867     if (std::error_code EC = Offset.getError())
868       return EC;
869 
870     FuncOffsetTable[*FName] = *Offset;
871   }
872   End = TableStart;
873   Data = SavedData;
874   return sampleprof_error::success;
875 }
876 
877 void SampleProfileReaderCompactBinary::collectFuncsFrom(const Module &M) {
878   UseAllFuncs = false;
879   FuncsToUse.clear();
880   for (auto &F : M)
881     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
882 }
883 
884 std::error_code SampleProfileReaderBinary::readSummaryEntry(
885     std::vector<ProfileSummaryEntry> &Entries) {
886   auto Cutoff = readNumber<uint64_t>();
887   if (std::error_code EC = Cutoff.getError())
888     return EC;
889 
890   auto MinBlockCount = readNumber<uint64_t>();
891   if (std::error_code EC = MinBlockCount.getError())
892     return EC;
893 
894   auto NumBlocks = readNumber<uint64_t>();
895   if (std::error_code EC = NumBlocks.getError())
896     return EC;
897 
898   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
899   return sampleprof_error::success;
900 }
901 
902 std::error_code SampleProfileReaderBinary::readSummary() {
903   auto TotalCount = readNumber<uint64_t>();
904   if (std::error_code EC = TotalCount.getError())
905     return EC;
906 
907   auto MaxBlockCount = readNumber<uint64_t>();
908   if (std::error_code EC = MaxBlockCount.getError())
909     return EC;
910 
911   auto MaxFunctionCount = readNumber<uint64_t>();
912   if (std::error_code EC = MaxFunctionCount.getError())
913     return EC;
914 
915   auto NumBlocks = readNumber<uint64_t>();
916   if (std::error_code EC = NumBlocks.getError())
917     return EC;
918 
919   auto NumFunctions = readNumber<uint64_t>();
920   if (std::error_code EC = NumFunctions.getError())
921     return EC;
922 
923   auto NumSummaryEntries = readNumber<uint64_t>();
924   if (std::error_code EC = NumSummaryEntries.getError())
925     return EC;
926 
927   std::vector<ProfileSummaryEntry> Entries;
928   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
929     std::error_code EC = readSummaryEntry(Entries);
930     if (EC != sampleprof_error::success)
931       return EC;
932   }
933   Summary = std::make_unique<ProfileSummary>(
934       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
935       *MaxFunctionCount, *NumBlocks, *NumFunctions);
936 
937   return sampleprof_error::success;
938 }
939 
940 bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
941   const uint8_t *Data =
942       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
943   uint64_t Magic = decodeULEB128(Data);
944   return Magic == SPMagic();
945 }
946 
947 bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
948   const uint8_t *Data =
949       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
950   uint64_t Magic = decodeULEB128(Data);
951   return Magic == SPMagic(SPF_Ext_Binary);
952 }
953 
954 bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
955   const uint8_t *Data =
956       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
957   uint64_t Magic = decodeULEB128(Data);
958   return Magic == SPMagic(SPF_Compact_Binary);
959 }
960 
961 std::error_code SampleProfileReaderGCC::skipNextWord() {
962   uint32_t dummy;
963   if (!GcovBuffer.readInt(dummy))
964     return sampleprof_error::truncated;
965   return sampleprof_error::success;
966 }
967 
968 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
969   if (sizeof(T) <= sizeof(uint32_t)) {
970     uint32_t Val;
971     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
972       return static_cast<T>(Val);
973   } else if (sizeof(T) <= sizeof(uint64_t)) {
974     uint64_t Val;
975     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
976       return static_cast<T>(Val);
977   }
978 
979   std::error_code EC = sampleprof_error::malformed;
980   reportError(0, EC.message());
981   return EC;
982 }
983 
984 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
985   StringRef Str;
986   if (!GcovBuffer.readString(Str))
987     return sampleprof_error::truncated;
988   return Str;
989 }
990 
991 std::error_code SampleProfileReaderGCC::readHeader() {
992   // Read the magic identifier.
993   if (!GcovBuffer.readGCDAFormat())
994     return sampleprof_error::unrecognized_format;
995 
996   // Read the version number. Note - the GCC reader does not validate this
997   // version, but the profile creator generates v704.
998   GCOV::GCOVVersion version;
999   if (!GcovBuffer.readGCOVVersion(version))
1000     return sampleprof_error::unrecognized_format;
1001 
1002   if (version != GCOV::V704)
1003     return sampleprof_error::unsupported_version;
1004 
1005   // Skip the empty integer.
1006   if (std::error_code EC = skipNextWord())
1007     return EC;
1008 
1009   return sampleprof_error::success;
1010 }
1011 
1012 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
1013   uint32_t Tag;
1014   if (!GcovBuffer.readInt(Tag))
1015     return sampleprof_error::truncated;
1016 
1017   if (Tag != Expected)
1018     return sampleprof_error::malformed;
1019 
1020   if (std::error_code EC = skipNextWord())
1021     return EC;
1022 
1023   return sampleprof_error::success;
1024 }
1025 
1026 std::error_code SampleProfileReaderGCC::readNameTable() {
1027   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1028     return EC;
1029 
1030   uint32_t Size;
1031   if (!GcovBuffer.readInt(Size))
1032     return sampleprof_error::truncated;
1033 
1034   for (uint32_t I = 0; I < Size; ++I) {
1035     StringRef Str;
1036     if (!GcovBuffer.readString(Str))
1037       return sampleprof_error::truncated;
1038     Names.push_back(Str);
1039   }
1040 
1041   return sampleprof_error::success;
1042 }
1043 
1044 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
1045   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1046     return EC;
1047 
1048   uint32_t NumFunctions;
1049   if (!GcovBuffer.readInt(NumFunctions))
1050     return sampleprof_error::truncated;
1051 
1052   InlineCallStack Stack;
1053   for (uint32_t I = 0; I < NumFunctions; ++I)
1054     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1055       return EC;
1056 
1057   computeSummary();
1058   return sampleprof_error::success;
1059 }
1060 
1061 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1062     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1063   uint64_t HeadCount = 0;
1064   if (InlineStack.size() == 0)
1065     if (!GcovBuffer.readInt64(HeadCount))
1066       return sampleprof_error::truncated;
1067 
1068   uint32_t NameIdx;
1069   if (!GcovBuffer.readInt(NameIdx))
1070     return sampleprof_error::truncated;
1071 
1072   StringRef Name(Names[NameIdx]);
1073 
1074   uint32_t NumPosCounts;
1075   if (!GcovBuffer.readInt(NumPosCounts))
1076     return sampleprof_error::truncated;
1077 
1078   uint32_t NumCallsites;
1079   if (!GcovBuffer.readInt(NumCallsites))
1080     return sampleprof_error::truncated;
1081 
1082   FunctionSamples *FProfile = nullptr;
1083   if (InlineStack.size() == 0) {
1084     // If this is a top function that we have already processed, do not
1085     // update its profile again.  This happens in the presence of
1086     // function aliases.  Since these aliases share the same function
1087     // body, there will be identical replicated profiles for the
1088     // original function.  In this case, we simply not bother updating
1089     // the profile of the original function.
1090     FProfile = &Profiles[Name];
1091     FProfile->addHeadSamples(HeadCount);
1092     if (FProfile->getTotalSamples() > 0)
1093       Update = false;
1094   } else {
1095     // Otherwise, we are reading an inlined instance. The top of the
1096     // inline stack contains the profile of the caller. Insert this
1097     // callee in the caller's CallsiteMap.
1098     FunctionSamples *CallerProfile = InlineStack.front();
1099     uint32_t LineOffset = Offset >> 16;
1100     uint32_t Discriminator = Offset & 0xffff;
1101     FProfile = &CallerProfile->functionSamplesAt(
1102         LineLocation(LineOffset, Discriminator))[Name];
1103   }
1104   FProfile->setName(Name);
1105 
1106   for (uint32_t I = 0; I < NumPosCounts; ++I) {
1107     uint32_t Offset;
1108     if (!GcovBuffer.readInt(Offset))
1109       return sampleprof_error::truncated;
1110 
1111     uint32_t NumTargets;
1112     if (!GcovBuffer.readInt(NumTargets))
1113       return sampleprof_error::truncated;
1114 
1115     uint64_t Count;
1116     if (!GcovBuffer.readInt64(Count))
1117       return sampleprof_error::truncated;
1118 
1119     // The line location is encoded in the offset as:
1120     //   high 16 bits: line offset to the start of the function.
1121     //   low 16 bits: discriminator.
1122     uint32_t LineOffset = Offset >> 16;
1123     uint32_t Discriminator = Offset & 0xffff;
1124 
1125     InlineCallStack NewStack;
1126     NewStack.push_back(FProfile);
1127     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1128     if (Update) {
1129       // Walk up the inline stack, adding the samples on this line to
1130       // the total sample count of the callers in the chain.
1131       for (auto CallerProfile : NewStack)
1132         CallerProfile->addTotalSamples(Count);
1133 
1134       // Update the body samples for the current profile.
1135       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1136     }
1137 
1138     // Process the list of functions called at an indirect call site.
1139     // These are all the targets that a function pointer (or virtual
1140     // function) resolved at runtime.
1141     for (uint32_t J = 0; J < NumTargets; J++) {
1142       uint32_t HistVal;
1143       if (!GcovBuffer.readInt(HistVal))
1144         return sampleprof_error::truncated;
1145 
1146       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1147         return sampleprof_error::malformed;
1148 
1149       uint64_t TargetIdx;
1150       if (!GcovBuffer.readInt64(TargetIdx))
1151         return sampleprof_error::truncated;
1152       StringRef TargetName(Names[TargetIdx]);
1153 
1154       uint64_t TargetCount;
1155       if (!GcovBuffer.readInt64(TargetCount))
1156         return sampleprof_error::truncated;
1157 
1158       if (Update)
1159         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1160                                          TargetName, TargetCount);
1161     }
1162   }
1163 
1164   // Process all the inlined callers into the current function. These
1165   // are all the callsites that were inlined into this function.
1166   for (uint32_t I = 0; I < NumCallsites; I++) {
1167     // The offset is encoded as:
1168     //   high 16 bits: line offset to the start of the function.
1169     //   low 16 bits: discriminator.
1170     uint32_t Offset;
1171     if (!GcovBuffer.readInt(Offset))
1172       return sampleprof_error::truncated;
1173     InlineCallStack NewStack;
1174     NewStack.push_back(FProfile);
1175     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1176     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1177       return EC;
1178   }
1179 
1180   return sampleprof_error::success;
1181 }
1182 
1183 /// Read a GCC AutoFDO profile.
1184 ///
1185 /// This format is generated by the Linux Perf conversion tool at
1186 /// https://github.com/google/autofdo.
1187 std::error_code SampleProfileReaderGCC::read() {
1188   // Read the string table.
1189   if (std::error_code EC = readNameTable())
1190     return EC;
1191 
1192   // Read the source profile.
1193   if (std::error_code EC = readFunctionProfiles())
1194     return EC;
1195 
1196   return sampleprof_error::success;
1197 }
1198 
1199 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
1200   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
1201   return Magic == "adcg*704";
1202 }
1203 
1204 std::error_code SampleProfileReaderItaniumRemapper::read() {
1205   // If the underlying data is in compact format, we can't remap it because
1206   // we don't know what the original function names were.
1207   if (getFormat() == SPF_Compact_Binary) {
1208     Ctx.diagnose(DiagnosticInfoSampleProfile(
1209         Buffer->getBufferIdentifier(),
1210         "Profile data remapping cannot be applied to profile data "
1211         "in compact format (original mangled names are not available).",
1212         DS_Warning));
1213     return sampleprof_error::success;
1214   }
1215 
1216   if (Error E = Remappings.read(*Buffer)) {
1217     handleAllErrors(
1218         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
1219           reportError(ParseError.getLineNum(), ParseError.getMessage());
1220         });
1221     return sampleprof_error::malformed;
1222   }
1223 
1224   for (auto &Sample : getProfiles())
1225     if (auto Key = Remappings.insert(Sample.first()))
1226       SampleMap.insert({Key, &Sample.second});
1227 
1228   return sampleprof_error::success;
1229 }
1230 
1231 FunctionSamples *
1232 SampleProfileReaderItaniumRemapper::getSamplesFor(StringRef Fname) {
1233   if (auto Key = Remappings.lookup(Fname))
1234     return SampleMap.lookup(Key);
1235   return SampleProfileReader::getSamplesFor(Fname);
1236 }
1237 
1238 /// Prepare a memory buffer for the contents of \p Filename.
1239 ///
1240 /// \returns an error code indicating the status of the buffer.
1241 static ErrorOr<std::unique_ptr<MemoryBuffer>>
1242 setupMemoryBuffer(const Twine &Filename) {
1243   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
1244   if (std::error_code EC = BufferOrErr.getError())
1245     return EC;
1246   auto Buffer = std::move(BufferOrErr.get());
1247 
1248   // Sanity check the file.
1249   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1250     return sampleprof_error::too_large;
1251 
1252   return std::move(Buffer);
1253 }
1254 
1255 /// Create a sample profile reader based on the format of the input file.
1256 ///
1257 /// \param Filename The file to open.
1258 ///
1259 /// \param C The LLVM context to use to emit diagnostics.
1260 ///
1261 /// \returns an error code indicating the status of the created reader.
1262 ErrorOr<std::unique_ptr<SampleProfileReader>>
1263 SampleProfileReader::create(const Twine &Filename, LLVMContext &C) {
1264   auto BufferOrError = setupMemoryBuffer(Filename);
1265   if (std::error_code EC = BufferOrError.getError())
1266     return EC;
1267   return create(BufferOrError.get(), C);
1268 }
1269 
1270 /// Create a sample profile remapper from the given input, to remap the
1271 /// function names in the given profile data.
1272 ///
1273 /// \param Filename The file to open.
1274 ///
1275 /// \param C The LLVM context to use to emit diagnostics.
1276 ///
1277 /// \param Underlying The underlying profile data reader to remap.
1278 ///
1279 /// \returns an error code indicating the status of the created reader.
1280 ErrorOr<std::unique_ptr<SampleProfileReader>>
1281 SampleProfileReaderItaniumRemapper::create(
1282     const Twine &Filename, LLVMContext &C,
1283     std::unique_ptr<SampleProfileReader> Underlying) {
1284   auto BufferOrError = setupMemoryBuffer(Filename);
1285   if (std::error_code EC = BufferOrError.getError())
1286     return EC;
1287   return std::make_unique<SampleProfileReaderItaniumRemapper>(
1288       std::move(BufferOrError.get()), C, std::move(Underlying));
1289 }
1290 
1291 /// Create a sample profile reader based on the format of the input data.
1292 ///
1293 /// \param B The memory buffer to create the reader from (assumes ownership).
1294 ///
1295 /// \param C The LLVM context to use to emit diagnostics.
1296 ///
1297 /// \returns an error code indicating the status of the created reader.
1298 ErrorOr<std::unique_ptr<SampleProfileReader>>
1299 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
1300   std::unique_ptr<SampleProfileReader> Reader;
1301   if (SampleProfileReaderRawBinary::hasFormat(*B))
1302     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1303   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1304     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1305   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1306     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
1307   else if (SampleProfileReaderGCC::hasFormat(*B))
1308     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1309   else if (SampleProfileReaderText::hasFormat(*B))
1310     Reader.reset(new SampleProfileReaderText(std::move(B), C));
1311   else
1312     return sampleprof_error::unrecognized_format;
1313 
1314   FunctionSamples::Format = Reader->getFormat();
1315   if (std::error_code EC = Reader->readHeader()) {
1316     return EC;
1317   }
1318 
1319   return std::move(Reader);
1320 }
1321 
1322 // For text and GCC file formats, we compute the summary after reading the
1323 // profile. Binary format has the profile summary in its header.
1324 void SampleProfileReader::computeSummary() {
1325   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1326   for (const auto &I : Profiles) {
1327     const FunctionSamples &Profile = I.second;
1328     Builder.addRecord(Profile);
1329   }
1330   Summary = Builder.getSummary();
1331 }
1332