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