SamplePGO - Add dump routines for LineLocation, SampleRecord and FunctionSamples
[oota-llvm.git] / lib / ProfileData / SampleProfReader.cpp
1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the class that reads LLVM sample profiles. It
11 // supports three file formats: text, binary and gcov.
12 //
13 // The textual representation is useful for debugging and testing purposes. The
14 // binary representation is more compact, resulting in smaller file sizes.
15 //
16 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17 // tool (https://github.com/google/autofdo)
18 //
19 // All three encodings can be used interchangeably as an input sample profile.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/ProfileData/SampleProfReader.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorOr.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/LineIterator.h"
30 #include "llvm/Support/MemoryBuffer.h"
31
32 using namespace llvm::sampleprof;
33 using namespace llvm;
34
35 /// \brief Dump the function profile for \p FName.
36 ///
37 /// \param FName Name of the function to print.
38 /// \param OS Stream to emit the output to.
39 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
40                                               raw_ostream &OS) {
41   OS << "Function: " << FName << ": " << Profiles[FName];
42 }
43
44 /// \brief Dump all the function profiles found on stream \p OS.
45 void SampleProfileReader::dump(raw_ostream &OS) {
46   for (const auto &I : Profiles)
47     dumpFunctionProfile(I.getKey(), OS);
48 }
49
50 /// \brief Parse \p Input as function head.
51 ///
52 /// Parse one line of \p Input, and update function name in \p FName,
53 /// function's total sample count in \p NumSamples, function's entry
54 /// count in \p NumHeadSamples.
55 ///
56 /// \returns true if parsing is successful.
57 static bool ParseHead(const StringRef &Input, StringRef &FName,
58                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
59   if (Input[0] == ' ')
60     return false;
61   size_t n2 = Input.rfind(':');
62   size_t n1 = Input.rfind(':', n2 - 1);
63   FName = Input.substr(0, n1);
64   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
65     return false;
66   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
67     return false;
68   return true;
69 }
70
71
72 /// \brief Returns true if line offset \p L is legal (only has 16 bits).
73 static bool isOffsetLegal(unsigned L) {
74   return (L & 0xffff) == L;
75 }
76
77 /// \brief Parse \p Input as line sample.
78 ///
79 /// \param Input input line.
80 /// \param IsCallsite true if the line represents an inlined callsite.
81 /// \param Depth the depth of the inline stack.
82 /// \param NumSamples total samples of the line/inlined callsite.
83 /// \param LineOffset line offset to the start of the function.
84 /// \param Discriminator discriminator of the line.
85 /// \param TargetCountMap map from indirect call target to count.
86 ///
87 /// returns true if parsing is successful.
88 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
89                       uint64_t &NumSamples, uint32_t &LineOffset,
90                       uint32_t &Discriminator, StringRef &CalleeName,
91                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
92   for (Depth = 0; Input[Depth] == ' '; Depth++)
93     ;
94   if (Depth == 0)
95     return false;
96
97   size_t n1 = Input.find(':');
98   StringRef Loc = Input.substr(Depth, n1 - Depth);
99   size_t n2 = Loc.find('.');
100   if (n2 == StringRef::npos) {
101     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
102       return false;
103     Discriminator = 0;
104   } else {
105     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
106       return false;
107     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
108       return false;
109   }
110
111   StringRef Rest = Input.substr(n1 + 2);
112   if (Rest[0] >= '0' && Rest[0] <= '9') {
113     IsCallsite = false;
114     size_t n3 = Rest.find(' ');
115     if (n3 == StringRef::npos) {
116       if (Rest.getAsInteger(10, NumSamples))
117         return false;
118     } else {
119       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
120         return false;
121     }
122     while (n3 != StringRef::npos) {
123       n3 += Rest.substr(n3).find_first_not_of(' ');
124       Rest = Rest.substr(n3);
125       n3 = Rest.find(' ');
126       StringRef pair = Rest;
127       if (n3 != StringRef::npos) {
128         pair = Rest.substr(0, n3);
129       }
130       size_t n4 = pair.find(':');
131       uint64_t count;
132       if (pair.substr(n4 + 1).getAsInteger(10, count))
133         return false;
134       TargetCountMap[pair.substr(0, n4)] = count;
135     }
136   } else {
137     IsCallsite = true;
138     size_t n3 = Rest.find_last_of(':');
139     CalleeName = Rest.substr(0, n3);
140     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
141       return false;
142   }
143   return true;
144 }
145
146 /// \brief Load samples from a text file.
147 ///
148 /// See the documentation at the top of the file for an explanation of
149 /// the expected format.
150 ///
151 /// \returns true if the file was loaded successfully, false otherwise.
152 std::error_code SampleProfileReaderText::read() {
153   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
154
155   InlineCallStack InlineStack;
156
157   for (; !LineIt.is_at_eof(); ++LineIt) {
158     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
159       continue;
160     // Read the header of each function.
161     //
162     // Note that for function identifiers we are actually expecting
163     // mangled names, but we may not always get them. This happens when
164     // the compiler decides not to emit the function (e.g., it was inlined
165     // and removed). In this case, the binary will not have the linkage
166     // name for the function, so the profiler will emit the function's
167     // unmangled name, which may contain characters like ':' and '>' in its
168     // name (member functions, templates, etc).
169     //
170     // The only requirement we place on the identifier, then, is that it
171     // should not begin with a number.
172     if ((*LineIt)[0] != ' ') {
173       uint64_t NumSamples, NumHeadSamples;
174       StringRef FName;
175       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
176         reportError(LineIt.line_number(),
177                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
178         return sampleprof_error::malformed;
179       }
180       Profiles[FName] = FunctionSamples();
181       FunctionSamples &FProfile = Profiles[FName];
182       FProfile.addTotalSamples(NumSamples);
183       FProfile.addHeadSamples(NumHeadSamples);
184       InlineStack.clear();
185       InlineStack.push_back(&FProfile);
186     } else {
187       uint64_t NumSamples;
188       StringRef FName;
189       DenseMap<StringRef, uint64_t> TargetCountMap;
190       bool IsCallsite;
191       uint32_t Depth, LineOffset, Discriminator;
192       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
193                      Discriminator, FName, TargetCountMap)) {
194         reportError(LineIt.line_number(),
195                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
196                         *LineIt);
197         return sampleprof_error::malformed;
198       }
199       if (IsCallsite) {
200         while (InlineStack.size() > Depth) {
201           InlineStack.pop_back();
202         }
203         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
204             CallsiteLocation(LineOffset, Discriminator, FName));
205         FSamples.addTotalSamples(NumSamples);
206         InlineStack.push_back(&FSamples);
207       } else {
208         while (InlineStack.size() > Depth) {
209           InlineStack.pop_back();
210         }
211         FunctionSamples &FProfile = *InlineStack.back();
212         for (const auto &name_count : TargetCountMap) {
213           FProfile.addCalledTargetSamples(LineOffset, Discriminator,
214                                           name_count.first, name_count.second);
215         }
216         FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
217       }
218     }
219   }
220
221   return sampleprof_error::success;
222 }
223
224 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
225   bool result = false;
226
227   // Check that the first non-comment line is a valid function header.
228   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
229   if (!LineIt.is_at_eof()) {
230     if ((*LineIt)[0] != ' ') {
231       uint64_t NumSamples, NumHeadSamples;
232       StringRef FName;
233       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
234     }
235   }
236
237   return result;
238 }
239
240 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
241   unsigned NumBytesRead = 0;
242   std::error_code EC;
243   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
244
245   if (Val > std::numeric_limits<T>::max())
246     EC = sampleprof_error::malformed;
247   else if (Data + NumBytesRead > End)
248     EC = sampleprof_error::truncated;
249   else
250     EC = sampleprof_error::success;
251
252   if (EC) {
253     reportError(0, EC.message());
254     return EC;
255   }
256
257   Data += NumBytesRead;
258   return static_cast<T>(Val);
259 }
260
261 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
262   std::error_code EC;
263   StringRef Str(reinterpret_cast<const char *>(Data));
264   if (Data + Str.size() + 1 > End) {
265     EC = sampleprof_error::truncated;
266     reportError(0, EC.message());
267     return EC;
268   }
269
270   Data += Str.size() + 1;
271   return Str;
272 }
273
274 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
275   std::error_code EC;
276   auto Idx = readNumber<uint32_t>();
277   if (std::error_code EC = Idx.getError())
278     return EC;
279   if (*Idx >= NameTable.size())
280     return sampleprof_error::truncated_name_table;
281   return NameTable[*Idx];
282 }
283
284 std::error_code
285 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
286   auto NumSamples = readNumber<uint64_t>();
287   if (std::error_code EC = NumSamples.getError())
288     return EC;
289   FProfile.addTotalSamples(*NumSamples);
290
291   // Read the samples in the body.
292   auto NumRecords = readNumber<uint32_t>();
293   if (std::error_code EC = NumRecords.getError())
294     return EC;
295
296   for (uint32_t I = 0; I < *NumRecords; ++I) {
297     auto LineOffset = readNumber<uint64_t>();
298     if (std::error_code EC = LineOffset.getError())
299       return EC;
300
301     if (!isOffsetLegal(*LineOffset)) {
302       return std::error_code();
303     }
304
305     auto Discriminator = readNumber<uint64_t>();
306     if (std::error_code EC = Discriminator.getError())
307       return EC;
308
309     auto NumSamples = readNumber<uint64_t>();
310     if (std::error_code EC = NumSamples.getError())
311       return EC;
312
313     auto NumCalls = readNumber<uint32_t>();
314     if (std::error_code EC = NumCalls.getError())
315       return EC;
316
317     for (uint32_t J = 0; J < *NumCalls; ++J) {
318       auto CalledFunction(readStringFromTable());
319       if (std::error_code EC = CalledFunction.getError())
320         return EC;
321
322       auto CalledFunctionSamples = readNumber<uint64_t>();
323       if (std::error_code EC = CalledFunctionSamples.getError())
324         return EC;
325
326       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
327                                       *CalledFunction, *CalledFunctionSamples);
328     }
329
330     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
331   }
332
333   // Read all the samples for inlined function calls.
334   auto NumCallsites = readNumber<uint32_t>();
335   if (std::error_code EC = NumCallsites.getError())
336     return EC;
337
338   for (uint32_t J = 0; J < *NumCallsites; ++J) {
339     auto LineOffset = readNumber<uint64_t>();
340     if (std::error_code EC = LineOffset.getError())
341       return EC;
342
343     auto Discriminator = readNumber<uint64_t>();
344     if (std::error_code EC = Discriminator.getError())
345       return EC;
346
347     auto FName(readStringFromTable());
348     if (std::error_code EC = FName.getError())
349       return EC;
350
351     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
352         CallsiteLocation(*LineOffset, *Discriminator, *FName));
353     if (std::error_code EC = readProfile(CalleeProfile))
354       return EC;
355   }
356
357   return sampleprof_error::success;
358 }
359
360 std::error_code SampleProfileReaderBinary::read() {
361   while (!at_eof()) {
362     auto NumHeadSamples = readNumber<uint64_t>();
363     if (std::error_code EC = NumHeadSamples.getError())
364       return EC;
365
366     auto FName(readStringFromTable());
367     if (std::error_code EC = FName.getError())
368       return EC;
369
370     Profiles[*FName] = FunctionSamples();
371     FunctionSamples &FProfile = Profiles[*FName];
372
373     FProfile.addHeadSamples(*NumHeadSamples);
374
375     if (std::error_code EC = readProfile(FProfile))
376       return EC;
377   }
378
379   return sampleprof_error::success;
380 }
381
382 std::error_code SampleProfileReaderBinary::readHeader() {
383   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
384   End = Data + Buffer->getBufferSize();
385
386   // Read and check the magic identifier.
387   auto Magic = readNumber<uint64_t>();
388   if (std::error_code EC = Magic.getError())
389     return EC;
390   else if (*Magic != SPMagic())
391     return sampleprof_error::bad_magic;
392
393   // Read the version number.
394   auto Version = readNumber<uint64_t>();
395   if (std::error_code EC = Version.getError())
396     return EC;
397   else if (*Version != SPVersion())
398     return sampleprof_error::unsupported_version;
399
400   // Read the name table.
401   auto Size = readNumber<uint32_t>();
402   if (std::error_code EC = Size.getError())
403     return EC;
404   NameTable.reserve(*Size);
405   for (uint32_t I = 0; I < *Size; ++I) {
406     auto Name(readString());
407     if (std::error_code EC = Name.getError())
408       return EC;
409     NameTable.push_back(*Name);
410   }
411
412   return sampleprof_error::success;
413 }
414
415 bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
416   const uint8_t *Data =
417       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
418   uint64_t Magic = decodeULEB128(Data);
419   return Magic == SPMagic();
420 }
421
422 std::error_code SampleProfileReaderGCC::skipNextWord() {
423   uint32_t dummy;
424   if (!GcovBuffer.readInt(dummy))
425     return sampleprof_error::truncated;
426   return sampleprof_error::success;
427 }
428
429 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
430   if (sizeof(T) <= sizeof(uint32_t)) {
431     uint32_t Val;
432     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
433       return static_cast<T>(Val);
434   } else if (sizeof(T) <= sizeof(uint64_t)) {
435     uint64_t Val;
436     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
437       return static_cast<T>(Val);
438   }
439
440   std::error_code EC = sampleprof_error::malformed;
441   reportError(0, EC.message());
442   return EC;
443 }
444
445 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
446   StringRef Str;
447   if (!GcovBuffer.readString(Str))
448     return sampleprof_error::truncated;
449   return Str;
450 }
451
452 std::error_code SampleProfileReaderGCC::readHeader() {
453   // Read the magic identifier.
454   if (!GcovBuffer.readGCDAFormat())
455     return sampleprof_error::unrecognized_format;
456
457   // Read the version number. Note - the GCC reader does not validate this
458   // version, but the profile creator generates v704.
459   GCOV::GCOVVersion version;
460   if (!GcovBuffer.readGCOVVersion(version))
461     return sampleprof_error::unrecognized_format;
462
463   if (version != GCOV::V704)
464     return sampleprof_error::unsupported_version;
465
466   // Skip the empty integer.
467   if (std::error_code EC = skipNextWord())
468     return EC;
469
470   return sampleprof_error::success;
471 }
472
473 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
474   uint32_t Tag;
475   if (!GcovBuffer.readInt(Tag))
476     return sampleprof_error::truncated;
477
478   if (Tag != Expected)
479     return sampleprof_error::malformed;
480
481   if (std::error_code EC = skipNextWord())
482     return EC;
483
484   return sampleprof_error::success;
485 }
486
487 std::error_code SampleProfileReaderGCC::readNameTable() {
488   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
489     return EC;
490
491   uint32_t Size;
492   if (!GcovBuffer.readInt(Size))
493     return sampleprof_error::truncated;
494
495   for (uint32_t I = 0; I < Size; ++I) {
496     StringRef Str;
497     if (!GcovBuffer.readString(Str))
498       return sampleprof_error::truncated;
499     Names.push_back(Str);
500   }
501
502   return sampleprof_error::success;
503 }
504
505 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
506   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
507     return EC;
508
509   uint32_t NumFunctions;
510   if (!GcovBuffer.readInt(NumFunctions))
511     return sampleprof_error::truncated;
512
513   InlineCallStack Stack;
514   for (uint32_t I = 0; I < NumFunctions; ++I)
515     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
516       return EC;
517
518   return sampleprof_error::success;
519 }
520
521 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
522     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
523   uint64_t HeadCount = 0;
524   if (InlineStack.size() == 0)
525     if (!GcovBuffer.readInt64(HeadCount))
526       return sampleprof_error::truncated;
527
528   uint32_t NameIdx;
529   if (!GcovBuffer.readInt(NameIdx))
530     return sampleprof_error::truncated;
531
532   StringRef Name(Names[NameIdx]);
533
534   uint32_t NumPosCounts;
535   if (!GcovBuffer.readInt(NumPosCounts))
536     return sampleprof_error::truncated;
537
538   uint32_t NumCallsites;
539   if (!GcovBuffer.readInt(NumCallsites))
540     return sampleprof_error::truncated;
541
542   FunctionSamples *FProfile = nullptr;
543   if (InlineStack.size() == 0) {
544     // If this is a top function that we have already processed, do not
545     // update its profile again.  This happens in the presence of
546     // function aliases.  Since these aliases share the same function
547     // body, there will be identical replicated profiles for the
548     // original function.  In this case, we simply not bother updating
549     // the profile of the original function.
550     FProfile = &Profiles[Name];
551     FProfile->addHeadSamples(HeadCount);
552     if (FProfile->getTotalSamples() > 0)
553       Update = false;
554   } else {
555     // Otherwise, we are reading an inlined instance. The top of the
556     // inline stack contains the profile of the caller. Insert this
557     // callee in the caller's CallsiteMap.
558     FunctionSamples *CallerProfile = InlineStack.front();
559     uint32_t LineOffset = Offset >> 16;
560     uint32_t Discriminator = Offset & 0xffff;
561     FProfile = &CallerProfile->functionSamplesAt(
562         CallsiteLocation(LineOffset, Discriminator, Name));
563   }
564
565   for (uint32_t I = 0; I < NumPosCounts; ++I) {
566     uint32_t Offset;
567     if (!GcovBuffer.readInt(Offset))
568       return sampleprof_error::truncated;
569
570     uint32_t NumTargets;
571     if (!GcovBuffer.readInt(NumTargets))
572       return sampleprof_error::truncated;
573
574     uint64_t Count;
575     if (!GcovBuffer.readInt64(Count))
576       return sampleprof_error::truncated;
577
578     // The line location is encoded in the offset as:
579     //   high 16 bits: line offset to the start of the function.
580     //   low 16 bits: discriminator.
581     uint32_t LineOffset = Offset >> 16;
582     uint32_t Discriminator = Offset & 0xffff;
583
584     InlineCallStack NewStack;
585     NewStack.push_back(FProfile);
586     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
587     if (Update) {
588       // Walk up the inline stack, adding the samples on this line to
589       // the total sample count of the callers in the chain.
590       for (auto CallerProfile : NewStack)
591         CallerProfile->addTotalSamples(Count);
592
593       // Update the body samples for the current profile.
594       FProfile->addBodySamples(LineOffset, Discriminator, Count);
595     }
596
597     // Process the list of functions called at an indirect call site.
598     // These are all the targets that a function pointer (or virtual
599     // function) resolved at runtime.
600     for (uint32_t J = 0; J < NumTargets; J++) {
601       uint32_t HistVal;
602       if (!GcovBuffer.readInt(HistVal))
603         return sampleprof_error::truncated;
604
605       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
606         return sampleprof_error::malformed;
607
608       uint64_t TargetIdx;
609       if (!GcovBuffer.readInt64(TargetIdx))
610         return sampleprof_error::truncated;
611       StringRef TargetName(Names[TargetIdx]);
612
613       uint64_t TargetCount;
614       if (!GcovBuffer.readInt64(TargetCount))
615         return sampleprof_error::truncated;
616
617       if (Update) {
618         FunctionSamples &TargetProfile = Profiles[TargetName];
619         TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
620                                              TargetName, TargetCount);
621       }
622     }
623   }
624
625   // Process all the inlined callers into the current function. These
626   // are all the callsites that were inlined into this function.
627   for (uint32_t I = 0; I < NumCallsites; I++) {
628     // The offset is encoded as:
629     //   high 16 bits: line offset to the start of the function.
630     //   low 16 bits: discriminator.
631     uint32_t Offset;
632     if (!GcovBuffer.readInt(Offset))
633       return sampleprof_error::truncated;
634     InlineCallStack NewStack;
635     NewStack.push_back(FProfile);
636     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
637     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
638       return EC;
639   }
640
641   return sampleprof_error::success;
642 }
643
644 /// \brief Read a GCC AutoFDO profile.
645 ///
646 /// This format is generated by the Linux Perf conversion tool at
647 /// https://github.com/google/autofdo.
648 std::error_code SampleProfileReaderGCC::read() {
649   // Read the string table.
650   if (std::error_code EC = readNameTable())
651     return EC;
652
653   // Read the source profile.
654   if (std::error_code EC = readFunctionProfiles())
655     return EC;
656
657   return sampleprof_error::success;
658 }
659
660 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
661   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
662   return Magic == "adcg*704";
663 }
664
665 /// \brief Prepare a memory buffer for the contents of \p Filename.
666 ///
667 /// \returns an error code indicating the status of the buffer.
668 static ErrorOr<std::unique_ptr<MemoryBuffer>>
669 setupMemoryBuffer(std::string Filename) {
670   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
671   if (std::error_code EC = BufferOrErr.getError())
672     return EC;
673   auto Buffer = std::move(BufferOrErr.get());
674
675   // Sanity check the file.
676   if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
677     return sampleprof_error::too_large;
678
679   return std::move(Buffer);
680 }
681
682 /// \brief Create a sample profile reader based on the format of the input file.
683 ///
684 /// \param Filename The file to open.
685 ///
686 /// \param Reader The reader to instantiate according to \p Filename's format.
687 ///
688 /// \param C The LLVM context to use to emit diagnostics.
689 ///
690 /// \returns an error code indicating the status of the created reader.
691 ErrorOr<std::unique_ptr<SampleProfileReader>>
692 SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
693   auto BufferOrError = setupMemoryBuffer(Filename);
694   if (std::error_code EC = BufferOrError.getError())
695     return EC;
696
697   auto Buffer = std::move(BufferOrError.get());
698   std::unique_ptr<SampleProfileReader> Reader;
699   if (SampleProfileReaderBinary::hasFormat(*Buffer))
700     Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
701   else if (SampleProfileReaderGCC::hasFormat(*Buffer))
702     Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
703   else if (SampleProfileReaderText::hasFormat(*Buffer))
704     Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
705   else
706     return sampleprof_error::unrecognized_format;
707
708   if (std::error_code EC = Reader->readHeader())
709     return EC;
710
711   return std::move(Reader);
712 }