1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that reads LLVM sample profiles. It
10 // supports three file formats: text, binary and gcov.
11 //
12 // The textual representation is useful for debugging and testing purposes. The
13 // binary representation is more compact, resulting in smaller file sizes.
14 //
15 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
16 // tool (https://github.com/google/autofdo)
17 //
18 // All three encodings can be used interchangeably as an input sample profile.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "llvm/ProfileData/SampleProfReader.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/IR/ProfileSummary.h"
27 #include "llvm/ProfileData/ProfileCommon.h"
28 #include "llvm/ProfileData/SampleProf.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/LineIterator.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cstddef>
37 #include <cstdint>
38 #include <limits>
39 #include <memory>
40 #include <system_error>
41 #include <vector>
42 
43 using namespace llvm;
44 using namespace sampleprof;
45 
46 /// Dump the function profile for \p FName.
47 ///
48 /// \param FName Name of the function to print.
49 /// \param OS Stream to emit the output to.
50 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
51                                               raw_ostream &OS) {
52   OS << "Function: " << FName << ": " << Profiles[FName];
53 }
54 
55 /// Dump all the function profiles found on stream \p OS.
56 void SampleProfileReader::dump(raw_ostream &OS) {
57   for (const auto &I : Profiles)
58     dumpFunctionProfile(I.getKey(), OS);
59 }
60 
61 /// Parse \p Input as function head.
62 ///
63 /// Parse one line of \p Input, and update function name in \p FName,
64 /// function's total sample count in \p NumSamples, function's entry
65 /// count in \p NumHeadSamples.
66 ///
67 /// \returns true if parsing is successful.
68 static bool ParseHead(const StringRef &Input, StringRef &FName,
69                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
70   if (Input[0] == ' ')
71     return false;
72   size_t n2 = Input.rfind(':');
73   size_t n1 = Input.rfind(':', n2 - 1);
74   FName = Input.substr(0, n1);
75   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
76     return false;
77   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
78     return false;
79   return true;
80 }
81 
82 /// Returns true if line offset \p L is legal (only has 16 bits).
83 static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
84 
85 /// Parse \p Input as line sample.
86 ///
87 /// \param Input input line.
88 /// \param IsCallsite true if the line represents an inlined callsite.
89 /// \param Depth the depth of the inline stack.
90 /// \param NumSamples total samples of the line/inlined callsite.
91 /// \param LineOffset line offset to the start of the function.
92 /// \param Discriminator discriminator of the line.
93 /// \param TargetCountMap map from indirect call target to count.
94 ///
95 /// returns true if parsing is successful.
96 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
97                       uint64_t &NumSamples, uint32_t &LineOffset,
98                       uint32_t &Discriminator, StringRef &CalleeName,
99                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
100   for (Depth = 0; Input[Depth] == ' '; Depth++)
101     ;
102   if (Depth == 0)
103     return false;
104 
105   size_t n1 = Input.find(':');
106   StringRef Loc = Input.substr(Depth, n1 - Depth);
107   size_t n2 = Loc.find('.');
108   if (n2 == StringRef::npos) {
109     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
110       return false;
111     Discriminator = 0;
112   } else {
113     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
114       return false;
115     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
116       return false;
117   }
118 
119   StringRef Rest = Input.substr(n1 + 2);
120   if (Rest[0] >= '0' && Rest[0] <= '9') {
121     IsCallsite = false;
122     size_t n3 = Rest.find(' ');
123     if (n3 == StringRef::npos) {
124       if (Rest.getAsInteger(10, NumSamples))
125         return false;
126     } else {
127       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
128         return false;
129     }
130     // Find call targets and their sample counts.
131     // Note: In some cases, there are symbols in the profile which are not
132     // mangled. To accommodate such cases, use colon + integer pairs as the
133     // anchor points.
134     // An example:
135     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
136     // ":1000" and ":437" are used as anchor points so the string above will
137     // be interpreted as
138     // target: _M_construct<char *>
139     // count: 1000
140     // target: string_view<std::allocator<char> >
141     // count: 437
142     while (n3 != StringRef::npos) {
143       n3 += Rest.substr(n3).find_first_not_of(' ');
144       Rest = Rest.substr(n3);
145       n3 = Rest.find_first_of(':');
146       if (n3 == StringRef::npos || n3 == 0)
147         return false;
148 
149       StringRef Target;
150       uint64_t count, n4;
151       while (true) {
152         // Get the segment after the current colon.
153         StringRef AfterColon = Rest.substr(n3 + 1);
154         // Get the target symbol before the current colon.
155         Target = Rest.substr(0, n3);
156         // Check if the word after the current colon is an integer.
157         n4 = AfterColon.find_first_of(' ');
158         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
159         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
160         if (!WordAfterColon.getAsInteger(10, count))
161           break;
162 
163         // Try to find the next colon.
164         uint64_t n5 = AfterColon.find_first_of(':');
165         if (n5 == StringRef::npos)
166           return false;
167         n3 += n5 + 1;
168       }
169 
170       // An anchor point is found. Save the {target, count} pair
171       TargetCountMap[Target] = count;
172       if (n4 == Rest.size())
173         break;
174       // Change n3 to the next blank space after colon + integer pair.
175       n3 = n4;
176     }
177   } else {
178     IsCallsite = true;
179     size_t n3 = Rest.find_last_of(':');
180     CalleeName = Rest.substr(0, n3);
181     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
182       return false;
183   }
184   return true;
185 }
186 
187 /// Load samples from a text file.
188 ///
189 /// See the documentation at the top of the file for an explanation of
190 /// the expected format.
191 ///
192 /// \returns true if the file was loaded successfully, false otherwise.
193 std::error_code SampleProfileReaderText::read() {
194   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
195   sampleprof_error Result = sampleprof_error::success;
196 
197   InlineCallStack InlineStack;
198 
199   for (; !LineIt.is_at_eof(); ++LineIt) {
200     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
201       continue;
202     // Read the header of each function.
203     //
204     // Note that for function identifiers we are actually expecting
205     // mangled names, but we may not always get them. This happens when
206     // the compiler decides not to emit the function (e.g., it was inlined
207     // and removed). In this case, the binary will not have the linkage
208     // name for the function, so the profiler will emit the function's
209     // unmangled name, which may contain characters like ':' and '>' in its
210     // name (member functions, templates, etc).
211     //
212     // The only requirement we place on the identifier, then, is that it
213     // should not begin with a number.
214     if ((*LineIt)[0] != ' ') {
215       uint64_t NumSamples, NumHeadSamples;
216       StringRef FName;
217       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
218         reportError(LineIt.line_number(),
219                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
220         return sampleprof_error::malformed;
221       }
222       Profiles[FName] = FunctionSamples();
223       FunctionSamples &FProfile = Profiles[FName];
224       FProfile.setName(FName);
225       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
226       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
227       InlineStack.clear();
228       InlineStack.push_back(&FProfile);
229     } else {
230       uint64_t NumSamples;
231       StringRef FName;
232       DenseMap<StringRef, uint64_t> TargetCountMap;
233       bool IsCallsite;
234       uint32_t Depth, LineOffset, Discriminator;
235       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
236                      Discriminator, FName, TargetCountMap)) {
237         reportError(LineIt.line_number(),
238                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
239                         *LineIt);
240         return sampleprof_error::malformed;
241       }
242       if (IsCallsite) {
243         while (InlineStack.size() > Depth) {
244           InlineStack.pop_back();
245         }
246         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
247             LineLocation(LineOffset, Discriminator))[FName];
248         FSamples.setName(FName);
249         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
250         InlineStack.push_back(&FSamples);
251       } else {
252         while (InlineStack.size() > Depth) {
253           InlineStack.pop_back();
254         }
255         FunctionSamples &FProfile = *InlineStack.back();
256         for (const auto &name_count : TargetCountMap) {
257           MergeResult(Result, FProfile.addCalledTargetSamples(
258                                   LineOffset, Discriminator, name_count.first,
259                                   name_count.second));
260         }
261         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
262                                                     NumSamples));
263       }
264     }
265   }
266   if (Result == sampleprof_error::success)
267     computeSummary();
268 
269   return Result;
270 }
271 
272 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
273   bool result = false;
274 
275   // Check that the first non-comment line is a valid function header.
276   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
277   if (!LineIt.is_at_eof()) {
278     if ((*LineIt)[0] != ' ') {
279       uint64_t NumSamples, NumHeadSamples;
280       StringRef FName;
281       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
282     }
283   }
284 
285   return result;
286 }
287 
288 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
289   unsigned NumBytesRead = 0;
290   std::error_code EC;
291   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
292 
293   if (Val > std::numeric_limits<T>::max())
294     EC = sampleprof_error::malformed;
295   else if (Data + NumBytesRead > End)
296     EC = sampleprof_error::truncated;
297   else
298     EC = sampleprof_error::success;
299 
300   if (EC) {
301     reportError(0, EC.message());
302     return EC;
303   }
304 
305   Data += NumBytesRead;
306   return static_cast<T>(Val);
307 }
308 
309 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
310   std::error_code EC;
311   StringRef Str(reinterpret_cast<const char *>(Data));
312   if (Data + Str.size() + 1 > End) {
313     EC = sampleprof_error::truncated;
314     reportError(0, EC.message());
315     return EC;
316   }
317 
318   Data += Str.size() + 1;
319   return Str;
320 }
321 
322 template <typename T>
323 ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
324   std::error_code EC;
325 
326   if (Data + sizeof(T) > End) {
327     EC = sampleprof_error::truncated;
328     reportError(0, EC.message());
329     return EC;
330   }
331 
332   using namespace support;
333   T Val = endian::readNext<T, little, unaligned>(Data);
334   return Val;
335 }
336 
337 template <typename T>
338 inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
339   std::error_code EC;
340   auto Idx = readNumber<uint32_t>();
341   if (std::error_code EC = Idx.getError())
342     return EC;
343   if (*Idx >= Table.size())
344     return sampleprof_error::truncated_name_table;
345   return *Idx;
346 }
347 
348 ErrorOr<StringRef> SampleProfileReaderRawBinary::readStringFromTable() {
349   auto Idx = readStringIndex(NameTable);
350   if (std::error_code EC = Idx.getError())
351     return EC;
352 
353   return NameTable[*Idx];
354 }
355 
356 ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
357   auto Idx = readStringIndex(NameTable);
358   if (std::error_code EC = Idx.getError())
359     return EC;
360 
361   return StringRef(NameTable[*Idx]);
362 }
363 
364 std::error_code
365 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
366   auto NumSamples = readNumber<uint64_t>();
367   if (std::error_code EC = NumSamples.getError())
368     return EC;
369   FProfile.addTotalSamples(*NumSamples);
370 
371   // Read the samples in the body.
372   auto NumRecords = readNumber<uint32_t>();
373   if (std::error_code EC = NumRecords.getError())
374     return EC;
375 
376   for (uint32_t I = 0; I < *NumRecords; ++I) {
377     auto LineOffset = readNumber<uint64_t>();
378     if (std::error_code EC = LineOffset.getError())
379       return EC;
380 
381     if (!isOffsetLegal(*LineOffset)) {
382       return std::error_code();
383     }
384 
385     auto Discriminator = readNumber<uint64_t>();
386     if (std::error_code EC = Discriminator.getError())
387       return EC;
388 
389     auto NumSamples = readNumber<uint64_t>();
390     if (std::error_code EC = NumSamples.getError())
391       return EC;
392 
393     auto NumCalls = readNumber<uint32_t>();
394     if (std::error_code EC = NumCalls.getError())
395       return EC;
396 
397     for (uint32_t J = 0; J < *NumCalls; ++J) {
398       auto CalledFunction(readStringFromTable());
399       if (std::error_code EC = CalledFunction.getError())
400         return EC;
401 
402       auto CalledFunctionSamples = readNumber<uint64_t>();
403       if (std::error_code EC = CalledFunctionSamples.getError())
404         return EC;
405 
406       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
407                                       *CalledFunction, *CalledFunctionSamples);
408     }
409 
410     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
411   }
412 
413   // Read all the samples for inlined function calls.
414   auto NumCallsites = readNumber<uint32_t>();
415   if (std::error_code EC = NumCallsites.getError())
416     return EC;
417 
418   for (uint32_t J = 0; J < *NumCallsites; ++J) {
419     auto LineOffset = readNumber<uint64_t>();
420     if (std::error_code EC = LineOffset.getError())
421       return EC;
422 
423     auto Discriminator = readNumber<uint64_t>();
424     if (std::error_code EC = Discriminator.getError())
425       return EC;
426 
427     auto FName(readStringFromTable());
428     if (std::error_code EC = FName.getError())
429       return EC;
430 
431     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
432         LineLocation(*LineOffset, *Discriminator))[*FName];
433     CalleeProfile.setName(*FName);
434     if (std::error_code EC = readProfile(CalleeProfile))
435       return EC;
436   }
437 
438   return sampleprof_error::success;
439 }
440 
441 std::error_code SampleProfileReaderBinary::readFuncProfile() {
442   auto NumHeadSamples = readNumber<uint64_t>();
443   if (std::error_code EC = NumHeadSamples.getError())
444     return EC;
445 
446   auto FName(readStringFromTable());
447   if (std::error_code EC = FName.getError())
448     return EC;
449 
450   Profiles[*FName] = FunctionSamples();
451   FunctionSamples &FProfile = Profiles[*FName];
452   FProfile.setName(*FName);
453 
454   FProfile.addHeadSamples(*NumHeadSamples);
455 
456   if (std::error_code EC = readProfile(FProfile))
457     return EC;
458   return sampleprof_error::success;
459 }
460 
461 std::error_code SampleProfileReaderBinary::read() {
462   while (!at_eof()) {
463     if (std::error_code EC = readFuncProfile())
464       return EC;
465   }
466 
467   return sampleprof_error::success;
468 }
469 
470 std::error_code SampleProfileReaderCompactBinary::read() {
471   std::vector<uint64_t> OffsetsToUse;
472   if (UseAllFuncs) {
473     for (auto FuncEntry : FuncOffsetTable) {
474       OffsetsToUse.push_back(FuncEntry.second);
475     }
476   }
477   else {
478     for (auto Name : FuncsToUse) {
479       auto GUID = std::to_string(MD5Hash(Name));
480       auto iter = FuncOffsetTable.find(StringRef(GUID));
481       if (iter == FuncOffsetTable.end())
482         continue;
483       OffsetsToUse.push_back(iter->second);
484     }
485   }
486 
487   for (auto Offset : OffsetsToUse) {
488     const uint8_t *SavedData = Data;
489     Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
490            Offset;
491     if (std::error_code EC = readFuncProfile())
492       return EC;
493     Data = SavedData;
494   }
495   return sampleprof_error::success;
496 }
497 
498 std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
499   if (Magic == SPMagic())
500     return sampleprof_error::success;
501   return sampleprof_error::bad_magic;
502 }
503 
504 std::error_code
505 SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
506   if (Magic == SPMagic(SPF_Compact_Binary))
507     return sampleprof_error::success;
508   return sampleprof_error::bad_magic;
509 }
510 
511 std::error_code SampleProfileReaderRawBinary::readNameTable() {
512   auto Size = readNumber<uint32_t>();
513   if (std::error_code EC = Size.getError())
514     return EC;
515   NameTable.reserve(*Size);
516   for (uint32_t I = 0; I < *Size; ++I) {
517     auto Name(readString());
518     if (std::error_code EC = Name.getError())
519       return EC;
520     NameTable.push_back(*Name);
521   }
522 
523   return sampleprof_error::success;
524 }
525 
526 std::error_code SampleProfileReaderCompactBinary::readNameTable() {
527   auto Size = readNumber<uint64_t>();
528   if (std::error_code EC = Size.getError())
529     return EC;
530   NameTable.reserve(*Size);
531   for (uint32_t I = 0; I < *Size; ++I) {
532     auto FID = readNumber<uint64_t>();
533     if (std::error_code EC = FID.getError())
534       return EC;
535     NameTable.push_back(std::to_string(*FID));
536   }
537   return sampleprof_error::success;
538 }
539 
540 std::error_code SampleProfileReaderBinary::readHeader() {
541   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
542   End = Data + Buffer->getBufferSize();
543 
544   // Read and check the magic identifier.
545   auto Magic = readNumber<uint64_t>();
546   if (std::error_code EC = Magic.getError())
547     return EC;
548   else if (std::error_code EC = verifySPMagic(*Magic))
549     return EC;
550 
551   // Read the version number.
552   auto Version = readNumber<uint64_t>();
553   if (std::error_code EC = Version.getError())
554     return EC;
555   else if (*Version != SPVersion())
556     return sampleprof_error::unsupported_version;
557 
558   if (std::error_code EC = readSummary())
559     return EC;
560 
561   if (std::error_code EC = readNameTable())
562     return EC;
563   return sampleprof_error::success;
564 }
565 
566 std::error_code SampleProfileReaderCompactBinary::readHeader() {
567   SampleProfileReaderBinary::readHeader();
568   if (std::error_code EC = readFuncOffsetTable())
569     return EC;
570   return sampleprof_error::success;
571 }
572 
573 std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
574   auto TableOffset = readUnencodedNumber<uint64_t>();
575   if (std::error_code EC = TableOffset.getError())
576     return EC;
577 
578   const uint8_t *SavedData = Data;
579   const uint8_t *TableStart =
580       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
581       *TableOffset;
582   Data = TableStart;
583 
584   auto Size = readNumber<uint64_t>();
585   if (std::error_code EC = Size.getError())
586     return EC;
587 
588   FuncOffsetTable.reserve(*Size);
589   for (uint32_t I = 0; I < *Size; ++I) {
590     auto FName(readStringFromTable());
591     if (std::error_code EC = FName.getError())
592       return EC;
593 
594     auto Offset = readNumber<uint64_t>();
595     if (std::error_code EC = Offset.getError())
596       return EC;
597 
598     FuncOffsetTable[*FName] = *Offset;
599   }
600   End = TableStart;
601   Data = SavedData;
602   return sampleprof_error::success;
603 }
604 
605 void SampleProfileReaderCompactBinary::collectFuncsToUse(const Module &M) {
606   UseAllFuncs = false;
607   FuncsToUse.clear();
608   for (auto &F : M) {
609     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
610     FuncsToUse.insert(CanonName);
611   }
612 }
613 
614 std::error_code SampleProfileReaderBinary::readSummaryEntry(
615     std::vector<ProfileSummaryEntry> &Entries) {
616   auto Cutoff = readNumber<uint64_t>();
617   if (std::error_code EC = Cutoff.getError())
618     return EC;
619 
620   auto MinBlockCount = readNumber<uint64_t>();
621   if (std::error_code EC = MinBlockCount.getError())
622     return EC;
623 
624   auto NumBlocks = readNumber<uint64_t>();
625   if (std::error_code EC = NumBlocks.getError())
626     return EC;
627 
628   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
629   return sampleprof_error::success;
630 }
631 
632 std::error_code SampleProfileReaderBinary::readSummary() {
633   auto TotalCount = readNumber<uint64_t>();
634   if (std::error_code EC = TotalCount.getError())
635     return EC;
636 
637   auto MaxBlockCount = readNumber<uint64_t>();
638   if (std::error_code EC = MaxBlockCount.getError())
639     return EC;
640 
641   auto MaxFunctionCount = readNumber<uint64_t>();
642   if (std::error_code EC = MaxFunctionCount.getError())
643     return EC;
644 
645   auto NumBlocks = readNumber<uint64_t>();
646   if (std::error_code EC = NumBlocks.getError())
647     return EC;
648 
649   auto NumFunctions = readNumber<uint64_t>();
650   if (std::error_code EC = NumFunctions.getError())
651     return EC;
652 
653   auto NumSummaryEntries = readNumber<uint64_t>();
654   if (std::error_code EC = NumSummaryEntries.getError())
655     return EC;
656 
657   std::vector<ProfileSummaryEntry> Entries;
658   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
659     std::error_code EC = readSummaryEntry(Entries);
660     if (EC != sampleprof_error::success)
661       return EC;
662   }
663   Summary = std::make_unique<ProfileSummary>(
664       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
665       *MaxFunctionCount, *NumBlocks, *NumFunctions);
666 
667   return sampleprof_error::success;
668 }
669 
670 bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
671   const uint8_t *Data =
672       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
673   uint64_t Magic = decodeULEB128(Data);
674   return Magic == SPMagic();
675 }
676 
677 bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
678   const uint8_t *Data =
679       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
680   uint64_t Magic = decodeULEB128(Data);
681   return Magic == SPMagic(SPF_Compact_Binary);
682 }
683 
684 std::error_code SampleProfileReaderGCC::skipNextWord() {
685   uint32_t dummy;
686   if (!GcovBuffer.readInt(dummy))
687     return sampleprof_error::truncated;
688   return sampleprof_error::success;
689 }
690 
691 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
692   if (sizeof(T) <= sizeof(uint32_t)) {
693     uint32_t Val;
694     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
695       return static_cast<T>(Val);
696   } else if (sizeof(T) <= sizeof(uint64_t)) {
697     uint64_t Val;
698     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
699       return static_cast<T>(Val);
700   }
701 
702   std::error_code EC = sampleprof_error::malformed;
703   reportError(0, EC.message());
704   return EC;
705 }
706 
707 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
708   StringRef Str;
709   if (!GcovBuffer.readString(Str))
710     return sampleprof_error::truncated;
711   return Str;
712 }
713 
714 std::error_code SampleProfileReaderGCC::readHeader() {
715   // Read the magic identifier.
716   if (!GcovBuffer.readGCDAFormat())
717     return sampleprof_error::unrecognized_format;
718 
719   // Read the version number. Note - the GCC reader does not validate this
720   // version, but the profile creator generates v704.
721   GCOV::GCOVVersion version;
722   if (!GcovBuffer.readGCOVVersion(version))
723     return sampleprof_error::unrecognized_format;
724 
725   if (version != GCOV::V704)
726     return sampleprof_error::unsupported_version;
727 
728   // Skip the empty integer.
729   if (std::error_code EC = skipNextWord())
730     return EC;
731 
732   return sampleprof_error::success;
733 }
734 
735 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
736   uint32_t Tag;
737   if (!GcovBuffer.readInt(Tag))
738     return sampleprof_error::truncated;
739 
740   if (Tag != Expected)
741     return sampleprof_error::malformed;
742 
743   if (std::error_code EC = skipNextWord())
744     return EC;
745 
746   return sampleprof_error::success;
747 }
748 
749 std::error_code SampleProfileReaderGCC::readNameTable() {
750   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
751     return EC;
752 
753   uint32_t Size;
754   if (!GcovBuffer.readInt(Size))
755     return sampleprof_error::truncated;
756 
757   for (uint32_t I = 0; I < Size; ++I) {
758     StringRef Str;
759     if (!GcovBuffer.readString(Str))
760       return sampleprof_error::truncated;
761     Names.push_back(Str);
762   }
763 
764   return sampleprof_error::success;
765 }
766 
767 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
768   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
769     return EC;
770 
771   uint32_t NumFunctions;
772   if (!GcovBuffer.readInt(NumFunctions))
773     return sampleprof_error::truncated;
774 
775   InlineCallStack Stack;
776   for (uint32_t I = 0; I < NumFunctions; ++I)
777     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
778       return EC;
779 
780   computeSummary();
781   return sampleprof_error::success;
782 }
783 
784 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
785     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
786   uint64_t HeadCount = 0;
787   if (InlineStack.size() == 0)
788     if (!GcovBuffer.readInt64(HeadCount))
789       return sampleprof_error::truncated;
790 
791   uint32_t NameIdx;
792   if (!GcovBuffer.readInt(NameIdx))
793     return sampleprof_error::truncated;
794 
795   StringRef Name(Names[NameIdx]);
796 
797   uint32_t NumPosCounts;
798   if (!GcovBuffer.readInt(NumPosCounts))
799     return sampleprof_error::truncated;
800 
801   uint32_t NumCallsites;
802   if (!GcovBuffer.readInt(NumCallsites))
803     return sampleprof_error::truncated;
804 
805   FunctionSamples *FProfile = nullptr;
806   if (InlineStack.size() == 0) {
807     // If this is a top function that we have already processed, do not
808     // update its profile again.  This happens in the presence of
809     // function aliases.  Since these aliases share the same function
810     // body, there will be identical replicated profiles for the
811     // original function.  In this case, we simply not bother updating
812     // the profile of the original function.
813     FProfile = &Profiles[Name];
814     FProfile->addHeadSamples(HeadCount);
815     if (FProfile->getTotalSamples() > 0)
816       Update = false;
817   } else {
818     // Otherwise, we are reading an inlined instance. The top of the
819     // inline stack contains the profile of the caller. Insert this
820     // callee in the caller's CallsiteMap.
821     FunctionSamples *CallerProfile = InlineStack.front();
822     uint32_t LineOffset = Offset >> 16;
823     uint32_t Discriminator = Offset & 0xffff;
824     FProfile = &CallerProfile->functionSamplesAt(
825         LineLocation(LineOffset, Discriminator))[Name];
826   }
827   FProfile->setName(Name);
828 
829   for (uint32_t I = 0; I < NumPosCounts; ++I) {
830     uint32_t Offset;
831     if (!GcovBuffer.readInt(Offset))
832       return sampleprof_error::truncated;
833 
834     uint32_t NumTargets;
835     if (!GcovBuffer.readInt(NumTargets))
836       return sampleprof_error::truncated;
837 
838     uint64_t Count;
839     if (!GcovBuffer.readInt64(Count))
840       return sampleprof_error::truncated;
841 
842     // The line location is encoded in the offset as:
843     //   high 16 bits: line offset to the start of the function.
844     //   low 16 bits: discriminator.
845     uint32_t LineOffset = Offset >> 16;
846     uint32_t Discriminator = Offset & 0xffff;
847 
848     InlineCallStack NewStack;
849     NewStack.push_back(FProfile);
850     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
851     if (Update) {
852       // Walk up the inline stack, adding the samples on this line to
853       // the total sample count of the callers in the chain.
854       for (auto CallerProfile : NewStack)
855         CallerProfile->addTotalSamples(Count);
856 
857       // Update the body samples for the current profile.
858       FProfile->addBodySamples(LineOffset, Discriminator, Count);
859     }
860 
861     // Process the list of functions called at an indirect call site.
862     // These are all the targets that a function pointer (or virtual
863     // function) resolved at runtime.
864     for (uint32_t J = 0; J < NumTargets; J++) {
865       uint32_t HistVal;
866       if (!GcovBuffer.readInt(HistVal))
867         return sampleprof_error::truncated;
868 
869       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
870         return sampleprof_error::malformed;
871 
872       uint64_t TargetIdx;
873       if (!GcovBuffer.readInt64(TargetIdx))
874         return sampleprof_error::truncated;
875       StringRef TargetName(Names[TargetIdx]);
876 
877       uint64_t TargetCount;
878       if (!GcovBuffer.readInt64(TargetCount))
879         return sampleprof_error::truncated;
880 
881       if (Update)
882         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
883                                          TargetName, TargetCount);
884     }
885   }
886 
887   // Process all the inlined callers into the current function. These
888   // are all the callsites that were inlined into this function.
889   for (uint32_t I = 0; I < NumCallsites; I++) {
890     // The offset is encoded as:
891     //   high 16 bits: line offset to the start of the function.
892     //   low 16 bits: discriminator.
893     uint32_t Offset;
894     if (!GcovBuffer.readInt(Offset))
895       return sampleprof_error::truncated;
896     InlineCallStack NewStack;
897     NewStack.push_back(FProfile);
898     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
899     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
900       return EC;
901   }
902 
903   return sampleprof_error::success;
904 }
905 
906 /// Read a GCC AutoFDO profile.
907 ///
908 /// This format is generated by the Linux Perf conversion tool at
909 /// https://github.com/google/autofdo.
910 std::error_code SampleProfileReaderGCC::read() {
911   // Read the string table.
912   if (std::error_code EC = readNameTable())
913     return EC;
914 
915   // Read the source profile.
916   if (std::error_code EC = readFunctionProfiles())
917     return EC;
918 
919   return sampleprof_error::success;
920 }
921 
922 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
923   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
924   return Magic == "adcg*704";
925 }
926 
927 std::error_code SampleProfileReaderItaniumRemapper::read() {
928   // If the underlying data is in compact format, we can't remap it because
929   // we don't know what the original function names were.
930   if (getFormat() == SPF_Compact_Binary) {
931     Ctx.diagnose(DiagnosticInfoSampleProfile(
932         Buffer->getBufferIdentifier(),
933         "Profile data remapping cannot be applied to profile data "
934         "in compact format (original mangled names are not available).",
935         DS_Warning));
936     return sampleprof_error::success;
937   }
938 
939   if (Error E = Remappings.read(*Buffer)) {
940     handleAllErrors(
941         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
942           reportError(ParseError.getLineNum(), ParseError.getMessage());
943         });
944     return sampleprof_error::malformed;
945   }
946 
947   for (auto &Sample : getProfiles())
948     if (auto Key = Remappings.insert(Sample.first()))
949       SampleMap.insert({Key, &Sample.second});
950 
951   return sampleprof_error::success;
952 }
953 
954 FunctionSamples *
955 SampleProfileReaderItaniumRemapper::getSamplesFor(StringRef Fname) {
956   if (auto Key = Remappings.lookup(Fname))
957     return SampleMap.lookup(Key);
958   return SampleProfileReader::getSamplesFor(Fname);
959 }
960 
961 /// Prepare a memory buffer for the contents of \p Filename.
962 ///
963 /// \returns an error code indicating the status of the buffer.
964 static ErrorOr<std::unique_ptr<MemoryBuffer>>
965 setupMemoryBuffer(const Twine &Filename) {
966   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
967   if (std::error_code EC = BufferOrErr.getError())
968     return EC;
969   auto Buffer = std::move(BufferOrErr.get());
970 
971   // Sanity check the file.
972   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
973     return sampleprof_error::too_large;
974 
975   return std::move(Buffer);
976 }
977 
978 /// Create a sample profile reader based on the format of the input file.
979 ///
980 /// \param Filename The file to open.
981 ///
982 /// \param C The LLVM context to use to emit diagnostics.
983 ///
984 /// \returns an error code indicating the status of the created reader.
985 ErrorOr<std::unique_ptr<SampleProfileReader>>
986 SampleProfileReader::create(const Twine &Filename, LLVMContext &C) {
987   auto BufferOrError = setupMemoryBuffer(Filename);
988   if (std::error_code EC = BufferOrError.getError())
989     return EC;
990   return create(BufferOrError.get(), C);
991 }
992 
993 /// Create a sample profile remapper from the given input, to remap the
994 /// function names in the given profile data.
995 ///
996 /// \param Filename The file to open.
997 ///
998 /// \param C The LLVM context to use to emit diagnostics.
999 ///
1000 /// \param Underlying The underlying profile data reader to remap.
1001 ///
1002 /// \returns an error code indicating the status of the created reader.
1003 ErrorOr<std::unique_ptr<SampleProfileReader>>
1004 SampleProfileReaderItaniumRemapper::create(
1005     const Twine &Filename, LLVMContext &C,
1006     std::unique_ptr<SampleProfileReader> Underlying) {
1007   auto BufferOrError = setupMemoryBuffer(Filename);
1008   if (std::error_code EC = BufferOrError.getError())
1009     return EC;
1010   return std::make_unique<SampleProfileReaderItaniumRemapper>(
1011       std::move(BufferOrError.get()), C, std::move(Underlying));
1012 }
1013 
1014 /// Create a sample profile reader based on the format of the input data.
1015 ///
1016 /// \param B The memory buffer to create the reader from (assumes ownership).
1017 ///
1018 /// \param C The LLVM context to use to emit diagnostics.
1019 ///
1020 /// \returns an error code indicating the status of the created reader.
1021 ErrorOr<std::unique_ptr<SampleProfileReader>>
1022 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
1023   std::unique_ptr<SampleProfileReader> Reader;
1024   if (SampleProfileReaderRawBinary::hasFormat(*B))
1025     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1026   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1027     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
1028   else if (SampleProfileReaderGCC::hasFormat(*B))
1029     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1030   else if (SampleProfileReaderText::hasFormat(*B))
1031     Reader.reset(new SampleProfileReaderText(std::move(B), C));
1032   else
1033     return sampleprof_error::unrecognized_format;
1034 
1035   FunctionSamples::Format = Reader->getFormat();
1036   if (std::error_code EC = Reader->readHeader())
1037     return EC;
1038 
1039   return std::move(Reader);
1040 }
1041 
1042 // For text and GCC file formats, we compute the summary after reading the
1043 // profile. Binary format has the profile summary in its header.
1044 void SampleProfileReader::computeSummary() {
1045   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1046   for (const auto &I : Profiles) {
1047     const FunctionSamples &Profile = I.second;
1048     Builder.addRecord(Profile);
1049   }
1050   Summary = Builder.getSummary();
1051 }
1052