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
11*bb5605caSDiego Novillo // supports three file formats: text, binary and gcov.
12de1ab26fSDiego Novillo //
13*bb5605caSDiego Novillo // The textual representation is useful for debugging and testing purposes. The
14*bb5605caSDiego Novillo // binary representation is more compact, resulting in smaller file sizes.
15de1ab26fSDiego Novillo //
16*bb5605caSDiego Novillo // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17*bb5605caSDiego Novillo // tool (https://github.com/google/autofdo)
18de1ab26fSDiego Novillo //
19*bb5605caSDiego 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"
24de1ab26fSDiego Novillo #include "llvm/Support/Debug.h"
25de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
26c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
27de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
28c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
296722688eSDehao Chen #include "llvm/ADT/DenseMap.h"
306722688eSDehao Chen #include "llvm/ADT/SmallVector.h"
31de1ab26fSDiego Novillo 
32c572e92cSDiego Novillo using namespace llvm::sampleprof;
33de1ab26fSDiego Novillo using namespace llvm;
34de1ab26fSDiego Novillo 
35de1ab26fSDiego Novillo /// \brief Print the samples collected for a function on stream \p OS.
36de1ab26fSDiego Novillo ///
37de1ab26fSDiego Novillo /// \param OS Stream to emit the output to.
38aae1ed8eSDiego Novillo void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
39de1ab26fSDiego Novillo   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
40de1ab26fSDiego Novillo      << " sampled lines\n";
41d5336ae2SDiego Novillo   for (const auto &SI : BodySamples) {
42d5336ae2SDiego Novillo     LineLocation Loc = SI.first;
43d5336ae2SDiego Novillo     const SampleRecord &Sample = SI.second;
44aae1ed8eSDiego Novillo     OS.indent(Indent);
45aae1ed8eSDiego Novillo     OS << "line offset: " << Loc.LineOffset
46c572e92cSDiego Novillo        << ", discriminator: " << Loc.Discriminator
47c572e92cSDiego Novillo        << ", number of samples: " << Sample.getSamples();
48c572e92cSDiego Novillo     if (Sample.hasCalls()) {
49c572e92cSDiego Novillo       OS << ", calls:";
50d5336ae2SDiego Novillo       for (const auto &I : Sample.getCallTargets())
51d5336ae2SDiego Novillo         OS << " " << I.first() << ":" << I.second;
52c572e92cSDiego Novillo     }
53c572e92cSDiego Novillo     OS << "\n";
54c572e92cSDiego Novillo   }
55aae1ed8eSDiego Novillo   for (const auto &CS : CallsiteSamples) {
56aae1ed8eSDiego Novillo     CallsiteLocation Loc = CS.first;
57aae1ed8eSDiego Novillo     const FunctionSamples &CalleeSamples = CS.second;
58aae1ed8eSDiego Novillo     OS.indent(Indent);
59aae1ed8eSDiego Novillo     OS << "line offset: " << Loc.LineOffset
60aae1ed8eSDiego Novillo        << ", discriminator: " << Loc.Discriminator
61aae1ed8eSDiego Novillo        << ", inlined callee: " << Loc.CalleeName << ": ";
62aae1ed8eSDiego Novillo     CalleeSamples.print(OS, Indent + 2);
63aae1ed8eSDiego Novillo   }
64de1ab26fSDiego Novillo }
65de1ab26fSDiego Novillo 
66de1ab26fSDiego Novillo /// \brief Dump the function profile for \p FName.
67de1ab26fSDiego Novillo ///
68de1ab26fSDiego Novillo /// \param FName Name of the function to print.
69d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
70d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
71d5336ae2SDiego Novillo                                               raw_ostream &OS) {
72d5336ae2SDiego Novillo   OS << "Function: " << FName << ": ";
73d5336ae2SDiego Novillo   Profiles[FName].print(OS);
74de1ab26fSDiego Novillo }
75de1ab26fSDiego Novillo 
76d5336ae2SDiego Novillo /// \brief Dump all the function profiles found on stream \p OS.
77d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
78d5336ae2SDiego Novillo   for (const auto &I : Profiles)
79d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
80de1ab26fSDiego Novillo }
81de1ab26fSDiego Novillo 
826722688eSDehao Chen /// \brief Parse \p Input as function head.
836722688eSDehao Chen ///
846722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
856722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
866722688eSDehao Chen /// count in \p NumHeadSamples.
876722688eSDehao Chen ///
886722688eSDehao Chen /// \returns true if parsing is successful.
896722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
906722688eSDehao Chen                       unsigned &NumSamples, unsigned &NumHeadSamples) {
916722688eSDehao Chen   if (Input[0] == ' ')
926722688eSDehao Chen     return false;
936722688eSDehao Chen   size_t n2 = Input.rfind(':');
946722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
956722688eSDehao Chen   FName = Input.substr(0, n1);
966722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
976722688eSDehao Chen     return false;
986722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
996722688eSDehao Chen     return false;
1006722688eSDehao Chen   return true;
1016722688eSDehao Chen }
1026722688eSDehao Chen 
1036722688eSDehao Chen /// \brief Parse \p Input as line sample.
1046722688eSDehao Chen ///
1056722688eSDehao Chen /// \param Input input line.
1066722688eSDehao Chen /// \param IsCallsite true if the line represents an inlined callsite.
1076722688eSDehao Chen /// \param Depth the depth of the inline stack.
1086722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
1096722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
1106722688eSDehao Chen /// \param Discriminator discriminator of the line.
1116722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
1126722688eSDehao Chen ///
1136722688eSDehao Chen /// returns true if parsing is successful.
1146722688eSDehao Chen static bool ParseLine(const StringRef &Input, bool &IsCallsite, unsigned &Depth,
1156722688eSDehao Chen                       unsigned &NumSamples, unsigned &LineOffset,
1166722688eSDehao Chen                       unsigned &Discriminator, StringRef &CalleeName,
1176722688eSDehao Chen                       DenseMap<StringRef, unsigned> &TargetCountMap) {
1186722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
1196722688eSDehao Chen     ;
1206722688eSDehao Chen   if (Depth == 0)
1216722688eSDehao Chen     return false;
1226722688eSDehao Chen 
1236722688eSDehao Chen   size_t n1 = Input.find(':');
1246722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
1256722688eSDehao Chen   size_t n2 = Loc.find('.');
1266722688eSDehao Chen   if (n2 == StringRef::npos) {
1276722688eSDehao Chen     if (Loc.getAsInteger(10, LineOffset))
1286722688eSDehao Chen       return false;
1296722688eSDehao Chen     Discriminator = 0;
1306722688eSDehao Chen   } else {
1316722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
1326722688eSDehao Chen       return false;
1336722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
1346722688eSDehao Chen       return false;
1356722688eSDehao Chen   }
1366722688eSDehao Chen 
1376722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
1386722688eSDehao Chen   if (Rest[0] >= '0' && Rest[0] <= '9') {
1396722688eSDehao Chen     IsCallsite = false;
1406722688eSDehao Chen     size_t n3 = Rest.find(' ');
1416722688eSDehao Chen     if (n3 == StringRef::npos) {
1426722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
1436722688eSDehao Chen         return false;
1446722688eSDehao Chen     } else {
1456722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
1466722688eSDehao Chen         return false;
1476722688eSDehao Chen     }
1486722688eSDehao Chen     while (n3 != StringRef::npos) {
1496722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
1506722688eSDehao Chen       Rest = Rest.substr(n3);
1516722688eSDehao Chen       n3 = Rest.find(' ');
1526722688eSDehao Chen       StringRef pair = Rest;
1536722688eSDehao Chen       if (n3 != StringRef::npos) {
1546722688eSDehao Chen         pair = Rest.substr(0, n3);
1556722688eSDehao Chen       }
1566722688eSDehao Chen       int n4 = pair.find(':');
1576722688eSDehao Chen       unsigned count;
1586722688eSDehao Chen       if (pair.substr(n4 + 1).getAsInteger(10, count))
1596722688eSDehao Chen         return false;
1606722688eSDehao Chen       TargetCountMap[pair.substr(0, n4)] = count;
1616722688eSDehao Chen     }
1626722688eSDehao Chen   } else {
1636722688eSDehao Chen     IsCallsite = true;
1646722688eSDehao Chen     int n3 = Rest.find_last_of(':');
1656722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
1666722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
1676722688eSDehao Chen       return false;
1686722688eSDehao Chen   }
1696722688eSDehao Chen   return true;
1706722688eSDehao Chen }
1716722688eSDehao Chen 
172de1ab26fSDiego Novillo /// \brief Load samples from a text file.
173de1ab26fSDiego Novillo ///
174de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
175de1ab26fSDiego Novillo /// the expected format.
176de1ab26fSDiego Novillo ///
177de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
178c572e92cSDiego Novillo std::error_code SampleProfileReaderText::read() {
179c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
180de1ab26fSDiego Novillo 
181aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
1826722688eSDehao Chen 
1836722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
1846722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
1856722688eSDehao Chen       continue;
186de1ab26fSDiego Novillo     // Read the header of each function.
187de1ab26fSDiego Novillo     //
188de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
189de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
190de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
191de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
192de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
193de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
194de1ab26fSDiego Novillo     // name (member functions, templates, etc).
195de1ab26fSDiego Novillo     //
196de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
197de1ab26fSDiego Novillo     // should not begin with a number.
1986722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
1996722688eSDehao Chen       unsigned NumSamples, NumHeadSamples;
2006722688eSDehao Chen       StringRef FName;
2016722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
2023376a787SDiego Novillo         reportError(LineIt.line_number(),
203de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
204c572e92cSDiego Novillo         return sampleprof_error::malformed;
205de1ab26fSDiego Novillo       }
206de1ab26fSDiego Novillo       Profiles[FName] = FunctionSamples();
207de1ab26fSDiego Novillo       FunctionSamples &FProfile = Profiles[FName];
208de1ab26fSDiego Novillo       FProfile.addTotalSamples(NumSamples);
209de1ab26fSDiego Novillo       FProfile.addHeadSamples(NumHeadSamples);
2106722688eSDehao Chen       InlineStack.clear();
2116722688eSDehao Chen       InlineStack.push_back(&FProfile);
2126722688eSDehao Chen     } else {
2136722688eSDehao Chen       unsigned NumSamples;
2146722688eSDehao Chen       StringRef FName;
2156722688eSDehao Chen       DenseMap<StringRef, unsigned> TargetCountMap;
2166722688eSDehao Chen       bool IsCallsite;
2176722688eSDehao Chen       unsigned Depth, LineOffset, Discriminator;
2186722688eSDehao Chen       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
2196722688eSDehao Chen                      Discriminator, FName, TargetCountMap)) {
2203376a787SDiego Novillo         reportError(LineIt.line_number(),
2213376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
2223376a787SDiego Novillo                         *LineIt);
223c572e92cSDiego Novillo         return sampleprof_error::malformed;
224de1ab26fSDiego Novillo       }
2256722688eSDehao Chen       if (IsCallsite) {
2266722688eSDehao Chen         while (InlineStack.size() > Depth) {
2276722688eSDehao Chen           InlineStack.pop_back();
228c572e92cSDiego Novillo         }
2296722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
2306722688eSDehao Chen             CallsiteLocation(LineOffset, Discriminator, FName));
2316722688eSDehao Chen         FSamples.addTotalSamples(NumSamples);
2326722688eSDehao Chen         InlineStack.push_back(&FSamples);
2336722688eSDehao Chen       } else {
2346722688eSDehao Chen         while (InlineStack.size() > Depth) {
2356722688eSDehao Chen           InlineStack.pop_back();
2366722688eSDehao Chen         }
2376722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
2386722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
239c572e92cSDiego Novillo           FProfile.addCalledTargetSamples(LineOffset, Discriminator,
2406722688eSDehao Chen                                           name_count.first, name_count.second);
241c572e92cSDiego Novillo         }
242de1ab26fSDiego Novillo         FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
2436722688eSDehao Chen       }
244de1ab26fSDiego Novillo     }
245de1ab26fSDiego Novillo   }
246de1ab26fSDiego Novillo 
247c572e92cSDiego Novillo   return sampleprof_error::success;
248de1ab26fSDiego Novillo }
249de1ab26fSDiego Novillo 
250d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
251c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
252c572e92cSDiego Novillo   std::error_code EC;
253c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
254c572e92cSDiego Novillo 
255c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
256c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
257c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
258c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
259c572e92cSDiego Novillo   else
260c572e92cSDiego Novillo     EC = sampleprof_error::success;
261c572e92cSDiego Novillo 
262c572e92cSDiego Novillo   if (EC) {
2633376a787SDiego Novillo     reportError(0, EC.message());
264c572e92cSDiego Novillo     return EC;
265c572e92cSDiego Novillo   }
266c572e92cSDiego Novillo 
267c572e92cSDiego Novillo   Data += NumBytesRead;
268c572e92cSDiego Novillo   return static_cast<T>(Val);
269c572e92cSDiego Novillo }
270c572e92cSDiego Novillo 
271c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
272c572e92cSDiego Novillo   std::error_code EC;
273c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
274c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
275c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
2763376a787SDiego Novillo     reportError(0, EC.message());
277c572e92cSDiego Novillo     return EC;
278c572e92cSDiego Novillo   }
279c572e92cSDiego Novillo 
280c572e92cSDiego Novillo   Data += Str.size() + 1;
281c572e92cSDiego Novillo   return Str;
282c572e92cSDiego Novillo }
283c572e92cSDiego Novillo 
284760c5a8fSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
285760c5a8fSDiego Novillo   std::error_code EC;
286760c5a8fSDiego Novillo   auto Idx = readNumber<unsigned>();
287760c5a8fSDiego Novillo   if (std::error_code EC = Idx.getError())
288760c5a8fSDiego Novillo     return EC;
289760c5a8fSDiego Novillo   if (*Idx >= NameTable.size())
290760c5a8fSDiego Novillo     return sampleprof_error::truncated_name_table;
291760c5a8fSDiego Novillo   return NameTable[*Idx];
292760c5a8fSDiego Novillo }
293760c5a8fSDiego Novillo 
294a7f1e8efSDiego Novillo std::error_code
295a7f1e8efSDiego Novillo SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
296c572e92cSDiego Novillo   auto Val = readNumber<unsigned>();
297c572e92cSDiego Novillo   if (std::error_code EC = Val.getError())
298c572e92cSDiego Novillo     return EC;
299c572e92cSDiego Novillo   FProfile.addTotalSamples(*Val);
300c572e92cSDiego Novillo 
301c572e92cSDiego Novillo   Val = readNumber<unsigned>();
302c572e92cSDiego Novillo   if (std::error_code EC = Val.getError())
303c572e92cSDiego Novillo     return EC;
304c572e92cSDiego Novillo   FProfile.addHeadSamples(*Val);
305c572e92cSDiego Novillo 
306c572e92cSDiego Novillo   // Read the samples in the body.
307c572e92cSDiego Novillo   auto NumRecords = readNumber<unsigned>();
308c572e92cSDiego Novillo   if (std::error_code EC = NumRecords.getError())
309c572e92cSDiego Novillo     return EC;
310a7f1e8efSDiego Novillo 
311c572e92cSDiego Novillo   for (unsigned I = 0; I < *NumRecords; ++I) {
312c572e92cSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
313c572e92cSDiego Novillo     if (std::error_code EC = LineOffset.getError())
314c572e92cSDiego Novillo       return EC;
315c572e92cSDiego Novillo 
316c572e92cSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
317c572e92cSDiego Novillo     if (std::error_code EC = Discriminator.getError())
318c572e92cSDiego Novillo       return EC;
319c572e92cSDiego Novillo 
320c572e92cSDiego Novillo     auto NumSamples = readNumber<uint64_t>();
321c572e92cSDiego Novillo     if (std::error_code EC = NumSamples.getError())
322c572e92cSDiego Novillo       return EC;
323c572e92cSDiego Novillo 
324c572e92cSDiego Novillo     auto NumCalls = readNumber<unsigned>();
325c572e92cSDiego Novillo     if (std::error_code EC = NumCalls.getError())
326c572e92cSDiego Novillo       return EC;
327c572e92cSDiego Novillo 
328c572e92cSDiego Novillo     for (unsigned J = 0; J < *NumCalls; ++J) {
329760c5a8fSDiego Novillo       auto CalledFunction(readStringFromTable());
330c572e92cSDiego Novillo       if (std::error_code EC = CalledFunction.getError())
331c572e92cSDiego Novillo         return EC;
332c572e92cSDiego Novillo 
333c572e92cSDiego Novillo       auto CalledFunctionSamples = readNumber<uint64_t>();
334c572e92cSDiego Novillo       if (std::error_code EC = CalledFunctionSamples.getError())
335c572e92cSDiego Novillo         return EC;
336c572e92cSDiego Novillo 
337c572e92cSDiego Novillo       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
338a7f1e8efSDiego Novillo                                       *CalledFunction, *CalledFunctionSamples);
339c572e92cSDiego Novillo     }
340c572e92cSDiego Novillo 
341c572e92cSDiego Novillo     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
342c572e92cSDiego Novillo   }
343a7f1e8efSDiego Novillo 
344a7f1e8efSDiego Novillo   // Read all the samples for inlined function calls.
345a7f1e8efSDiego Novillo   auto NumCallsites = readNumber<unsigned>();
346a7f1e8efSDiego Novillo   if (std::error_code EC = NumCallsites.getError())
347a7f1e8efSDiego Novillo     return EC;
348a7f1e8efSDiego Novillo 
349a7f1e8efSDiego Novillo   for (unsigned J = 0; J < *NumCallsites; ++J) {
350a7f1e8efSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
351a7f1e8efSDiego Novillo     if (std::error_code EC = LineOffset.getError())
352a7f1e8efSDiego Novillo       return EC;
353a7f1e8efSDiego Novillo 
354a7f1e8efSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
355a7f1e8efSDiego Novillo     if (std::error_code EC = Discriminator.getError())
356a7f1e8efSDiego Novillo       return EC;
357a7f1e8efSDiego Novillo 
358760c5a8fSDiego Novillo     auto FName(readStringFromTable());
359a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
360a7f1e8efSDiego Novillo       return EC;
361a7f1e8efSDiego Novillo 
362a7f1e8efSDiego Novillo     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
363a7f1e8efSDiego Novillo         CallsiteLocation(*LineOffset, *Discriminator, *FName));
364a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(CalleeProfile))
365a7f1e8efSDiego Novillo       return EC;
366a7f1e8efSDiego Novillo   }
367a7f1e8efSDiego Novillo 
368a7f1e8efSDiego Novillo   return sampleprof_error::success;
369a7f1e8efSDiego Novillo }
370a7f1e8efSDiego Novillo 
371a7f1e8efSDiego Novillo std::error_code SampleProfileReaderBinary::read() {
372a7f1e8efSDiego Novillo   while (!at_eof()) {
373760c5a8fSDiego Novillo     auto FName(readStringFromTable());
374a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
375a7f1e8efSDiego Novillo       return EC;
376a7f1e8efSDiego Novillo 
377a7f1e8efSDiego Novillo     Profiles[*FName] = FunctionSamples();
378a7f1e8efSDiego Novillo     FunctionSamples &FProfile = Profiles[*FName];
379a7f1e8efSDiego Novillo 
380a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(FProfile))
381a7f1e8efSDiego Novillo       return EC;
382c572e92cSDiego Novillo   }
383c572e92cSDiego Novillo 
384c572e92cSDiego Novillo   return sampleprof_error::success;
385c572e92cSDiego Novillo }
386c572e92cSDiego Novillo 
387c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::readHeader() {
388c572e92cSDiego Novillo   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
389c572e92cSDiego Novillo   End = Data + Buffer->getBufferSize();
390c572e92cSDiego Novillo 
391c572e92cSDiego Novillo   // Read and check the magic identifier.
392c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
393c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
394c572e92cSDiego Novillo     return EC;
395c572e92cSDiego Novillo   else if (*Magic != SPMagic())
396c572e92cSDiego Novillo     return sampleprof_error::bad_magic;
397c572e92cSDiego Novillo 
398c572e92cSDiego Novillo   // Read the version number.
399c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
400c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
401c572e92cSDiego Novillo     return EC;
402c572e92cSDiego Novillo   else if (*Version != SPVersion())
403c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
404c572e92cSDiego Novillo 
405760c5a8fSDiego Novillo   // Read the name table.
406760c5a8fSDiego Novillo   auto Size = readNumber<size_t>();
407760c5a8fSDiego Novillo   if (std::error_code EC = Size.getError())
408760c5a8fSDiego Novillo     return EC;
409760c5a8fSDiego Novillo   NameTable.reserve(*Size);
410760c5a8fSDiego Novillo   for (size_t I = 0; I < *Size; ++I) {
411760c5a8fSDiego Novillo     auto Name(readString());
412760c5a8fSDiego Novillo     if (std::error_code EC = Name.getError())
413760c5a8fSDiego Novillo       return EC;
414760c5a8fSDiego Novillo     NameTable.push_back(*Name);
415760c5a8fSDiego Novillo   }
416760c5a8fSDiego Novillo 
417c572e92cSDiego Novillo   return sampleprof_error::success;
418c572e92cSDiego Novillo }
419c572e92cSDiego Novillo 
420c572e92cSDiego Novillo bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
421c572e92cSDiego Novillo   const uint8_t *Data =
422c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
423c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
424c572e92cSDiego Novillo   return Magic == SPMagic();
425c572e92cSDiego Novillo }
426c572e92cSDiego Novillo 
4273376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
4283376a787SDiego Novillo   uint32_t dummy;
4293376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
4303376a787SDiego Novillo     return sampleprof_error::truncated;
4313376a787SDiego Novillo   return sampleprof_error::success;
4323376a787SDiego Novillo }
4333376a787SDiego Novillo 
4343376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
4353376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
4363376a787SDiego Novillo     uint32_t Val;
4373376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
4383376a787SDiego Novillo       return static_cast<T>(Val);
4393376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
4403376a787SDiego Novillo     uint64_t Val;
4413376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
4423376a787SDiego Novillo       return static_cast<T>(Val);
4433376a787SDiego Novillo   }
4443376a787SDiego Novillo 
4453376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
4463376a787SDiego Novillo   reportError(0, EC.message());
4473376a787SDiego Novillo   return EC;
4483376a787SDiego Novillo }
4493376a787SDiego Novillo 
4503376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
4513376a787SDiego Novillo   StringRef Str;
4523376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
4533376a787SDiego Novillo     return sampleprof_error::truncated;
4543376a787SDiego Novillo   return Str;
4553376a787SDiego Novillo }
4563376a787SDiego Novillo 
4573376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
4583376a787SDiego Novillo   // Read the magic identifier.
4593376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
4603376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
4613376a787SDiego Novillo 
4623376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
4633376a787SDiego Novillo   // version, but the profile creator generates v704.
4643376a787SDiego Novillo   GCOV::GCOVVersion version;
4653376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
4663376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
4673376a787SDiego Novillo 
4683376a787SDiego Novillo   if (version != GCOV::V704)
4693376a787SDiego Novillo     return sampleprof_error::unsupported_version;
4703376a787SDiego Novillo 
4713376a787SDiego Novillo   // Skip the empty integer.
4723376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
4733376a787SDiego Novillo     return EC;
4743376a787SDiego Novillo 
4753376a787SDiego Novillo   return sampleprof_error::success;
4763376a787SDiego Novillo }
4773376a787SDiego Novillo 
4783376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
4793376a787SDiego Novillo   uint32_t Tag;
4803376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
4813376a787SDiego Novillo     return sampleprof_error::truncated;
4823376a787SDiego Novillo 
4833376a787SDiego Novillo   if (Tag != Expected)
4843376a787SDiego Novillo     return sampleprof_error::malformed;
4853376a787SDiego Novillo 
4863376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
4873376a787SDiego Novillo     return EC;
4883376a787SDiego Novillo 
4893376a787SDiego Novillo   return sampleprof_error::success;
4903376a787SDiego Novillo }
4913376a787SDiego Novillo 
4923376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
4933376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
4943376a787SDiego Novillo     return EC;
4953376a787SDiego Novillo 
4963376a787SDiego Novillo   uint32_t Size;
4973376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
4983376a787SDiego Novillo     return sampleprof_error::truncated;
4993376a787SDiego Novillo 
5003376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
5013376a787SDiego Novillo     StringRef Str;
5023376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
5033376a787SDiego Novillo       return sampleprof_error::truncated;
5043376a787SDiego Novillo     Names.push_back(Str);
5053376a787SDiego Novillo   }
5063376a787SDiego Novillo 
5073376a787SDiego Novillo   return sampleprof_error::success;
5083376a787SDiego Novillo }
5093376a787SDiego Novillo 
5103376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
5113376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
5123376a787SDiego Novillo     return EC;
5133376a787SDiego Novillo 
5143376a787SDiego Novillo   uint32_t NumFunctions;
5153376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
5163376a787SDiego Novillo     return sampleprof_error::truncated;
5173376a787SDiego Novillo 
518aae1ed8eSDiego Novillo   InlineCallStack Stack;
5193376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
520aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
5213376a787SDiego Novillo       return EC;
5223376a787SDiego Novillo 
5233376a787SDiego Novillo   return sampleprof_error::success;
5243376a787SDiego Novillo }
5253376a787SDiego Novillo 
526aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
527aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
5283376a787SDiego Novillo   uint64_t HeadCount = 0;
529aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
5303376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
5313376a787SDiego Novillo       return sampleprof_error::truncated;
5323376a787SDiego Novillo 
5333376a787SDiego Novillo   uint32_t NameIdx;
5343376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
5353376a787SDiego Novillo     return sampleprof_error::truncated;
5363376a787SDiego Novillo 
5373376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
5383376a787SDiego Novillo 
5393376a787SDiego Novillo   uint32_t NumPosCounts;
5403376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
5413376a787SDiego Novillo     return sampleprof_error::truncated;
5423376a787SDiego Novillo 
543aae1ed8eSDiego Novillo   uint32_t NumCallsites;
544aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
5453376a787SDiego Novillo     return sampleprof_error::truncated;
5463376a787SDiego Novillo 
547aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
548aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
549aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
550aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
551aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
552aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
553aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
554aae1ed8eSDiego Novillo     // the profile of the original function.
555aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
556aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
557aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
5583376a787SDiego Novillo       Update = false;
559aae1ed8eSDiego Novillo   } else {
560aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
561aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
562aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
563aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
564aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
565aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
566aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
567aae1ed8eSDiego Novillo         CallsiteLocation(LineOffset, Discriminator, Name));
5683376a787SDiego Novillo   }
5693376a787SDiego Novillo 
5703376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
5713376a787SDiego Novillo     uint32_t Offset;
5723376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
5733376a787SDiego Novillo       return sampleprof_error::truncated;
5743376a787SDiego Novillo 
5753376a787SDiego Novillo     uint32_t NumTargets;
5763376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
5773376a787SDiego Novillo       return sampleprof_error::truncated;
5783376a787SDiego Novillo 
5793376a787SDiego Novillo     uint64_t Count;
5803376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
5813376a787SDiego Novillo       return sampleprof_error::truncated;
5823376a787SDiego Novillo 
583aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
584aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
585aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
586aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
587aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
5883376a787SDiego Novillo 
589aae1ed8eSDiego Novillo     InlineCallStack NewStack;
590aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
591aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
592aae1ed8eSDiego Novillo     if (Update) {
593aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
594aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
595aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
596aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
597aae1ed8eSDiego Novillo 
598aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
599aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
600aae1ed8eSDiego Novillo     }
601aae1ed8eSDiego Novillo 
602aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
603aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
604aae1ed8eSDiego Novillo     // function) resolved at runtime.
6053376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
6063376a787SDiego Novillo       uint32_t HistVal;
6073376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
6083376a787SDiego Novillo         return sampleprof_error::truncated;
6093376a787SDiego Novillo 
6103376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
6113376a787SDiego Novillo         return sampleprof_error::malformed;
6123376a787SDiego Novillo 
6133376a787SDiego Novillo       uint64_t TargetIdx;
6143376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
6153376a787SDiego Novillo         return sampleprof_error::truncated;
6163376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
6173376a787SDiego Novillo 
6183376a787SDiego Novillo       uint64_t TargetCount;
6193376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
6203376a787SDiego Novillo         return sampleprof_error::truncated;
6213376a787SDiego Novillo 
6223376a787SDiego Novillo       if (Update) {
6233376a787SDiego Novillo         FunctionSamples &TargetProfile = Profiles[TargetName];
624aae1ed8eSDiego Novillo         TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
625aae1ed8eSDiego Novillo                                              TargetName, TargetCount);
6263376a787SDiego Novillo       }
6273376a787SDiego Novillo     }
6283376a787SDiego Novillo   }
6293376a787SDiego Novillo 
630aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
631aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
632aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
6333376a787SDiego Novillo     // The offset is encoded as:
6343376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
6353376a787SDiego Novillo     //   low 16 bits: discriminator.
6363376a787SDiego Novillo     uint32_t Offset;
6373376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
6383376a787SDiego Novillo       return sampleprof_error::truncated;
639aae1ed8eSDiego Novillo     InlineCallStack NewStack;
640aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
641aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
642aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
6433376a787SDiego Novillo       return EC;
6443376a787SDiego Novillo   }
6453376a787SDiego Novillo 
6463376a787SDiego Novillo   return sampleprof_error::success;
6473376a787SDiego Novillo }
6483376a787SDiego Novillo 
6493376a787SDiego Novillo /// \brief Read a GCC AutoFDO profile.
6503376a787SDiego Novillo ///
6513376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
6523376a787SDiego Novillo /// https://github.com/google/autofdo.
6533376a787SDiego Novillo std::error_code SampleProfileReaderGCC::read() {
6543376a787SDiego Novillo   // Read the string table.
6553376a787SDiego Novillo   if (std::error_code EC = readNameTable())
6563376a787SDiego Novillo     return EC;
6573376a787SDiego Novillo 
6583376a787SDiego Novillo   // Read the source profile.
6593376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
6603376a787SDiego Novillo     return EC;
6613376a787SDiego Novillo 
6623376a787SDiego Novillo   return sampleprof_error::success;
6633376a787SDiego Novillo }
6643376a787SDiego Novillo 
6653376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
6663376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
6673376a787SDiego Novillo   return Magic == "adcg*704";
6683376a787SDiego Novillo }
6693376a787SDiego Novillo 
670c572e92cSDiego Novillo /// \brief Prepare a memory buffer for the contents of \p Filename.
671de1ab26fSDiego Novillo ///
672c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
673fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
674fcd55607SDiego Novillo setupMemoryBuffer(std::string Filename) {
675c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
676c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
677c572e92cSDiego Novillo     return EC;
678fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
679c572e92cSDiego Novillo 
680c572e92cSDiego Novillo   // Sanity check the file.
681c572e92cSDiego Novillo   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
682c572e92cSDiego Novillo     return sampleprof_error::too_large;
683c572e92cSDiego Novillo 
684fcd55607SDiego Novillo   return std::move(Buffer);
685c572e92cSDiego Novillo }
686c572e92cSDiego Novillo 
687c572e92cSDiego Novillo /// \brief Create a sample profile reader based on the format of the input file.
688c572e92cSDiego Novillo ///
689c572e92cSDiego Novillo /// \param Filename The file to open.
690c572e92cSDiego Novillo ///
691c572e92cSDiego Novillo /// \param Reader The reader to instantiate according to \p Filename's format.
692c572e92cSDiego Novillo ///
693c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
694c572e92cSDiego Novillo ///
695c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
696fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
697fcd55607SDiego Novillo SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
698fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
699fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
700c572e92cSDiego Novillo     return EC;
701c572e92cSDiego Novillo 
702fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrError.get());
703fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
704c572e92cSDiego Novillo   if (SampleProfileReaderBinary::hasFormat(*Buffer))
705c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
7063376a787SDiego Novillo   else if (SampleProfileReaderGCC::hasFormat(*Buffer))
7073376a787SDiego Novillo     Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
708c572e92cSDiego Novillo   else
709c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
710c572e92cSDiego Novillo 
711fcd55607SDiego Novillo   if (std::error_code EC = Reader->readHeader())
712fcd55607SDiego Novillo     return EC;
713fcd55607SDiego Novillo 
714fcd55607SDiego Novillo   return std::move(Reader);
715de1ab26fSDiego Novillo }
716