1de1ab26fSDiego Novillo //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2de1ab26fSDiego Novillo //
3de1ab26fSDiego Novillo //                      The LLVM Compiler Infrastructure
4de1ab26fSDiego Novillo //
5de1ab26fSDiego Novillo // This file is distributed under the University of Illinois Open Source
6de1ab26fSDiego Novillo // License. See LICENSE.TXT for details.
7de1ab26fSDiego Novillo //
8de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
9de1ab26fSDiego Novillo //
10de1ab26fSDiego Novillo // This file implements the class that reads LLVM sample profiles. It
11bb5605caSDiego Novillo // supports three file formats: text, binary and gcov.
12de1ab26fSDiego Novillo //
13bb5605caSDiego Novillo // The textual representation is useful for debugging and testing purposes. The
14bb5605caSDiego Novillo // binary representation is more compact, resulting in smaller file sizes.
15de1ab26fSDiego Novillo //
16bb5605caSDiego Novillo // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17bb5605caSDiego Novillo // tool (https://github.com/google/autofdo)
18de1ab26fSDiego Novillo //
19bb5605caSDiego Novillo // All three encodings can be used interchangeably as an input sample profile.
20de1ab26fSDiego Novillo //
21de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
22de1ab26fSDiego Novillo 
23de1ab26fSDiego Novillo #include "llvm/ProfileData/SampleProfReader.h"
24b93483dbSDiego Novillo #include "llvm/ADT/DenseMap.h"
25*40ee23dbSEaswaran Raman #include "llvm/ADT/STLExtras.h"
26b93483dbSDiego Novillo #include "llvm/ADT/SmallVector.h"
27de1ab26fSDiego Novillo #include "llvm/Support/Debug.h"
28de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
29c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
30de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
31c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
32de1ab26fSDiego Novillo 
33c572e92cSDiego Novillo using namespace llvm::sampleprof;
34de1ab26fSDiego Novillo using namespace llvm;
35de1ab26fSDiego Novillo 
36de1ab26fSDiego Novillo /// \brief Dump the function profile for \p FName.
37de1ab26fSDiego Novillo ///
38de1ab26fSDiego Novillo /// \param FName Name of the function to print.
39d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
40d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
41d5336ae2SDiego Novillo                                               raw_ostream &OS) {
428e415a82SDiego Novillo   OS << "Function: " << FName << ": " << Profiles[FName];
43de1ab26fSDiego Novillo }
44de1ab26fSDiego Novillo 
45d5336ae2SDiego Novillo /// \brief Dump all the function profiles found on stream \p OS.
46d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
47d5336ae2SDiego Novillo   for (const auto &I : Profiles)
48d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
49de1ab26fSDiego Novillo }
50de1ab26fSDiego Novillo 
516722688eSDehao Chen /// \brief Parse \p Input as function head.
526722688eSDehao Chen ///
536722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
546722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
556722688eSDehao Chen /// count in \p NumHeadSamples.
566722688eSDehao Chen ///
576722688eSDehao Chen /// \returns true if parsing is successful.
586722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
5938be3330SDiego Novillo                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
606722688eSDehao Chen   if (Input[0] == ' ')
616722688eSDehao Chen     return false;
626722688eSDehao Chen   size_t n2 = Input.rfind(':');
636722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
646722688eSDehao Chen   FName = Input.substr(0, n1);
656722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
666722688eSDehao Chen     return false;
676722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
686722688eSDehao Chen     return false;
696722688eSDehao Chen   return true;
706722688eSDehao Chen }
716722688eSDehao Chen 
7210042412SDehao Chen 
7310042412SDehao Chen /// \brief Returns true if line offset \p L is legal (only has 16 bits).
7410042412SDehao Chen static bool isOffsetLegal(unsigned L) {
7510042412SDehao Chen   return (L & 0xffff) == L;
7610042412SDehao Chen }
7710042412SDehao Chen 
786722688eSDehao Chen /// \brief Parse \p Input as line sample.
796722688eSDehao Chen ///
806722688eSDehao Chen /// \param Input input line.
816722688eSDehao Chen /// \param IsCallsite true if the line represents an inlined callsite.
826722688eSDehao Chen /// \param Depth the depth of the inline stack.
836722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
846722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
856722688eSDehao Chen /// \param Discriminator discriminator of the line.
866722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
876722688eSDehao Chen ///
886722688eSDehao Chen /// returns true if parsing is successful.
8938be3330SDiego Novillo static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
9038be3330SDiego Novillo                       uint64_t &NumSamples, uint32_t &LineOffset,
9138be3330SDiego Novillo                       uint32_t &Discriminator, StringRef &CalleeName,
9238be3330SDiego Novillo                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
936722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
946722688eSDehao Chen     ;
956722688eSDehao Chen   if (Depth == 0)
966722688eSDehao Chen     return false;
976722688eSDehao Chen 
986722688eSDehao Chen   size_t n1 = Input.find(':');
996722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
1006722688eSDehao Chen   size_t n2 = Loc.find('.');
1016722688eSDehao Chen   if (n2 == StringRef::npos) {
10210042412SDehao Chen     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
1036722688eSDehao Chen       return false;
1046722688eSDehao Chen     Discriminator = 0;
1056722688eSDehao Chen   } else {
1066722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
1076722688eSDehao Chen       return false;
1086722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
1096722688eSDehao Chen       return false;
1106722688eSDehao Chen   }
1116722688eSDehao Chen 
1126722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
1136722688eSDehao Chen   if (Rest[0] >= '0' && Rest[0] <= '9') {
1146722688eSDehao Chen     IsCallsite = false;
1156722688eSDehao Chen     size_t n3 = Rest.find(' ');
1166722688eSDehao Chen     if (n3 == StringRef::npos) {
1176722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
1186722688eSDehao Chen         return false;
1196722688eSDehao Chen     } else {
1206722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
1216722688eSDehao Chen         return false;
1226722688eSDehao Chen     }
1236722688eSDehao Chen     while (n3 != StringRef::npos) {
1246722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
1256722688eSDehao Chen       Rest = Rest.substr(n3);
1266722688eSDehao Chen       n3 = Rest.find(' ');
1276722688eSDehao Chen       StringRef pair = Rest;
1286722688eSDehao Chen       if (n3 != StringRef::npos) {
1296722688eSDehao Chen         pair = Rest.substr(0, n3);
1306722688eSDehao Chen       }
13138be3330SDiego Novillo       size_t n4 = pair.find(':');
13238be3330SDiego Novillo       uint64_t count;
1336722688eSDehao Chen       if (pair.substr(n4 + 1).getAsInteger(10, count))
1346722688eSDehao Chen         return false;
1356722688eSDehao Chen       TargetCountMap[pair.substr(0, n4)] = count;
1366722688eSDehao Chen     }
1376722688eSDehao Chen   } else {
1386722688eSDehao Chen     IsCallsite = true;
13938be3330SDiego Novillo     size_t n3 = Rest.find_last_of(':');
1406722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
1416722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
1426722688eSDehao Chen       return false;
1436722688eSDehao Chen   }
1446722688eSDehao Chen   return true;
1456722688eSDehao Chen }
1466722688eSDehao Chen 
147de1ab26fSDiego Novillo /// \brief Load samples from a text file.
148de1ab26fSDiego Novillo ///
149de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
150de1ab26fSDiego Novillo /// the expected format.
151de1ab26fSDiego Novillo ///
152de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
153c572e92cSDiego Novillo std::error_code SampleProfileReaderText::read() {
154c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
15548dd080cSNathan Slingerland   sampleprof_error Result = sampleprof_error::success;
156de1ab26fSDiego Novillo 
157aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
1586722688eSDehao Chen 
1596722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
1606722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
1616722688eSDehao Chen       continue;
162de1ab26fSDiego Novillo     // Read the header of each function.
163de1ab26fSDiego Novillo     //
164de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
165de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
166de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
167de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
168de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
169de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
170de1ab26fSDiego Novillo     // name (member functions, templates, etc).
171de1ab26fSDiego Novillo     //
172de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
173de1ab26fSDiego Novillo     // should not begin with a number.
1746722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
17538be3330SDiego Novillo       uint64_t NumSamples, NumHeadSamples;
1766722688eSDehao Chen       StringRef FName;
1776722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
1783376a787SDiego Novillo         reportError(LineIt.line_number(),
179de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
180c572e92cSDiego Novillo         return sampleprof_error::malformed;
181de1ab26fSDiego Novillo       }
182de1ab26fSDiego Novillo       Profiles[FName] = FunctionSamples();
183de1ab26fSDiego Novillo       FunctionSamples &FProfile = Profiles[FName];
18448dd080cSNathan Slingerland       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
18548dd080cSNathan Slingerland       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
1866722688eSDehao Chen       InlineStack.clear();
1876722688eSDehao Chen       InlineStack.push_back(&FProfile);
1886722688eSDehao Chen     } else {
18938be3330SDiego Novillo       uint64_t NumSamples;
1906722688eSDehao Chen       StringRef FName;
19138be3330SDiego Novillo       DenseMap<StringRef, uint64_t> TargetCountMap;
1926722688eSDehao Chen       bool IsCallsite;
19338be3330SDiego Novillo       uint32_t Depth, LineOffset, Discriminator;
1946722688eSDehao Chen       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
1956722688eSDehao Chen                      Discriminator, FName, TargetCountMap)) {
1963376a787SDiego Novillo         reportError(LineIt.line_number(),
1973376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
1983376a787SDiego Novillo                         *LineIt);
199c572e92cSDiego Novillo         return sampleprof_error::malformed;
200de1ab26fSDiego Novillo       }
2016722688eSDehao Chen       if (IsCallsite) {
2026722688eSDehao Chen         while (InlineStack.size() > Depth) {
2036722688eSDehao Chen           InlineStack.pop_back();
204c572e92cSDiego Novillo         }
2056722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
2066722688eSDehao Chen             CallsiteLocation(LineOffset, Discriminator, FName));
20748dd080cSNathan Slingerland         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
2086722688eSDehao Chen         InlineStack.push_back(&FSamples);
2096722688eSDehao Chen       } else {
2106722688eSDehao Chen         while (InlineStack.size() > Depth) {
2116722688eSDehao Chen           InlineStack.pop_back();
2126722688eSDehao Chen         }
2136722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
2146722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
21548dd080cSNathan Slingerland           MergeResult(Result, FProfile.addCalledTargetSamples(
21648dd080cSNathan Slingerland                                   LineOffset, Discriminator, name_count.first,
21748dd080cSNathan Slingerland                                   name_count.second));
218c572e92cSDiego Novillo         }
21948dd080cSNathan Slingerland         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
22048dd080cSNathan Slingerland                                                     NumSamples));
2216722688eSDehao Chen       }
222de1ab26fSDiego Novillo     }
223de1ab26fSDiego Novillo   }
224*40ee23dbSEaswaran Raman   if (Result == sampleprof_error::success)
225*40ee23dbSEaswaran Raman     computeSummary();
226de1ab26fSDiego Novillo 
22748dd080cSNathan Slingerland   return Result;
228de1ab26fSDiego Novillo }
229de1ab26fSDiego Novillo 
2304f823667SNathan Slingerland bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
2314f823667SNathan Slingerland   bool result = false;
2324f823667SNathan Slingerland 
2334f823667SNathan Slingerland   // Check that the first non-comment line is a valid function header.
2344f823667SNathan Slingerland   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
2354f823667SNathan Slingerland   if (!LineIt.is_at_eof()) {
2364f823667SNathan Slingerland     if ((*LineIt)[0] != ' ') {
2374f823667SNathan Slingerland       uint64_t NumSamples, NumHeadSamples;
2384f823667SNathan Slingerland       StringRef FName;
2394f823667SNathan Slingerland       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
2404f823667SNathan Slingerland     }
2414f823667SNathan Slingerland   }
2424f823667SNathan Slingerland 
2434f823667SNathan Slingerland   return result;
2444f823667SNathan Slingerland }
2454f823667SNathan Slingerland 
246d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
247c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
248c572e92cSDiego Novillo   std::error_code EC;
249c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
250c572e92cSDiego Novillo 
251c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
252c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
253c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
254c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
255c572e92cSDiego Novillo   else
256c572e92cSDiego Novillo     EC = sampleprof_error::success;
257c572e92cSDiego Novillo 
258c572e92cSDiego Novillo   if (EC) {
2593376a787SDiego Novillo     reportError(0, EC.message());
260c572e92cSDiego Novillo     return EC;
261c572e92cSDiego Novillo   }
262c572e92cSDiego Novillo 
263c572e92cSDiego Novillo   Data += NumBytesRead;
264c572e92cSDiego Novillo   return static_cast<T>(Val);
265c572e92cSDiego Novillo }
266c572e92cSDiego Novillo 
267c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
268c572e92cSDiego Novillo   std::error_code EC;
269c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
270c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
271c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
2723376a787SDiego Novillo     reportError(0, EC.message());
273c572e92cSDiego Novillo     return EC;
274c572e92cSDiego Novillo   }
275c572e92cSDiego Novillo 
276c572e92cSDiego Novillo   Data += Str.size() + 1;
277c572e92cSDiego Novillo   return Str;
278c572e92cSDiego Novillo }
279c572e92cSDiego Novillo 
280760c5a8fSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
281760c5a8fSDiego Novillo   std::error_code EC;
28238be3330SDiego Novillo   auto Idx = readNumber<uint32_t>();
283760c5a8fSDiego Novillo   if (std::error_code EC = Idx.getError())
284760c5a8fSDiego Novillo     return EC;
285760c5a8fSDiego Novillo   if (*Idx >= NameTable.size())
286760c5a8fSDiego Novillo     return sampleprof_error::truncated_name_table;
287760c5a8fSDiego Novillo   return NameTable[*Idx];
288760c5a8fSDiego Novillo }
289760c5a8fSDiego Novillo 
290a7f1e8efSDiego Novillo std::error_code
291a7f1e8efSDiego Novillo SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
292b93483dbSDiego Novillo   auto NumSamples = readNumber<uint64_t>();
293b93483dbSDiego Novillo   if (std::error_code EC = NumSamples.getError())
294c572e92cSDiego Novillo     return EC;
295b93483dbSDiego Novillo   FProfile.addTotalSamples(*NumSamples);
296c572e92cSDiego Novillo 
297c572e92cSDiego Novillo   // Read the samples in the body.
29838be3330SDiego Novillo   auto NumRecords = readNumber<uint32_t>();
299c572e92cSDiego Novillo   if (std::error_code EC = NumRecords.getError())
300c572e92cSDiego Novillo     return EC;
301a7f1e8efSDiego Novillo 
30238be3330SDiego Novillo   for (uint32_t I = 0; I < *NumRecords; ++I) {
303c572e92cSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
304c572e92cSDiego Novillo     if (std::error_code EC = LineOffset.getError())
305c572e92cSDiego Novillo       return EC;
306c572e92cSDiego Novillo 
30710042412SDehao Chen     if (!isOffsetLegal(*LineOffset)) {
30810042412SDehao Chen       return std::error_code();
30910042412SDehao Chen     }
31010042412SDehao Chen 
311c572e92cSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
312c572e92cSDiego Novillo     if (std::error_code EC = Discriminator.getError())
313c572e92cSDiego Novillo       return EC;
314c572e92cSDiego Novillo 
315c572e92cSDiego Novillo     auto NumSamples = readNumber<uint64_t>();
316c572e92cSDiego Novillo     if (std::error_code EC = NumSamples.getError())
317c572e92cSDiego Novillo       return EC;
318c572e92cSDiego Novillo 
31938be3330SDiego Novillo     auto NumCalls = readNumber<uint32_t>();
320c572e92cSDiego Novillo     if (std::error_code EC = NumCalls.getError())
321c572e92cSDiego Novillo       return EC;
322c572e92cSDiego Novillo 
32338be3330SDiego Novillo     for (uint32_t J = 0; J < *NumCalls; ++J) {
324760c5a8fSDiego Novillo       auto CalledFunction(readStringFromTable());
325c572e92cSDiego Novillo       if (std::error_code EC = CalledFunction.getError())
326c572e92cSDiego Novillo         return EC;
327c572e92cSDiego Novillo 
328c572e92cSDiego Novillo       auto CalledFunctionSamples = readNumber<uint64_t>();
329c572e92cSDiego Novillo       if (std::error_code EC = CalledFunctionSamples.getError())
330c572e92cSDiego Novillo         return EC;
331c572e92cSDiego Novillo 
332c572e92cSDiego Novillo       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
333a7f1e8efSDiego Novillo                                       *CalledFunction, *CalledFunctionSamples);
334c572e92cSDiego Novillo     }
335c572e92cSDiego Novillo 
336c572e92cSDiego Novillo     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
337c572e92cSDiego Novillo   }
338a7f1e8efSDiego Novillo 
339a7f1e8efSDiego Novillo   // Read all the samples for inlined function calls.
34038be3330SDiego Novillo   auto NumCallsites = readNumber<uint32_t>();
341a7f1e8efSDiego Novillo   if (std::error_code EC = NumCallsites.getError())
342a7f1e8efSDiego Novillo     return EC;
343a7f1e8efSDiego Novillo 
34438be3330SDiego Novillo   for (uint32_t J = 0; J < *NumCallsites; ++J) {
345a7f1e8efSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
346a7f1e8efSDiego Novillo     if (std::error_code EC = LineOffset.getError())
347a7f1e8efSDiego Novillo       return EC;
348a7f1e8efSDiego Novillo 
349a7f1e8efSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
350a7f1e8efSDiego Novillo     if (std::error_code EC = Discriminator.getError())
351a7f1e8efSDiego Novillo       return EC;
352a7f1e8efSDiego Novillo 
353760c5a8fSDiego Novillo     auto FName(readStringFromTable());
354a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
355a7f1e8efSDiego Novillo       return EC;
356a7f1e8efSDiego Novillo 
357a7f1e8efSDiego Novillo     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
358a7f1e8efSDiego Novillo         CallsiteLocation(*LineOffset, *Discriminator, *FName));
359a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(CalleeProfile))
360a7f1e8efSDiego Novillo       return EC;
361a7f1e8efSDiego Novillo   }
362a7f1e8efSDiego Novillo 
363a7f1e8efSDiego Novillo   return sampleprof_error::success;
364a7f1e8efSDiego Novillo }
365a7f1e8efSDiego Novillo 
366a7f1e8efSDiego Novillo std::error_code SampleProfileReaderBinary::read() {
367a7f1e8efSDiego Novillo   while (!at_eof()) {
368b93483dbSDiego Novillo     auto NumHeadSamples = readNumber<uint64_t>();
369b93483dbSDiego Novillo     if (std::error_code EC = NumHeadSamples.getError())
370b93483dbSDiego Novillo       return EC;
371b93483dbSDiego Novillo 
372760c5a8fSDiego Novillo     auto FName(readStringFromTable());
373a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
374a7f1e8efSDiego Novillo       return EC;
375a7f1e8efSDiego Novillo 
376a7f1e8efSDiego Novillo     Profiles[*FName] = FunctionSamples();
377a7f1e8efSDiego Novillo     FunctionSamples &FProfile = Profiles[*FName];
378a7f1e8efSDiego Novillo 
379b93483dbSDiego Novillo     FProfile.addHeadSamples(*NumHeadSamples);
380b93483dbSDiego Novillo 
381a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(FProfile))
382a7f1e8efSDiego Novillo       return EC;
383c572e92cSDiego Novillo   }
384c572e92cSDiego Novillo 
385c572e92cSDiego Novillo   return sampleprof_error::success;
386c572e92cSDiego Novillo }
387c572e92cSDiego Novillo 
388c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::readHeader() {
389c572e92cSDiego Novillo   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
390c572e92cSDiego Novillo   End = Data + Buffer->getBufferSize();
391c572e92cSDiego Novillo 
392c572e92cSDiego Novillo   // Read and check the magic identifier.
393c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
394c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
395c572e92cSDiego Novillo     return EC;
396c572e92cSDiego Novillo   else if (*Magic != SPMagic())
397c572e92cSDiego Novillo     return sampleprof_error::bad_magic;
398c572e92cSDiego Novillo 
399c572e92cSDiego Novillo   // Read the version number.
400c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
401c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
402c572e92cSDiego Novillo     return EC;
403c572e92cSDiego Novillo   else if (*Version != SPVersion())
404c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
405c572e92cSDiego Novillo 
406*40ee23dbSEaswaran Raman   if (std::error_code EC = readSummary())
407*40ee23dbSEaswaran Raman     return EC;
408*40ee23dbSEaswaran Raman 
409760c5a8fSDiego Novillo   // Read the name table.
41038be3330SDiego Novillo   auto Size = readNumber<uint32_t>();
411760c5a8fSDiego Novillo   if (std::error_code EC = Size.getError())
412760c5a8fSDiego Novillo     return EC;
413760c5a8fSDiego Novillo   NameTable.reserve(*Size);
41438be3330SDiego Novillo   for (uint32_t I = 0; I < *Size; ++I) {
415760c5a8fSDiego Novillo     auto Name(readString());
416760c5a8fSDiego Novillo     if (std::error_code EC = Name.getError())
417760c5a8fSDiego Novillo       return EC;
418760c5a8fSDiego Novillo     NameTable.push_back(*Name);
419760c5a8fSDiego Novillo   }
420760c5a8fSDiego Novillo 
421c572e92cSDiego Novillo   return sampleprof_error::success;
422c572e92cSDiego Novillo }
423c572e92cSDiego Novillo 
424*40ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummaryEntry(
425*40ee23dbSEaswaran Raman     std::vector<ProfileSummaryEntry> &Entries) {
426*40ee23dbSEaswaran Raman   auto Cutoff = readNumber<uint64_t>();
427*40ee23dbSEaswaran Raman   if (std::error_code EC = Cutoff.getError())
428*40ee23dbSEaswaran Raman     return EC;
429*40ee23dbSEaswaran Raman 
430*40ee23dbSEaswaran Raman   auto MinBlockCount = readNumber<uint64_t>();
431*40ee23dbSEaswaran Raman   if (std::error_code EC = MinBlockCount.getError())
432*40ee23dbSEaswaran Raman     return EC;
433*40ee23dbSEaswaran Raman 
434*40ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
435*40ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
436*40ee23dbSEaswaran Raman     return EC;
437*40ee23dbSEaswaran Raman 
438*40ee23dbSEaswaran Raman   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
439*40ee23dbSEaswaran Raman   return sampleprof_error::success;
440*40ee23dbSEaswaran Raman }
441*40ee23dbSEaswaran Raman 
442*40ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummary() {
443*40ee23dbSEaswaran Raman   auto TotalCount = readNumber<uint64_t>();
444*40ee23dbSEaswaran Raman   if (std::error_code EC = TotalCount.getError())
445*40ee23dbSEaswaran Raman     return EC;
446*40ee23dbSEaswaran Raman 
447*40ee23dbSEaswaran Raman   auto MaxBlockCount = readNumber<uint64_t>();
448*40ee23dbSEaswaran Raman   if (std::error_code EC = MaxBlockCount.getError())
449*40ee23dbSEaswaran Raman     return EC;
450*40ee23dbSEaswaran Raman 
451*40ee23dbSEaswaran Raman   auto MaxFunctionCount = readNumber<uint64_t>();
452*40ee23dbSEaswaran Raman   if (std::error_code EC = MaxFunctionCount.getError())
453*40ee23dbSEaswaran Raman     return EC;
454*40ee23dbSEaswaran Raman 
455*40ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
456*40ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
457*40ee23dbSEaswaran Raman     return EC;
458*40ee23dbSEaswaran Raman 
459*40ee23dbSEaswaran Raman   auto NumFunctions = readNumber<uint64_t>();
460*40ee23dbSEaswaran Raman   if (std::error_code EC = NumFunctions.getError())
461*40ee23dbSEaswaran Raman     return EC;
462*40ee23dbSEaswaran Raman 
463*40ee23dbSEaswaran Raman   auto NumSummaryEntries = readNumber<uint64_t>();
464*40ee23dbSEaswaran Raman   if (std::error_code EC = NumSummaryEntries.getError())
465*40ee23dbSEaswaran Raman     return EC;
466*40ee23dbSEaswaran Raman 
467*40ee23dbSEaswaran Raman   std::vector<ProfileSummaryEntry> Entries;
468*40ee23dbSEaswaran Raman   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
469*40ee23dbSEaswaran Raman     std::error_code EC = readSummaryEntry(Entries);
470*40ee23dbSEaswaran Raman     if (EC != sampleprof_error::success)
471*40ee23dbSEaswaran Raman       return EC;
472*40ee23dbSEaswaran Raman   }
473*40ee23dbSEaswaran Raman   Summary = llvm::make_unique<SampleProfileSummary>(
474*40ee23dbSEaswaran Raman       *TotalCount, *MaxBlockCount, *MaxFunctionCount, *NumBlocks, *NumFunctions,
475*40ee23dbSEaswaran Raman       Entries);
476*40ee23dbSEaswaran Raman 
477*40ee23dbSEaswaran Raman   return sampleprof_error::success;
478*40ee23dbSEaswaran Raman }
479*40ee23dbSEaswaran Raman 
480c572e92cSDiego Novillo bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
481c572e92cSDiego Novillo   const uint8_t *Data =
482c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
483c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
484c572e92cSDiego Novillo   return Magic == SPMagic();
485c572e92cSDiego Novillo }
486c572e92cSDiego Novillo 
4873376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
4883376a787SDiego Novillo   uint32_t dummy;
4893376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
4903376a787SDiego Novillo     return sampleprof_error::truncated;
4913376a787SDiego Novillo   return sampleprof_error::success;
4923376a787SDiego Novillo }
4933376a787SDiego Novillo 
4943376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
4953376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
4963376a787SDiego Novillo     uint32_t Val;
4973376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
4983376a787SDiego Novillo       return static_cast<T>(Val);
4993376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
5003376a787SDiego Novillo     uint64_t Val;
5013376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
5023376a787SDiego Novillo       return static_cast<T>(Val);
5033376a787SDiego Novillo   }
5043376a787SDiego Novillo 
5053376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
5063376a787SDiego Novillo   reportError(0, EC.message());
5073376a787SDiego Novillo   return EC;
5083376a787SDiego Novillo }
5093376a787SDiego Novillo 
5103376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
5113376a787SDiego Novillo   StringRef Str;
5123376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
5133376a787SDiego Novillo     return sampleprof_error::truncated;
5143376a787SDiego Novillo   return Str;
5153376a787SDiego Novillo }
5163376a787SDiego Novillo 
5173376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
5183376a787SDiego Novillo   // Read the magic identifier.
5193376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
5203376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
5213376a787SDiego Novillo 
5223376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
5233376a787SDiego Novillo   // version, but the profile creator generates v704.
5243376a787SDiego Novillo   GCOV::GCOVVersion version;
5253376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
5263376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
5273376a787SDiego Novillo 
5283376a787SDiego Novillo   if (version != GCOV::V704)
5293376a787SDiego Novillo     return sampleprof_error::unsupported_version;
5303376a787SDiego Novillo 
5313376a787SDiego Novillo   // Skip the empty integer.
5323376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
5333376a787SDiego Novillo     return EC;
5343376a787SDiego Novillo 
5353376a787SDiego Novillo   return sampleprof_error::success;
5363376a787SDiego Novillo }
5373376a787SDiego Novillo 
5383376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
5393376a787SDiego Novillo   uint32_t Tag;
5403376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
5413376a787SDiego Novillo     return sampleprof_error::truncated;
5423376a787SDiego Novillo 
5433376a787SDiego Novillo   if (Tag != Expected)
5443376a787SDiego Novillo     return sampleprof_error::malformed;
5453376a787SDiego Novillo 
5463376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
5473376a787SDiego Novillo     return EC;
5483376a787SDiego Novillo 
5493376a787SDiego Novillo   return sampleprof_error::success;
5503376a787SDiego Novillo }
5513376a787SDiego Novillo 
5523376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
5533376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
5543376a787SDiego Novillo     return EC;
5553376a787SDiego Novillo 
5563376a787SDiego Novillo   uint32_t Size;
5573376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
5583376a787SDiego Novillo     return sampleprof_error::truncated;
5593376a787SDiego Novillo 
5603376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
5613376a787SDiego Novillo     StringRef Str;
5623376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
5633376a787SDiego Novillo       return sampleprof_error::truncated;
5643376a787SDiego Novillo     Names.push_back(Str);
5653376a787SDiego Novillo   }
5663376a787SDiego Novillo 
5673376a787SDiego Novillo   return sampleprof_error::success;
5683376a787SDiego Novillo }
5693376a787SDiego Novillo 
5703376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
5713376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
5723376a787SDiego Novillo     return EC;
5733376a787SDiego Novillo 
5743376a787SDiego Novillo   uint32_t NumFunctions;
5753376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
5763376a787SDiego Novillo     return sampleprof_error::truncated;
5773376a787SDiego Novillo 
578aae1ed8eSDiego Novillo   InlineCallStack Stack;
5793376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
580aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
5813376a787SDiego Novillo       return EC;
5823376a787SDiego Novillo 
583*40ee23dbSEaswaran Raman   computeSummary();
5843376a787SDiego Novillo   return sampleprof_error::success;
5853376a787SDiego Novillo }
5863376a787SDiego Novillo 
587aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
588aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
5893376a787SDiego Novillo   uint64_t HeadCount = 0;
590aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
5913376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
5923376a787SDiego Novillo       return sampleprof_error::truncated;
5933376a787SDiego Novillo 
5943376a787SDiego Novillo   uint32_t NameIdx;
5953376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
5963376a787SDiego Novillo     return sampleprof_error::truncated;
5973376a787SDiego Novillo 
5983376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
5993376a787SDiego Novillo 
6003376a787SDiego Novillo   uint32_t NumPosCounts;
6013376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
6023376a787SDiego Novillo     return sampleprof_error::truncated;
6033376a787SDiego Novillo 
604aae1ed8eSDiego Novillo   uint32_t NumCallsites;
605aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
6063376a787SDiego Novillo     return sampleprof_error::truncated;
6073376a787SDiego Novillo 
608aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
609aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
610aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
611aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
612aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
613aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
614aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
615aae1ed8eSDiego Novillo     // the profile of the original function.
616aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
617aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
618aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
6193376a787SDiego Novillo       Update = false;
620aae1ed8eSDiego Novillo   } else {
621aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
622aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
623aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
624aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
625aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
626aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
627aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
628aae1ed8eSDiego Novillo         CallsiteLocation(LineOffset, Discriminator, Name));
6293376a787SDiego Novillo   }
6303376a787SDiego Novillo 
6313376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
6323376a787SDiego Novillo     uint32_t Offset;
6333376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
6343376a787SDiego Novillo       return sampleprof_error::truncated;
6353376a787SDiego Novillo 
6363376a787SDiego Novillo     uint32_t NumTargets;
6373376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
6383376a787SDiego Novillo       return sampleprof_error::truncated;
6393376a787SDiego Novillo 
6403376a787SDiego Novillo     uint64_t Count;
6413376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
6423376a787SDiego Novillo       return sampleprof_error::truncated;
6433376a787SDiego Novillo 
644aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
645aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
646aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
647aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
648aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
6493376a787SDiego Novillo 
650aae1ed8eSDiego Novillo     InlineCallStack NewStack;
651aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
652aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
653aae1ed8eSDiego Novillo     if (Update) {
654aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
655aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
656aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
657aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
658aae1ed8eSDiego Novillo 
659aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
660aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
661aae1ed8eSDiego Novillo     }
662aae1ed8eSDiego Novillo 
663aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
664aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
665aae1ed8eSDiego Novillo     // function) resolved at runtime.
6663376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
6673376a787SDiego Novillo       uint32_t HistVal;
6683376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
6693376a787SDiego Novillo         return sampleprof_error::truncated;
6703376a787SDiego Novillo 
6713376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
6723376a787SDiego Novillo         return sampleprof_error::malformed;
6733376a787SDiego Novillo 
6743376a787SDiego Novillo       uint64_t TargetIdx;
6753376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
6763376a787SDiego Novillo         return sampleprof_error::truncated;
6773376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
6783376a787SDiego Novillo 
6793376a787SDiego Novillo       uint64_t TargetCount;
6803376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
6813376a787SDiego Novillo         return sampleprof_error::truncated;
6823376a787SDiego Novillo 
6833376a787SDiego Novillo       if (Update) {
6843376a787SDiego Novillo         FunctionSamples &TargetProfile = Profiles[TargetName];
685aae1ed8eSDiego Novillo         TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
686aae1ed8eSDiego Novillo                                              TargetName, TargetCount);
6873376a787SDiego Novillo       }
6883376a787SDiego Novillo     }
6893376a787SDiego Novillo   }
6903376a787SDiego Novillo 
691aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
692aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
693aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
6943376a787SDiego Novillo     // The offset is encoded as:
6953376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
6963376a787SDiego Novillo     //   low 16 bits: discriminator.
6973376a787SDiego Novillo     uint32_t Offset;
6983376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
6993376a787SDiego Novillo       return sampleprof_error::truncated;
700aae1ed8eSDiego Novillo     InlineCallStack NewStack;
701aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
702aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
703aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
7043376a787SDiego Novillo       return EC;
7053376a787SDiego Novillo   }
7063376a787SDiego Novillo 
7073376a787SDiego Novillo   return sampleprof_error::success;
7083376a787SDiego Novillo }
7093376a787SDiego Novillo 
7103376a787SDiego Novillo /// \brief Read a GCC AutoFDO profile.
7113376a787SDiego Novillo ///
7123376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
7133376a787SDiego Novillo /// https://github.com/google/autofdo.
7143376a787SDiego Novillo std::error_code SampleProfileReaderGCC::read() {
7153376a787SDiego Novillo   // Read the string table.
7163376a787SDiego Novillo   if (std::error_code EC = readNameTable())
7173376a787SDiego Novillo     return EC;
7183376a787SDiego Novillo 
7193376a787SDiego Novillo   // Read the source profile.
7203376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
7213376a787SDiego Novillo     return EC;
7223376a787SDiego Novillo 
7233376a787SDiego Novillo   return sampleprof_error::success;
7243376a787SDiego Novillo }
7253376a787SDiego Novillo 
7263376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
7273376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
7283376a787SDiego Novillo   return Magic == "adcg*704";
7293376a787SDiego Novillo }
7303376a787SDiego Novillo 
731c572e92cSDiego Novillo /// \brief Prepare a memory buffer for the contents of \p Filename.
732de1ab26fSDiego Novillo ///
733c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
734fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
735fcd55607SDiego Novillo setupMemoryBuffer(std::string Filename) {
736c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
737c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
738c572e92cSDiego Novillo     return EC;
739fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
740c572e92cSDiego Novillo 
741c572e92cSDiego Novillo   // Sanity check the file.
74238be3330SDiego Novillo   if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
743c572e92cSDiego Novillo     return sampleprof_error::too_large;
744c572e92cSDiego Novillo 
745fcd55607SDiego Novillo   return std::move(Buffer);
746c572e92cSDiego Novillo }
747c572e92cSDiego Novillo 
748c572e92cSDiego Novillo /// \brief Create a sample profile reader based on the format of the input file.
749c572e92cSDiego Novillo ///
750c572e92cSDiego Novillo /// \param Filename The file to open.
751c572e92cSDiego Novillo ///
752c572e92cSDiego Novillo /// \param Reader The reader to instantiate according to \p Filename's format.
753c572e92cSDiego Novillo ///
754c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
755c572e92cSDiego Novillo ///
756c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
757fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
758fcd55607SDiego Novillo SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
759fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
760fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
761c572e92cSDiego Novillo     return EC;
76251abea74SNathan Slingerland   return create(BufferOrError.get(), C);
76351abea74SNathan Slingerland }
764c572e92cSDiego Novillo 
76551abea74SNathan Slingerland /// \brief Create a sample profile reader based on the format of the input data.
76651abea74SNathan Slingerland ///
76751abea74SNathan Slingerland /// \param B The memory buffer to create the reader from (assumes ownership).
76851abea74SNathan Slingerland ///
76951abea74SNathan Slingerland /// \param Reader The reader to instantiate according to \p Filename's format.
77051abea74SNathan Slingerland ///
77151abea74SNathan Slingerland /// \param C The LLVM context to use to emit diagnostics.
77251abea74SNathan Slingerland ///
77351abea74SNathan Slingerland /// \returns an error code indicating the status of the created reader.
77451abea74SNathan Slingerland ErrorOr<std::unique_ptr<SampleProfileReader>>
77551abea74SNathan Slingerland SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
776fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
77751abea74SNathan Slingerland   if (SampleProfileReaderBinary::hasFormat(*B))
77851abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderBinary(std::move(B), C));
77951abea74SNathan Slingerland   else if (SampleProfileReaderGCC::hasFormat(*B))
78051abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
78151abea74SNathan Slingerland   else if (SampleProfileReaderText::hasFormat(*B))
78251abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderText(std::move(B), C));
7834f823667SNathan Slingerland   else
7844f823667SNathan Slingerland     return sampleprof_error::unrecognized_format;
785c572e92cSDiego Novillo 
786fcd55607SDiego Novillo   if (std::error_code EC = Reader->readHeader())
787fcd55607SDiego Novillo     return EC;
788fcd55607SDiego Novillo 
789fcd55607SDiego Novillo   return std::move(Reader);
790de1ab26fSDiego Novillo }
791*40ee23dbSEaswaran Raman 
792*40ee23dbSEaswaran Raman // For text and GCC file formats, we compute the summary after reading the
793*40ee23dbSEaswaran Raman // profile. Binary format has the profile summary in its header.
794*40ee23dbSEaswaran Raman void SampleProfileReader::computeSummary() {
795*40ee23dbSEaswaran Raman   Summary.reset(new SampleProfileSummary(ProfileSummary::DefaultCutoffs));
796*40ee23dbSEaswaran Raman   for (const auto &I : Profiles) {
797*40ee23dbSEaswaran Raman     const FunctionSamples &Profile = I.second;
798*40ee23dbSEaswaran Raman     Summary->addRecord(Profile);
799*40ee23dbSEaswaran Raman   }
800*40ee23dbSEaswaran Raman   Summary->computeDetailedSummary();
801*40ee23dbSEaswaran Raman }
802