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