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