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 that contains metadata.
87 /// Possible metadata:
88 /// - CFG Checksum information:
89 ///     !CFGChecksum: 12345
90 /// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
91 static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash) {
92   if (!Input.startswith("!CFGChecksum:"))
93     return false;
94 
95   StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
96   return !CFGInfo.getAsInteger(10, FunctionHash);
97 }
98 
99 enum class LineType {
100   CallSiteProfile,
101   BodyProfile,
102   Metadata,
103 };
104 
105 /// Parse \p Input as line sample.
106 ///
107 /// \param Input input line.
108 /// \param LineTy Type of this line.
109 /// \param Depth the depth of the inline stack.
110 /// \param NumSamples total samples of the line/inlined callsite.
111 /// \param LineOffset line offset to the start of the function.
112 /// \param Discriminator discriminator of the line.
113 /// \param TargetCountMap map from indirect call target to count.
114 /// \param FunctionHash the function's CFG hash, used by pseudo probe.
115 ///
116 /// returns true if parsing is successful.
117 static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
118                       uint64_t &NumSamples, uint32_t &LineOffset,
119                       uint32_t &Discriminator, StringRef &CalleeName,
120                       DenseMap<StringRef, uint64_t> &TargetCountMap,
121                       uint64_t &FunctionHash) {
122   for (Depth = 0; Input[Depth] == ' '; Depth++)
123     ;
124   if (Depth == 0)
125     return false;
126 
127   if (Depth == 1 && Input[Depth] == '!') {
128     LineTy = LineType::Metadata;
129     return parseMetadata(Input.substr(Depth), FunctionHash);
130   }
131 
132   size_t n1 = Input.find(':');
133   StringRef Loc = Input.substr(Depth, n1 - Depth);
134   size_t n2 = Loc.find('.');
135   if (n2 == StringRef::npos) {
136     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
137       return false;
138     Discriminator = 0;
139   } else {
140     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
141       return false;
142     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
143       return false;
144   }
145 
146   StringRef Rest = Input.substr(n1 + 2);
147   if (isDigit(Rest[0])) {
148     LineTy = LineType::BodyProfile;
149     size_t n3 = Rest.find(' ');
150     if (n3 == StringRef::npos) {
151       if (Rest.getAsInteger(10, NumSamples))
152         return false;
153     } else {
154       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
155         return false;
156     }
157     // Find call targets and their sample counts.
158     // Note: In some cases, there are symbols in the profile which are not
159     // mangled. To accommodate such cases, use colon + integer pairs as the
160     // anchor points.
161     // An example:
162     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
163     // ":1000" and ":437" are used as anchor points so the string above will
164     // be interpreted as
165     // target: _M_construct<char *>
166     // count: 1000
167     // target: string_view<std::allocator<char> >
168     // count: 437
169     while (n3 != StringRef::npos) {
170       n3 += Rest.substr(n3).find_first_not_of(' ');
171       Rest = Rest.substr(n3);
172       n3 = Rest.find_first_of(':');
173       if (n3 == StringRef::npos || n3 == 0)
174         return false;
175 
176       StringRef Target;
177       uint64_t count, n4;
178       while (true) {
179         // Get the segment after the current colon.
180         StringRef AfterColon = Rest.substr(n3 + 1);
181         // Get the target symbol before the current colon.
182         Target = Rest.substr(0, n3);
183         // Check if the word after the current colon is an integer.
184         n4 = AfterColon.find_first_of(' ');
185         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
186         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
187         if (!WordAfterColon.getAsInteger(10, count))
188           break;
189 
190         // Try to find the next colon.
191         uint64_t n5 = AfterColon.find_first_of(':');
192         if (n5 == StringRef::npos)
193           return false;
194         n3 += n5 + 1;
195       }
196 
197       // An anchor point is found. Save the {target, count} pair
198       TargetCountMap[Target] = count;
199       if (n4 == Rest.size())
200         break;
201       // Change n3 to the next blank space after colon + integer pair.
202       n3 = n4;
203     }
204   } else {
205     LineTy = LineType::CallSiteProfile;
206     size_t n3 = Rest.find_last_of(':');
207     CalleeName = Rest.substr(0, n3);
208     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
209       return false;
210   }
211   return true;
212 }
213 
214 /// Load samples from a text file.
215 ///
216 /// See the documentation at the top of the file for an explanation of
217 /// the expected format.
218 ///
219 /// \returns true if the file was loaded successfully, false otherwise.
220 std::error_code SampleProfileReaderText::readImpl() {
221   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
222   sampleprof_error Result = sampleprof_error::success;
223 
224   InlineCallStack InlineStack;
225   uint32_t ProbeProfileCount = 0;
226 
227   // SeenMetadata tracks whether we have processed metadata for the current
228   // top-level function profile.
229   bool SeenMetadata = false;
230 
231   for (; !LineIt.is_at_eof(); ++LineIt) {
232     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
233       continue;
234     // Read the header of each function.
235     //
236     // Note that for function identifiers we are actually expecting
237     // mangled names, but we may not always get them. This happens when
238     // the compiler decides not to emit the function (e.g., it was inlined
239     // and removed). In this case, the binary will not have the linkage
240     // name for the function, so the profiler will emit the function's
241     // unmangled name, which may contain characters like ':' and '>' in its
242     // name (member functions, templates, etc).
243     //
244     // The only requirement we place on the identifier, then, is that it
245     // should not begin with a number.
246     if ((*LineIt)[0] != ' ') {
247       uint64_t NumSamples, NumHeadSamples;
248       StringRef FName;
249       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
250         reportError(LineIt.line_number(),
251                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
252         return sampleprof_error::malformed;
253       }
254       SeenMetadata = false;
255       SampleContext FContext(FName);
256       if (FContext.hasContext())
257         ++CSProfileCount;
258       Profiles[FContext] = FunctionSamples();
259       FunctionSamples &FProfile = Profiles[FContext];
260       FProfile.setName(FContext.getNameWithoutContext());
261       FProfile.setContext(FContext);
262       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
263       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
264       InlineStack.clear();
265       InlineStack.push_back(&FProfile);
266     } else {
267       uint64_t NumSamples;
268       StringRef FName;
269       DenseMap<StringRef, uint64_t> TargetCountMap;
270       uint32_t Depth, LineOffset, Discriminator;
271       LineType LineTy;
272       uint64_t FunctionHash;
273       if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
274                      Discriminator, FName, TargetCountMap, FunctionHash)) {
275         reportError(LineIt.line_number(),
276                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
277                         *LineIt);
278         return sampleprof_error::malformed;
279       }
280       if (SeenMetadata && LineTy != LineType::Metadata) {
281         // Metadata must be put at the end of a function profile.
282         reportError(LineIt.line_number(),
283                     "Found non-metadata after metadata: " + *LineIt);
284         return sampleprof_error::malformed;
285       }
286       while (InlineStack.size() > Depth) {
287         InlineStack.pop_back();
288       }
289       switch (LineTy) {
290       case LineType::CallSiteProfile: {
291         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
292             LineLocation(LineOffset, Discriminator))[std::string(FName)];
293         FSamples.setName(FName);
294         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
295         InlineStack.push_back(&FSamples);
296         break;
297       }
298       case LineType::BodyProfile: {
299         while (InlineStack.size() > Depth) {
300           InlineStack.pop_back();
301         }
302         FunctionSamples &FProfile = *InlineStack.back();
303         for (const auto &name_count : TargetCountMap) {
304           MergeResult(Result, FProfile.addCalledTargetSamples(
305                                   LineOffset, Discriminator, name_count.first,
306                                   name_count.second));
307         }
308         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
309                                                     NumSamples));
310         break;
311       }
312       case LineType::Metadata: {
313         FunctionSamples &FProfile = *InlineStack.back();
314         FProfile.setFunctionHash(FunctionHash);
315         ++ProbeProfileCount;
316         SeenMetadata = true;
317         break;
318       }
319       }
320     }
321   }
322 
323   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
324          "Cannot have both context-sensitive and regular profile");
325   ProfileIsCS = (CSProfileCount > 0);
326   assert((ProbeProfileCount == 0 || ProbeProfileCount == Profiles.size()) &&
327          "Cannot have both probe-based profiles and regular profiles");
328   ProfileIsProbeBased = (ProbeProfileCount > 0);
329   FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
330   FunctionSamples::ProfileIsCS = ProfileIsCS;
331 
332   if (Result == sampleprof_error::success)
333     computeSummary();
334 
335   return Result;
336 }
337 
338 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
339   bool result = false;
340 
341   // Check that the first non-comment line is a valid function header.
342   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
343   if (!LineIt.is_at_eof()) {
344     if ((*LineIt)[0] != ' ') {
345       uint64_t NumSamples, NumHeadSamples;
346       StringRef FName;
347       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
348     }
349   }
350 
351   return result;
352 }
353 
354 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
355   unsigned NumBytesRead = 0;
356   std::error_code EC;
357   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
358 
359   if (Val > std::numeric_limits<T>::max())
360     EC = sampleprof_error::malformed;
361   else if (Data + NumBytesRead > End)
362     EC = sampleprof_error::truncated;
363   else
364     EC = sampleprof_error::success;
365 
366   if (EC) {
367     reportError(0, EC.message());
368     return EC;
369   }
370 
371   Data += NumBytesRead;
372   return static_cast<T>(Val);
373 }
374 
375 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
376   std::error_code EC;
377   StringRef Str(reinterpret_cast<const char *>(Data));
378   if (Data + Str.size() + 1 > End) {
379     EC = sampleprof_error::truncated;
380     reportError(0, EC.message());
381     return EC;
382   }
383 
384   Data += Str.size() + 1;
385   return Str;
386 }
387 
388 template <typename T>
389 ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
390   std::error_code EC;
391 
392   if (Data + sizeof(T) > End) {
393     EC = sampleprof_error::truncated;
394     reportError(0, EC.message());
395     return EC;
396   }
397 
398   using namespace support;
399   T Val = endian::readNext<T, little, unaligned>(Data);
400   return Val;
401 }
402 
403 template <typename T>
404 inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
405   std::error_code EC;
406   auto Idx = readNumber<uint32_t>();
407   if (std::error_code EC = Idx.getError())
408     return EC;
409   if (*Idx >= Table.size())
410     return sampleprof_error::truncated_name_table;
411   return *Idx;
412 }
413 
414 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
415   auto Idx = readStringIndex(NameTable);
416   if (std::error_code EC = Idx.getError())
417     return EC;
418 
419   return NameTable[*Idx];
420 }
421 
422 ErrorOr<StringRef> SampleProfileReaderExtBinaryBase::readStringFromTable() {
423   if (!FixedLengthMD5)
424     return SampleProfileReaderBinary::readStringFromTable();
425 
426   // read NameTable index.
427   auto Idx = readStringIndex(NameTable);
428   if (std::error_code EC = Idx.getError())
429     return EC;
430 
431   // Check whether the name to be accessed has been accessed before,
432   // if not, read it from memory directly.
433   StringRef &SR = NameTable[*Idx];
434   if (SR.empty()) {
435     const uint8_t *SavedData = Data;
436     Data = MD5NameMemStart + ((*Idx) * sizeof(uint64_t));
437     auto FID = readUnencodedNumber<uint64_t>();
438     if (std::error_code EC = FID.getError())
439       return EC;
440     // Save the string converted from uint64_t in MD5StringBuf. All the
441     // references to the name are all StringRefs refering to the string
442     // in MD5StringBuf.
443     MD5StringBuf->push_back(std::to_string(*FID));
444     SR = MD5StringBuf->back();
445     Data = SavedData;
446   }
447   return SR;
448 }
449 
450 ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
451   auto Idx = readStringIndex(NameTable);
452   if (std::error_code EC = Idx.getError())
453     return EC;
454 
455   return StringRef(NameTable[*Idx]);
456 }
457 
458 std::error_code
459 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
460   auto NumSamples = readNumber<uint64_t>();
461   if (std::error_code EC = NumSamples.getError())
462     return EC;
463   FProfile.addTotalSamples(*NumSamples);
464 
465   // Read the samples in the body.
466   auto NumRecords = readNumber<uint32_t>();
467   if (std::error_code EC = NumRecords.getError())
468     return EC;
469 
470   for (uint32_t I = 0; I < *NumRecords; ++I) {
471     auto LineOffset = readNumber<uint64_t>();
472     if (std::error_code EC = LineOffset.getError())
473       return EC;
474 
475     if (!isOffsetLegal(*LineOffset)) {
476       return std::error_code();
477     }
478 
479     auto Discriminator = readNumber<uint64_t>();
480     if (std::error_code EC = Discriminator.getError())
481       return EC;
482 
483     auto NumSamples = readNumber<uint64_t>();
484     if (std::error_code EC = NumSamples.getError())
485       return EC;
486 
487     auto NumCalls = readNumber<uint32_t>();
488     if (std::error_code EC = NumCalls.getError())
489       return EC;
490 
491     for (uint32_t J = 0; J < *NumCalls; ++J) {
492       auto CalledFunction(readStringFromTable());
493       if (std::error_code EC = CalledFunction.getError())
494         return EC;
495 
496       auto CalledFunctionSamples = readNumber<uint64_t>();
497       if (std::error_code EC = CalledFunctionSamples.getError())
498         return EC;
499 
500       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
501                                       *CalledFunction, *CalledFunctionSamples);
502     }
503 
504     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
505   }
506 
507   // Read all the samples for inlined function calls.
508   auto NumCallsites = readNumber<uint32_t>();
509   if (std::error_code EC = NumCallsites.getError())
510     return EC;
511 
512   for (uint32_t J = 0; J < *NumCallsites; ++J) {
513     auto LineOffset = readNumber<uint64_t>();
514     if (std::error_code EC = LineOffset.getError())
515       return EC;
516 
517     auto Discriminator = readNumber<uint64_t>();
518     if (std::error_code EC = Discriminator.getError())
519       return EC;
520 
521     auto FName(readStringFromTable());
522     if (std::error_code EC = FName.getError())
523       return EC;
524 
525     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
526         LineLocation(*LineOffset, *Discriminator))[std::string(*FName)];
527     CalleeProfile.setName(*FName);
528     if (std::error_code EC = readProfile(CalleeProfile))
529       return EC;
530   }
531 
532   return sampleprof_error::success;
533 }
534 
535 std::error_code
536 SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
537   Data = Start;
538   auto NumHeadSamples = readNumber<uint64_t>();
539   if (std::error_code EC = NumHeadSamples.getError())
540     return EC;
541 
542   auto FName(readStringFromTable());
543   if (std::error_code EC = FName.getError())
544     return EC;
545 
546   SampleContext FContext(*FName);
547   Profiles[FContext] = FunctionSamples();
548   FunctionSamples &FProfile = Profiles[FContext];
549   FProfile.setName(FContext.getNameWithoutContext());
550   FProfile.setContext(FContext);
551   FProfile.addHeadSamples(*NumHeadSamples);
552 
553   if (FContext.hasContext())
554     CSProfileCount++;
555 
556   if (std::error_code EC = readProfile(FProfile))
557     return EC;
558   return sampleprof_error::success;
559 }
560 
561 std::error_code SampleProfileReaderBinary::readImpl() {
562   while (!at_eof()) {
563     if (std::error_code EC = readFuncProfile(Data))
564       return EC;
565   }
566 
567   return sampleprof_error::success;
568 }
569 
570 std::error_code SampleProfileReaderExtBinaryBase::readOneSection(
571     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
572   Data = Start;
573   End = Start + Size;
574   switch (Entry.Type) {
575   case SecProfSummary:
576     if (std::error_code EC = readSummary())
577       return EC;
578     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
579       Summary->setPartialProfile(true);
580     break;
581   case SecNameTable: {
582     FixedLengthMD5 =
583         hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5);
584     bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
585     assert((!FixedLengthMD5 || UseMD5) &&
586            "If FixedLengthMD5 is true, UseMD5 has to be true");
587     if (std::error_code EC = readNameTableSec(UseMD5))
588       return EC;
589     break;
590   }
591   case SecLBRProfile:
592     if (std::error_code EC = readFuncProfiles())
593       return EC;
594     break;
595   case SecFuncOffsetTable:
596     if (std::error_code EC = readFuncOffsetTable())
597       return EC;
598     break;
599   case SecFuncMetadata:
600     ProfileIsProbeBased =
601         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagIsProbeBased);
602     FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
603     if (std::error_code EC = readFuncMetadata())
604       return EC;
605     break;
606   case SecProfileSymbolList:
607     if (std::error_code EC = readProfileSymbolList())
608       return EC;
609     break;
610   default:
611     if (std::error_code EC = readCustomSection(Entry))
612       return EC;
613     break;
614   }
615   return sampleprof_error::success;
616 }
617 
618 void SampleProfileReaderExtBinaryBase::collectFuncsFrom(const Module &M) {
619   UseAllFuncs = false;
620   FuncsToUse.clear();
621   for (auto &F : M)
622     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
623 }
624 
625 std::error_code SampleProfileReaderExtBinaryBase::readFuncOffsetTable() {
626   // If there are more than one FuncOffsetTable, the profile read associated
627   // with previous FuncOffsetTable has to be done before next FuncOffsetTable
628   // is read.
629   FuncOffsetTable.clear();
630 
631   auto Size = readNumber<uint64_t>();
632   if (std::error_code EC = Size.getError())
633     return EC;
634 
635   FuncOffsetTable.reserve(*Size);
636   for (uint32_t I = 0; I < *Size; ++I) {
637     auto FName(readStringFromTable());
638     if (std::error_code EC = FName.getError())
639       return EC;
640 
641     auto Offset = readNumber<uint64_t>();
642     if (std::error_code EC = Offset.getError())
643       return EC;
644 
645     FuncOffsetTable[*FName] = *Offset;
646   }
647   return sampleprof_error::success;
648 }
649 
650 std::error_code SampleProfileReaderExtBinaryBase::readFuncProfiles() {
651   const uint8_t *Start = Data;
652   if (UseAllFuncs) {
653     while (Data < End) {
654       if (std::error_code EC = readFuncProfile(Data))
655         return EC;
656     }
657     assert(Data == End && "More data is read than expected");
658   } else {
659     if (Remapper) {
660       for (auto Name : FuncsToUse) {
661         Remapper->insert(Name);
662       }
663     }
664 
665     if (useMD5()) {
666       for (auto Name : FuncsToUse) {
667         auto GUID = std::to_string(MD5Hash(Name));
668         auto iter = FuncOffsetTable.find(StringRef(GUID));
669         if (iter == FuncOffsetTable.end())
670           continue;
671         const uint8_t *FuncProfileAddr = Start + iter->second;
672         assert(FuncProfileAddr < End && "out of LBRProfile section");
673         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
674           return EC;
675       }
676     } else {
677       for (auto NameOffset : FuncOffsetTable) {
678         SampleContext FContext(NameOffset.first);
679         auto FuncName = FContext.getNameWithoutContext();
680         if (!FuncsToUse.count(FuncName) &&
681             (!Remapper || !Remapper->exist(FuncName)))
682           continue;
683         const uint8_t *FuncProfileAddr = Start + NameOffset.second;
684         assert(FuncProfileAddr < End && "out of LBRProfile section");
685         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
686           return EC;
687       }
688     }
689     Data = End;
690   }
691 
692   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
693          "Cannot have both context-sensitive and regular profile");
694   ProfileIsCS = (CSProfileCount > 0);
695   FunctionSamples::ProfileIsCS = ProfileIsCS;
696   return sampleprof_error::success;
697 }
698 
699 std::error_code SampleProfileReaderExtBinaryBase::readProfileSymbolList() {
700   if (!ProfSymList)
701     ProfSymList = std::make_unique<ProfileSymbolList>();
702 
703   if (std::error_code EC = ProfSymList->read(Data, End - Data))
704     return EC;
705 
706   Data = End;
707   return sampleprof_error::success;
708 }
709 
710 std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
711     const uint8_t *SecStart, const uint64_t SecSize,
712     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
713   Data = SecStart;
714   End = SecStart + SecSize;
715   auto DecompressSize = readNumber<uint64_t>();
716   if (std::error_code EC = DecompressSize.getError())
717     return EC;
718   DecompressBufSize = *DecompressSize;
719 
720   auto CompressSize = readNumber<uint64_t>();
721   if (std::error_code EC = CompressSize.getError())
722     return EC;
723 
724   if (!llvm::zlib::isAvailable())
725     return sampleprof_error::zlib_unavailable;
726 
727   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
728                               *CompressSize);
729   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
730   size_t UCSize = DecompressBufSize;
731   llvm::Error E =
732       zlib::uncompress(CompressedStrings, Buffer, UCSize);
733   if (E)
734     return sampleprof_error::uncompress_failed;
735   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
736   return sampleprof_error::success;
737 }
738 
739 std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
740   const uint8_t *BufStart =
741       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
742 
743   for (auto &Entry : SecHdrTable) {
744     // Skip empty section.
745     if (!Entry.Size)
746       continue;
747 
748     // Skip sections without context when SkipFlatProf is true.
749     if (SkipFlatProf && hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
750       continue;
751 
752     const uint8_t *SecStart = BufStart + Entry.Offset;
753     uint64_t SecSize = Entry.Size;
754 
755     // If the section is compressed, decompress it into a buffer
756     // DecompressBuf before reading the actual data. The pointee of
757     // 'Data' will be changed to buffer hold by DecompressBuf
758     // temporarily when reading the actual data.
759     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
760     if (isCompressed) {
761       const uint8_t *DecompressBuf;
762       uint64_t DecompressBufSize;
763       if (std::error_code EC = decompressSection(
764               SecStart, SecSize, DecompressBuf, DecompressBufSize))
765         return EC;
766       SecStart = DecompressBuf;
767       SecSize = DecompressBufSize;
768     }
769 
770     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
771       return EC;
772     if (Data != SecStart + SecSize)
773       return sampleprof_error::malformed;
774 
775     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
776     if (isCompressed) {
777       Data = BufStart + Entry.Offset;
778       End = BufStart + Buffer->getBufferSize();
779     }
780   }
781 
782   return sampleprof_error::success;
783 }
784 
785 std::error_code SampleProfileReaderCompactBinary::readImpl() {
786   std::vector<uint64_t> OffsetsToUse;
787   if (UseAllFuncs) {
788     for (auto FuncEntry : FuncOffsetTable) {
789       OffsetsToUse.push_back(FuncEntry.second);
790     }
791   }
792   else {
793     for (auto Name : FuncsToUse) {
794       auto GUID = std::to_string(MD5Hash(Name));
795       auto iter = FuncOffsetTable.find(StringRef(GUID));
796       if (iter == FuncOffsetTable.end())
797         continue;
798       OffsetsToUse.push_back(iter->second);
799     }
800   }
801 
802   for (auto Offset : OffsetsToUse) {
803     const uint8_t *SavedData = Data;
804     if (std::error_code EC = readFuncProfile(
805             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
806             Offset))
807       return EC;
808     Data = SavedData;
809   }
810   return sampleprof_error::success;
811 }
812 
813 std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
814   if (Magic == SPMagic())
815     return sampleprof_error::success;
816   return sampleprof_error::bad_magic;
817 }
818 
819 std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
820   if (Magic == SPMagic(SPF_Ext_Binary))
821     return sampleprof_error::success;
822   return sampleprof_error::bad_magic;
823 }
824 
825 std::error_code
826 SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
827   if (Magic == SPMagic(SPF_Compact_Binary))
828     return sampleprof_error::success;
829   return sampleprof_error::bad_magic;
830 }
831 
832 std::error_code SampleProfileReaderBinary::readNameTable() {
833   auto Size = readNumber<uint32_t>();
834   if (std::error_code EC = Size.getError())
835     return EC;
836   NameTable.reserve(*Size + NameTable.size());
837   for (uint32_t I = 0; I < *Size; ++I) {
838     auto Name(readString());
839     if (std::error_code EC = Name.getError())
840       return EC;
841     NameTable.push_back(*Name);
842   }
843 
844   return sampleprof_error::success;
845 }
846 
847 std::error_code SampleProfileReaderExtBinaryBase::readMD5NameTable() {
848   auto Size = readNumber<uint64_t>();
849   if (std::error_code EC = Size.getError())
850     return EC;
851   MD5StringBuf = std::make_unique<std::vector<std::string>>();
852   MD5StringBuf->reserve(*Size);
853   if (FixedLengthMD5) {
854     // Preallocate and initialize NameTable so we can check whether a name
855     // index has been read before by checking whether the element in the
856     // NameTable is empty, meanwhile readStringIndex can do the boundary
857     // check using the size of NameTable.
858     NameTable.resize(*Size + NameTable.size());
859 
860     MD5NameMemStart = Data;
861     Data = Data + (*Size) * sizeof(uint64_t);
862     return sampleprof_error::success;
863   }
864   NameTable.reserve(*Size);
865   for (uint32_t I = 0; I < *Size; ++I) {
866     auto FID = readNumber<uint64_t>();
867     if (std::error_code EC = FID.getError())
868       return EC;
869     MD5StringBuf->push_back(std::to_string(*FID));
870     // NameTable is a vector of StringRef. Here it is pushing back a
871     // StringRef initialized with the last string in MD5stringBuf.
872     NameTable.push_back(MD5StringBuf->back());
873   }
874   return sampleprof_error::success;
875 }
876 
877 std::error_code SampleProfileReaderExtBinaryBase::readNameTableSec(bool IsMD5) {
878   if (IsMD5)
879     return readMD5NameTable();
880   return SampleProfileReaderBinary::readNameTable();
881 }
882 
883 std::error_code SampleProfileReaderExtBinaryBase::readFuncMetadata() {
884   if (!ProfileIsProbeBased)
885     return sampleprof_error::success;
886   for (unsigned I = 0; I < Profiles.size(); ++I) {
887     auto FName(readStringFromTable());
888     if (std::error_code EC = FName.getError())
889       return EC;
890 
891     auto Checksum = readNumber<uint64_t>();
892     if (std::error_code EC = Checksum.getError())
893       return EC;
894 
895     SampleContext FContext(*FName);
896     Profiles[FContext].setFunctionHash(*Checksum);
897   }
898   return sampleprof_error::success;
899 }
900 
901 std::error_code SampleProfileReaderCompactBinary::readNameTable() {
902   auto Size = readNumber<uint64_t>();
903   if (std::error_code EC = Size.getError())
904     return EC;
905   NameTable.reserve(*Size);
906   for (uint32_t I = 0; I < *Size; ++I) {
907     auto FID = readNumber<uint64_t>();
908     if (std::error_code EC = FID.getError())
909       return EC;
910     NameTable.push_back(std::to_string(*FID));
911   }
912   return sampleprof_error::success;
913 }
914 
915 std::error_code
916 SampleProfileReaderExtBinaryBase::readSecHdrTableEntry(uint32_t Idx) {
917   SecHdrTableEntry Entry;
918   auto Type = readUnencodedNumber<uint64_t>();
919   if (std::error_code EC = Type.getError())
920     return EC;
921   Entry.Type = static_cast<SecType>(*Type);
922 
923   auto Flags = readUnencodedNumber<uint64_t>();
924   if (std::error_code EC = Flags.getError())
925     return EC;
926   Entry.Flags = *Flags;
927 
928   auto Offset = readUnencodedNumber<uint64_t>();
929   if (std::error_code EC = Offset.getError())
930     return EC;
931   Entry.Offset = *Offset;
932 
933   auto Size = readUnencodedNumber<uint64_t>();
934   if (std::error_code EC = Size.getError())
935     return EC;
936   Entry.Size = *Size;
937 
938   Entry.LayoutIndex = Idx;
939   SecHdrTable.push_back(std::move(Entry));
940   return sampleprof_error::success;
941 }
942 
943 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
944   auto EntryNum = readUnencodedNumber<uint64_t>();
945   if (std::error_code EC = EntryNum.getError())
946     return EC;
947 
948   for (uint32_t i = 0; i < (*EntryNum); i++)
949     if (std::error_code EC = readSecHdrTableEntry(i))
950       return EC;
951 
952   return sampleprof_error::success;
953 }
954 
955 std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
956   const uint8_t *BufStart =
957       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
958   Data = BufStart;
959   End = BufStart + Buffer->getBufferSize();
960 
961   if (std::error_code EC = readMagicIdent())
962     return EC;
963 
964   if (std::error_code EC = readSecHdrTable())
965     return EC;
966 
967   return sampleprof_error::success;
968 }
969 
970 uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
971   uint64_t Size = 0;
972   for (auto &Entry : SecHdrTable) {
973     if (Entry.Type == Type)
974       Size += Entry.Size;
975   }
976   return Size;
977 }
978 
979 uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
980   // Sections in SecHdrTable is not necessarily in the same order as
981   // sections in the profile because section like FuncOffsetTable needs
982   // to be written after section LBRProfile but needs to be read before
983   // section LBRProfile, so we cannot simply use the last entry in
984   // SecHdrTable to calculate the file size.
985   uint64_t FileSize = 0;
986   for (auto &Entry : SecHdrTable) {
987     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
988   }
989   return FileSize;
990 }
991 
992 static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
993   std::string Flags;
994   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
995     Flags.append("{compressed,");
996   else
997     Flags.append("{");
998 
999   if (hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
1000     Flags.append("flat,");
1001 
1002   switch (Entry.Type) {
1003   case SecNameTable:
1004     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5))
1005       Flags.append("fixlenmd5,");
1006     else if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
1007       Flags.append("md5,");
1008     break;
1009   case SecProfSummary:
1010     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
1011       Flags.append("partial,");
1012     break;
1013   default:
1014     break;
1015   }
1016   char &last = Flags.back();
1017   if (last == ',')
1018     last = '}';
1019   else
1020     Flags.append("}");
1021   return Flags;
1022 }
1023 
1024 bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
1025   uint64_t TotalSecsSize = 0;
1026   for (auto &Entry : SecHdrTable) {
1027     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1028        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1029        << "\n";
1030     ;
1031     TotalSecsSize += Entry.Size;
1032   }
1033   uint64_t HeaderSize = SecHdrTable.front().Offset;
1034   assert(HeaderSize + TotalSecsSize == getFileSize() &&
1035          "Size of 'header + sections' doesn't match the total size of profile");
1036 
1037   OS << "Header Size: " << HeaderSize << "\n";
1038   OS << "Total Sections Size: " << TotalSecsSize << "\n";
1039   OS << "File Size: " << getFileSize() << "\n";
1040   return true;
1041 }
1042 
1043 std::error_code SampleProfileReaderBinary::readMagicIdent() {
1044   // Read and check the magic identifier.
1045   auto Magic = readNumber<uint64_t>();
1046   if (std::error_code EC = Magic.getError())
1047     return EC;
1048   else if (std::error_code EC = verifySPMagic(*Magic))
1049     return EC;
1050 
1051   // Read the version number.
1052   auto Version = readNumber<uint64_t>();
1053   if (std::error_code EC = Version.getError())
1054     return EC;
1055   else if (*Version != SPVersion())
1056     return sampleprof_error::unsupported_version;
1057 
1058   return sampleprof_error::success;
1059 }
1060 
1061 std::error_code SampleProfileReaderBinary::readHeader() {
1062   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1063   End = Data + Buffer->getBufferSize();
1064 
1065   if (std::error_code EC = readMagicIdent())
1066     return EC;
1067 
1068   if (std::error_code EC = readSummary())
1069     return EC;
1070 
1071   if (std::error_code EC = readNameTable())
1072     return EC;
1073   return sampleprof_error::success;
1074 }
1075 
1076 std::error_code SampleProfileReaderCompactBinary::readHeader() {
1077   SampleProfileReaderBinary::readHeader();
1078   if (std::error_code EC = readFuncOffsetTable())
1079     return EC;
1080   return sampleprof_error::success;
1081 }
1082 
1083 std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
1084   auto TableOffset = readUnencodedNumber<uint64_t>();
1085   if (std::error_code EC = TableOffset.getError())
1086     return EC;
1087 
1088   const uint8_t *SavedData = Data;
1089   const uint8_t *TableStart =
1090       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
1091       *TableOffset;
1092   Data = TableStart;
1093 
1094   auto Size = readNumber<uint64_t>();
1095   if (std::error_code EC = Size.getError())
1096     return EC;
1097 
1098   FuncOffsetTable.reserve(*Size);
1099   for (uint32_t I = 0; I < *Size; ++I) {
1100     auto FName(readStringFromTable());
1101     if (std::error_code EC = FName.getError())
1102       return EC;
1103 
1104     auto Offset = readNumber<uint64_t>();
1105     if (std::error_code EC = Offset.getError())
1106       return EC;
1107 
1108     FuncOffsetTable[*FName] = *Offset;
1109   }
1110   End = TableStart;
1111   Data = SavedData;
1112   return sampleprof_error::success;
1113 }
1114 
1115 void SampleProfileReaderCompactBinary::collectFuncsFrom(const Module &M) {
1116   UseAllFuncs = false;
1117   FuncsToUse.clear();
1118   for (auto &F : M)
1119     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
1120 }
1121 
1122 std::error_code SampleProfileReaderBinary::readSummaryEntry(
1123     std::vector<ProfileSummaryEntry> &Entries) {
1124   auto Cutoff = readNumber<uint64_t>();
1125   if (std::error_code EC = Cutoff.getError())
1126     return EC;
1127 
1128   auto MinBlockCount = readNumber<uint64_t>();
1129   if (std::error_code EC = MinBlockCount.getError())
1130     return EC;
1131 
1132   auto NumBlocks = readNumber<uint64_t>();
1133   if (std::error_code EC = NumBlocks.getError())
1134     return EC;
1135 
1136   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
1137   return sampleprof_error::success;
1138 }
1139 
1140 std::error_code SampleProfileReaderBinary::readSummary() {
1141   auto TotalCount = readNumber<uint64_t>();
1142   if (std::error_code EC = TotalCount.getError())
1143     return EC;
1144 
1145   auto MaxBlockCount = readNumber<uint64_t>();
1146   if (std::error_code EC = MaxBlockCount.getError())
1147     return EC;
1148 
1149   auto MaxFunctionCount = readNumber<uint64_t>();
1150   if (std::error_code EC = MaxFunctionCount.getError())
1151     return EC;
1152 
1153   auto NumBlocks = readNumber<uint64_t>();
1154   if (std::error_code EC = NumBlocks.getError())
1155     return EC;
1156 
1157   auto NumFunctions = readNumber<uint64_t>();
1158   if (std::error_code EC = NumFunctions.getError())
1159     return EC;
1160 
1161   auto NumSummaryEntries = readNumber<uint64_t>();
1162   if (std::error_code EC = NumSummaryEntries.getError())
1163     return EC;
1164 
1165   std::vector<ProfileSummaryEntry> Entries;
1166   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
1167     std::error_code EC = readSummaryEntry(Entries);
1168     if (EC != sampleprof_error::success)
1169       return EC;
1170   }
1171   Summary = std::make_unique<ProfileSummary>(
1172       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
1173       *MaxFunctionCount, *NumBlocks, *NumFunctions);
1174 
1175   return sampleprof_error::success;
1176 }
1177 
1178 bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
1179   const uint8_t *Data =
1180       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1181   uint64_t Magic = decodeULEB128(Data);
1182   return Magic == SPMagic();
1183 }
1184 
1185 bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
1186   const uint8_t *Data =
1187       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1188   uint64_t Magic = decodeULEB128(Data);
1189   return Magic == SPMagic(SPF_Ext_Binary);
1190 }
1191 
1192 bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
1193   const uint8_t *Data =
1194       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1195   uint64_t Magic = decodeULEB128(Data);
1196   return Magic == SPMagic(SPF_Compact_Binary);
1197 }
1198 
1199 std::error_code SampleProfileReaderGCC::skipNextWord() {
1200   uint32_t dummy;
1201   if (!GcovBuffer.readInt(dummy))
1202     return sampleprof_error::truncated;
1203   return sampleprof_error::success;
1204 }
1205 
1206 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
1207   if (sizeof(T) <= sizeof(uint32_t)) {
1208     uint32_t Val;
1209     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
1210       return static_cast<T>(Val);
1211   } else if (sizeof(T) <= sizeof(uint64_t)) {
1212     uint64_t Val;
1213     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
1214       return static_cast<T>(Val);
1215   }
1216 
1217   std::error_code EC = sampleprof_error::malformed;
1218   reportError(0, EC.message());
1219   return EC;
1220 }
1221 
1222 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
1223   StringRef Str;
1224   if (!GcovBuffer.readString(Str))
1225     return sampleprof_error::truncated;
1226   return Str;
1227 }
1228 
1229 std::error_code SampleProfileReaderGCC::readHeader() {
1230   // Read the magic identifier.
1231   if (!GcovBuffer.readGCDAFormat())
1232     return sampleprof_error::unrecognized_format;
1233 
1234   // Read the version number. Note - the GCC reader does not validate this
1235   // version, but the profile creator generates v704.
1236   GCOV::GCOVVersion version;
1237   if (!GcovBuffer.readGCOVVersion(version))
1238     return sampleprof_error::unrecognized_format;
1239 
1240   if (version != GCOV::V407)
1241     return sampleprof_error::unsupported_version;
1242 
1243   // Skip the empty integer.
1244   if (std::error_code EC = skipNextWord())
1245     return EC;
1246 
1247   return sampleprof_error::success;
1248 }
1249 
1250 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
1251   uint32_t Tag;
1252   if (!GcovBuffer.readInt(Tag))
1253     return sampleprof_error::truncated;
1254 
1255   if (Tag != Expected)
1256     return sampleprof_error::malformed;
1257 
1258   if (std::error_code EC = skipNextWord())
1259     return EC;
1260 
1261   return sampleprof_error::success;
1262 }
1263 
1264 std::error_code SampleProfileReaderGCC::readNameTable() {
1265   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1266     return EC;
1267 
1268   uint32_t Size;
1269   if (!GcovBuffer.readInt(Size))
1270     return sampleprof_error::truncated;
1271 
1272   for (uint32_t I = 0; I < Size; ++I) {
1273     StringRef Str;
1274     if (!GcovBuffer.readString(Str))
1275       return sampleprof_error::truncated;
1276     Names.push_back(std::string(Str));
1277   }
1278 
1279   return sampleprof_error::success;
1280 }
1281 
1282 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
1283   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1284     return EC;
1285 
1286   uint32_t NumFunctions;
1287   if (!GcovBuffer.readInt(NumFunctions))
1288     return sampleprof_error::truncated;
1289 
1290   InlineCallStack Stack;
1291   for (uint32_t I = 0; I < NumFunctions; ++I)
1292     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1293       return EC;
1294 
1295   computeSummary();
1296   return sampleprof_error::success;
1297 }
1298 
1299 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1300     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1301   uint64_t HeadCount = 0;
1302   if (InlineStack.size() == 0)
1303     if (!GcovBuffer.readInt64(HeadCount))
1304       return sampleprof_error::truncated;
1305 
1306   uint32_t NameIdx;
1307   if (!GcovBuffer.readInt(NameIdx))
1308     return sampleprof_error::truncated;
1309 
1310   StringRef Name(Names[NameIdx]);
1311 
1312   uint32_t NumPosCounts;
1313   if (!GcovBuffer.readInt(NumPosCounts))
1314     return sampleprof_error::truncated;
1315 
1316   uint32_t NumCallsites;
1317   if (!GcovBuffer.readInt(NumCallsites))
1318     return sampleprof_error::truncated;
1319 
1320   FunctionSamples *FProfile = nullptr;
1321   if (InlineStack.size() == 0) {
1322     // If this is a top function that we have already processed, do not
1323     // update its profile again.  This happens in the presence of
1324     // function aliases.  Since these aliases share the same function
1325     // body, there will be identical replicated profiles for the
1326     // original function.  In this case, we simply not bother updating
1327     // the profile of the original function.
1328     FProfile = &Profiles[Name];
1329     FProfile->addHeadSamples(HeadCount);
1330     if (FProfile->getTotalSamples() > 0)
1331       Update = false;
1332   } else {
1333     // Otherwise, we are reading an inlined instance. The top of the
1334     // inline stack contains the profile of the caller. Insert this
1335     // callee in the caller's CallsiteMap.
1336     FunctionSamples *CallerProfile = InlineStack.front();
1337     uint32_t LineOffset = Offset >> 16;
1338     uint32_t Discriminator = Offset & 0xffff;
1339     FProfile = &CallerProfile->functionSamplesAt(
1340         LineLocation(LineOffset, Discriminator))[std::string(Name)];
1341   }
1342   FProfile->setName(Name);
1343 
1344   for (uint32_t I = 0; I < NumPosCounts; ++I) {
1345     uint32_t Offset;
1346     if (!GcovBuffer.readInt(Offset))
1347       return sampleprof_error::truncated;
1348 
1349     uint32_t NumTargets;
1350     if (!GcovBuffer.readInt(NumTargets))
1351       return sampleprof_error::truncated;
1352 
1353     uint64_t Count;
1354     if (!GcovBuffer.readInt64(Count))
1355       return sampleprof_error::truncated;
1356 
1357     // The line location is encoded in the offset as:
1358     //   high 16 bits: line offset to the start of the function.
1359     //   low 16 bits: discriminator.
1360     uint32_t LineOffset = Offset >> 16;
1361     uint32_t Discriminator = Offset & 0xffff;
1362 
1363     InlineCallStack NewStack;
1364     NewStack.push_back(FProfile);
1365     llvm::append_range(NewStack, InlineStack);
1366     if (Update) {
1367       // Walk up the inline stack, adding the samples on this line to
1368       // the total sample count of the callers in the chain.
1369       for (auto CallerProfile : NewStack)
1370         CallerProfile->addTotalSamples(Count);
1371 
1372       // Update the body samples for the current profile.
1373       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1374     }
1375 
1376     // Process the list of functions called at an indirect call site.
1377     // These are all the targets that a function pointer (or virtual
1378     // function) resolved at runtime.
1379     for (uint32_t J = 0; J < NumTargets; J++) {
1380       uint32_t HistVal;
1381       if (!GcovBuffer.readInt(HistVal))
1382         return sampleprof_error::truncated;
1383 
1384       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1385         return sampleprof_error::malformed;
1386 
1387       uint64_t TargetIdx;
1388       if (!GcovBuffer.readInt64(TargetIdx))
1389         return sampleprof_error::truncated;
1390       StringRef TargetName(Names[TargetIdx]);
1391 
1392       uint64_t TargetCount;
1393       if (!GcovBuffer.readInt64(TargetCount))
1394         return sampleprof_error::truncated;
1395 
1396       if (Update)
1397         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1398                                          TargetName, TargetCount);
1399     }
1400   }
1401 
1402   // Process all the inlined callers into the current function. These
1403   // are all the callsites that were inlined into this function.
1404   for (uint32_t I = 0; I < NumCallsites; I++) {
1405     // The offset is encoded as:
1406     //   high 16 bits: line offset to the start of the function.
1407     //   low 16 bits: discriminator.
1408     uint32_t Offset;
1409     if (!GcovBuffer.readInt(Offset))
1410       return sampleprof_error::truncated;
1411     InlineCallStack NewStack;
1412     NewStack.push_back(FProfile);
1413     llvm::append_range(NewStack, InlineStack);
1414     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1415       return EC;
1416   }
1417 
1418   return sampleprof_error::success;
1419 }
1420 
1421 /// Read a GCC AutoFDO profile.
1422 ///
1423 /// This format is generated by the Linux Perf conversion tool at
1424 /// https://github.com/google/autofdo.
1425 std::error_code SampleProfileReaderGCC::readImpl() {
1426   // Read the string table.
1427   if (std::error_code EC = readNameTable())
1428     return EC;
1429 
1430   // Read the source profile.
1431   if (std::error_code EC = readFunctionProfiles())
1432     return EC;
1433 
1434   return sampleprof_error::success;
1435 }
1436 
1437 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
1438   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
1439   return Magic == "adcg*704";
1440 }
1441 
1442 void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1443   // If the reader uses MD5 to represent string, we can't remap it because
1444   // we don't know what the original function names were.
1445   if (Reader.useMD5()) {
1446     Ctx.diagnose(DiagnosticInfoSampleProfile(
1447         Reader.getBuffer()->getBufferIdentifier(),
1448         "Profile data remapping cannot be applied to profile data "
1449         "in compact format (original mangled names are not available).",
1450         DS_Warning));
1451     return;
1452   }
1453 
1454   // CSSPGO-TODO: Remapper is not yet supported.
1455   // We will need to remap the entire context string.
1456   assert(Remappings && "should be initialized while creating remapper");
1457   for (auto &Sample : Reader.getProfiles()) {
1458     DenseSet<StringRef> NamesInSample;
1459     Sample.second.findAllNames(NamesInSample);
1460     for (auto &Name : NamesInSample)
1461       if (auto Key = Remappings->insert(Name))
1462         NameMap.insert({Key, Name});
1463   }
1464 
1465   RemappingApplied = true;
1466 }
1467 
1468 Optional<StringRef>
1469 SampleProfileReaderItaniumRemapper::lookUpNameInProfile(StringRef Fname) {
1470   if (auto Key = Remappings->lookup(Fname))
1471     return NameMap.lookup(Key);
1472   return None;
1473 }
1474 
1475 /// Prepare a memory buffer for the contents of \p Filename.
1476 ///
1477 /// \returns an error code indicating the status of the buffer.
1478 static ErrorOr<std::unique_ptr<MemoryBuffer>>
1479 setupMemoryBuffer(const Twine &Filename) {
1480   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
1481   if (std::error_code EC = BufferOrErr.getError())
1482     return EC;
1483   auto Buffer = std::move(BufferOrErr.get());
1484 
1485   // Sanity check the file.
1486   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1487     return sampleprof_error::too_large;
1488 
1489   return std::move(Buffer);
1490 }
1491 
1492 /// Create a sample profile reader based on the format of the input file.
1493 ///
1494 /// \param Filename The file to open.
1495 ///
1496 /// \param C The LLVM context to use to emit diagnostics.
1497 ///
1498 /// \param RemapFilename The file used for profile remapping.
1499 ///
1500 /// \returns an error code indicating the status of the created reader.
1501 ErrorOr<std::unique_ptr<SampleProfileReader>>
1502 SampleProfileReader::create(const std::string Filename, LLVMContext &C,
1503                             const std::string RemapFilename) {
1504   auto BufferOrError = setupMemoryBuffer(Filename);
1505   if (std::error_code EC = BufferOrError.getError())
1506     return EC;
1507   return create(BufferOrError.get(), C, RemapFilename);
1508 }
1509 
1510 /// Create a sample profile remapper from the given input, to remap the
1511 /// function names in the given profile data.
1512 ///
1513 /// \param Filename The file to open.
1514 ///
1515 /// \param Reader The profile reader the remapper is going to be applied to.
1516 ///
1517 /// \param C The LLVM context to use to emit diagnostics.
1518 ///
1519 /// \returns an error code indicating the status of the created reader.
1520 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1521 SampleProfileReaderItaniumRemapper::create(const std::string Filename,
1522                                            SampleProfileReader &Reader,
1523                                            LLVMContext &C) {
1524   auto BufferOrError = setupMemoryBuffer(Filename);
1525   if (std::error_code EC = BufferOrError.getError())
1526     return EC;
1527   return create(BufferOrError.get(), Reader, C);
1528 }
1529 
1530 /// Create a sample profile remapper from the given input, to remap the
1531 /// function names in the given profile data.
1532 ///
1533 /// \param B The memory buffer to create the reader from (assumes ownership).
1534 ///
1535 /// \param C The LLVM context to use to emit diagnostics.
1536 ///
1537 /// \param Reader The profile reader the remapper is going to be applied to.
1538 ///
1539 /// \returns an error code indicating the status of the created reader.
1540 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1541 SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
1542                                            SampleProfileReader &Reader,
1543                                            LLVMContext &C) {
1544   auto Remappings = std::make_unique<SymbolRemappingReader>();
1545   if (Error E = Remappings->read(*B.get())) {
1546     handleAllErrors(
1547         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
1548           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
1549                                                  ParseError.getLineNum(),
1550                                                  ParseError.getMessage()));
1551         });
1552     return sampleprof_error::malformed;
1553   }
1554 
1555   return std::make_unique<SampleProfileReaderItaniumRemapper>(
1556       std::move(B), std::move(Remappings), Reader);
1557 }
1558 
1559 /// Create a sample profile reader based on the format of the input data.
1560 ///
1561 /// \param B The memory buffer to create the reader from (assumes ownership).
1562 ///
1563 /// \param C The LLVM context to use to emit diagnostics.
1564 ///
1565 /// \param RemapFilename The file used for profile remapping.
1566 ///
1567 /// \returns an error code indicating the status of the created reader.
1568 ErrorOr<std::unique_ptr<SampleProfileReader>>
1569 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
1570                             const std::string RemapFilename) {
1571   std::unique_ptr<SampleProfileReader> Reader;
1572   if (SampleProfileReaderRawBinary::hasFormat(*B))
1573     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1574   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1575     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1576   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1577     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
1578   else if (SampleProfileReaderGCC::hasFormat(*B))
1579     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1580   else if (SampleProfileReaderText::hasFormat(*B))
1581     Reader.reset(new SampleProfileReaderText(std::move(B), C));
1582   else
1583     return sampleprof_error::unrecognized_format;
1584 
1585   if (!RemapFilename.empty()) {
1586     auto ReaderOrErr =
1587         SampleProfileReaderItaniumRemapper::create(RemapFilename, *Reader, C);
1588     if (std::error_code EC = ReaderOrErr.getError()) {
1589       std::string Msg = "Could not create remapper: " + EC.message();
1590       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
1591       return EC;
1592     }
1593     Reader->Remapper = std::move(ReaderOrErr.get());
1594   }
1595 
1596   FunctionSamples::Format = Reader->getFormat();
1597   if (std::error_code EC = Reader->readHeader()) {
1598     return EC;
1599   }
1600 
1601   return std::move(Reader);
1602 }
1603 
1604 // For text and GCC file formats, we compute the summary after reading the
1605 // profile. Binary format has the profile summary in its header.
1606 void SampleProfileReader::computeSummary() {
1607   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1608   for (const auto &I : Profiles) {
1609     const FunctionSamples &Profile = I.second;
1610     Builder.addRecord(Profile);
1611   }
1612   Summary = Builder.getSummary();
1613 }
1614