1 //===- SampleProfReader.h - Read LLVM sample profile data -------*- C++ -*-===//
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 contains definitions needed for reading sample profiles.
10 //
11 // NOTE: If you are making changes to this file format, please remember
12 //       to document them in the Clang documentation at
13 //       tools/clang/docs/UsersManual.rst.
14 //
15 // Text format
16 // -----------
17 //
18 // Sample profiles are written as ASCII text. The file is divided into
19 // sections, which correspond to each of the functions executed at runtime.
20 // Each section has the following format
21 //
22 //     function1:total_samples:total_head_samples
23 //      offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
24 //      offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
25 //      ...
26 //      offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
27 //      offsetA[.discriminator]: fnA:num_of_total_samples
28 //       offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
29 //       ...
30 //      !CFGChecksum: num
31 //      !Attribute: flags
32 //
33 // This is a nested tree in which the indentation represents the nesting level
34 // of the inline stack. There are no blank lines in the file. And the spacing
35 // within a single line is fixed. Additional spaces will result in an error
36 // while reading the file.
37 //
38 // Any line starting with the '#' character is completely ignored.
39 //
40 // Inlined calls are represented with indentation. The Inline stack is a
41 // stack of source locations in which the top of the stack represents the
42 // leaf function, and the bottom of the stack represents the actual
43 // symbol to which the instruction belongs.
44 //
45 // Function names must be mangled in order for the profile loader to
46 // match them in the current translation unit. The two numbers in the
47 // function header specify how many total samples were accumulated in the
48 // function (first number), and the total number of samples accumulated
49 // in the prologue of the function (second number). This head sample
50 // count provides an indicator of how frequently the function is invoked.
51 //
52 // There are three types of lines in the function body.
53 //
54 // * Sampled line represents the profile information of a source location.
55 // * Callsite line represents the profile information of a callsite.
56 // * Metadata line represents extra metadata of the function.
57 //
58 // Each sampled line may contain several items. Some are optional (marked
59 // below):
60 //
61 // a. Source line offset. This number represents the line number
62 //    in the function where the sample was collected. The line number is
63 //    always relative to the line where symbol of the function is
64 //    defined. So, if the function has its header at line 280, the offset
65 //    13 is at line 293 in the file.
66 //
67 //    Note that this offset should never be a negative number. This could
68 //    happen in cases like macros. The debug machinery will register the
69 //    line number at the point of macro expansion. So, if the macro was
70 //    expanded in a line before the start of the function, the profile
71 //    converter should emit a 0 as the offset (this means that the optimizers
72 //    will not be able to associate a meaningful weight to the instructions
73 //    in the macro).
74 //
75 // b. [OPTIONAL] Discriminator. This is used if the sampled program
76 //    was compiled with DWARF discriminator support
77 //    (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
78 //    DWARF discriminators are unsigned integer values that allow the
79 //    compiler to distinguish between multiple execution paths on the
80 //    same source line location.
81 //
82 //    For example, consider the line of code ``if (cond) foo(); else bar();``.
83 //    If the predicate ``cond`` is true 80% of the time, then the edge
84 //    into function ``foo`` should be considered to be taken most of the
85 //    time. But both calls to ``foo`` and ``bar`` are at the same source
86 //    line, so a sample count at that line is not sufficient. The
87 //    compiler needs to know which part of that line is taken more
88 //    frequently.
89 //
90 //    This is what discriminators provide. In this case, the calls to
91 //    ``foo`` and ``bar`` will be at the same line, but will have
92 //    different discriminator values. This allows the compiler to correctly
93 //    set edge weights into ``foo`` and ``bar``.
94 //
95 // c. Number of samples. This is an integer quantity representing the
96 //    number of samples collected by the profiler at this source
97 //    location.
98 //
99 // d. [OPTIONAL] Potential call targets and samples. If present, this
100 //    line contains a call instruction. This models both direct and
101 //    number of samples. For example,
102 //
103 //      130: 7  foo:3  bar:2  baz:7
104 //
105 //    The above means that at relative line offset 130 there is a call
106 //    instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
107 //    with ``baz()`` being the relatively more frequently called target.
108 //
109 // Each callsite line may contain several items. Some are optional.
110 //
111 // a. Source line offset. This number represents the line number of the
112 //    callsite that is inlined in the profiled binary.
113 //
114 // b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
115 //
116 // c. Number of samples. This is an integer quantity representing the
117 //    total number of samples collected for the inlined instance at this
118 //    callsite
119 //
120 // Metadata line can occur in lines with one indent only, containing extra
121 // information for the top-level function. Furthermore, metadata can only
122 // occur after all the body samples and callsite samples.
123 // Each metadata line may contain a particular type of metadata, marked by
124 // the starting characters annotated with !. We process each metadata line
125 // independently, hence each metadata line has to form an independent piece
126 // of information that does not require cross-line reference.
127 // We support the following types of metadata:
128 //
129 // a. CFG Checksum (a.k.a. function hash):
130 //   !CFGChecksum: 12345
131 // b. CFG Checksum (see ContextAttributeMask):
132 //   !Atribute: 1
133 //
134 //
135 // Binary format
136 // -------------
137 //
138 // This is a more compact encoding. Numbers are encoded as ULEB128 values
139 // and all strings are encoded in a name table. The file is organized in
140 // the following sections:
141 //
142 // MAGIC (uint64_t)
143 //    File identifier computed by function SPMagic() (0x5350524f463432ff)
144 //
145 // VERSION (uint32_t)
146 //    File format version number computed by SPVersion()
147 //
148 // SUMMARY
149 //    TOTAL_COUNT (uint64_t)
150 //        Total number of samples in the profile.
151 //    MAX_COUNT (uint64_t)
152 //        Maximum value of samples on a line.
153 //    MAX_FUNCTION_COUNT (uint64_t)
154 //        Maximum number of samples at function entry (head samples).
155 //    NUM_COUNTS (uint64_t)
156 //        Number of lines with samples.
157 //    NUM_FUNCTIONS (uint64_t)
158 //        Number of functions with samples.
159 //    NUM_DETAILED_SUMMARY_ENTRIES (size_t)
160 //        Number of entries in detailed summary
161 //    DETAILED_SUMMARY
162 //        A list of detailed summary entry. Each entry consists of
163 //        CUTOFF (uint32_t)
164 //            Required percentile of total sample count expressed as a fraction
165 //            multiplied by 1000000.
166 //        MIN_COUNT (uint64_t)
167 //            The minimum number of samples required to reach the target
168 //            CUTOFF.
169 //        NUM_COUNTS (uint64_t)
170 //            Number of samples to get to the desrired percentile.
171 //
172 // NAME TABLE
173 //    SIZE (uint32_t)
174 //        Number of entries in the name table.
175 //    NAMES
176 //        A NUL-separated list of SIZE strings.
177 //
178 // FUNCTION BODY (one for each uninlined function body present in the profile)
179 //    HEAD_SAMPLES (uint64_t) [only for top-level functions]
180 //        Total number of samples collected at the head (prologue) of the
181 //        function.
182 //        NOTE: This field should only be present for top-level functions
183 //              (i.e., not inlined into any caller). Inlined function calls
184 //              have no prologue, so they don't need this.
185 //    NAME_IDX (uint32_t)
186 //        Index into the name table indicating the function name.
187 //    SAMPLES (uint64_t)
188 //        Total number of samples collected in this function.
189 //    NRECS (uint32_t)
190 //        Total number of sampling records this function's profile.
191 //    BODY RECORDS
192 //        A list of NRECS entries. Each entry contains:
193 //          OFFSET (uint32_t)
194 //            Line offset from the start of the function.
195 //          DISCRIMINATOR (uint32_t)
196 //            Discriminator value (see description of discriminators
197 //            in the text format documentation above).
198 //          SAMPLES (uint64_t)
199 //            Number of samples collected at this location.
200 //          NUM_CALLS (uint32_t)
201 //            Number of non-inlined function calls made at this location. In the
202 //            case of direct calls, this number will always be 1. For indirect
203 //            calls (virtual functions and function pointers) this will
204 //            represent all the actual functions called at runtime.
205 //          CALL_TARGETS
206 //            A list of NUM_CALLS entries for each called function:
207 //               NAME_IDX (uint32_t)
208 //                  Index into the name table with the callee name.
209 //               SAMPLES (uint64_t)
210 //                  Number of samples collected at the call site.
211 //    NUM_INLINED_FUNCTIONS (uint32_t)
212 //      Number of callees inlined into this function.
213 //    INLINED FUNCTION RECORDS
214 //      A list of NUM_INLINED_FUNCTIONS entries describing each of the inlined
215 //      callees.
216 //        OFFSET (uint32_t)
217 //          Line offset from the start of the function.
218 //        DISCRIMINATOR (uint32_t)
219 //          Discriminator value (see description of discriminators
220 //          in the text format documentation above).
221 //        FUNCTION BODY
222 //          A FUNCTION BODY entry describing the inlined function.
223 //===----------------------------------------------------------------------===//
224 
225 #ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
226 #define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
227 
228 #include "llvm/ADT/Optional.h"
229 #include "llvm/ADT/SmallVector.h"
230 #include "llvm/ADT/StringMap.h"
231 #include "llvm/ADT/StringRef.h"
232 #include "llvm/IR/DiagnosticInfo.h"
233 #include "llvm/IR/Function.h"
234 #include "llvm/IR/LLVMContext.h"
235 #include "llvm/IR/ProfileSummary.h"
236 #include "llvm/ProfileData/GCOV.h"
237 #include "llvm/ProfileData/SampleProf.h"
238 #include "llvm/Support/Debug.h"
239 #include "llvm/Support/Discriminator.h"
240 #include "llvm/Support/ErrorOr.h"
241 #include "llvm/Support/MemoryBuffer.h"
242 #include "llvm/Support/SymbolRemappingReader.h"
243 #include <algorithm>
244 #include <cstdint>
245 #include <memory>
246 #include <string>
247 #include <system_error>
248 #include <vector>
249 
250 namespace llvm {
251 
252 class raw_ostream;
253 class Twine;
254 
255 namespace sampleprof {
256 
257 class SampleProfileReader;
258 
259 /// SampleProfileReaderItaniumRemapper remaps the profile data from a
260 /// sample profile data reader, by applying a provided set of equivalences
261 /// between components of the symbol names in the profile.
262 class SampleProfileReaderItaniumRemapper {
263 public:
264   SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
265                                      std::unique_ptr<SymbolRemappingReader> SRR,
266                                      SampleProfileReader &R)
267       : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
268     assert(Remappings && "Remappings cannot be nullptr");
269   }
270 
271   /// Create a remapper from the given remapping file. The remapper will
272   /// be used for profile read in by Reader.
273   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
274   create(const std::string Filename, SampleProfileReader &Reader,
275          LLVMContext &C);
276 
277   /// Create a remapper from the given Buffer. The remapper will
278   /// be used for profile read in by Reader.
279   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
280   create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
281          LLVMContext &C);
282 
283   /// Apply remappings to the profile read by Reader.
284   void applyRemapping(LLVMContext &Ctx);
285 
286   bool hasApplied() { return RemappingApplied; }
287 
288   /// Insert function name into remapper.
289   void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
290 
291   /// Query whether there is equivalent in the remapper which has been
292   /// inserted.
293   bool exist(StringRef FunctionName) {
294     return Remappings->lookup(FunctionName);
295   }
296 
297   /// Return the equivalent name in the profile for \p FunctionName if
298   /// it exists.
299   Optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
300 
301 private:
302   // The buffer holding the content read from remapping file.
303   std::unique_ptr<MemoryBuffer> Buffer;
304   std::unique_ptr<SymbolRemappingReader> Remappings;
305   // Map remapping key to the name in the profile. By looking up the
306   // key in the remapper, a given new name can be mapped to the
307   // cannonical name using the NameMap.
308   DenseMap<SymbolRemappingReader::Key, StringRef> NameMap;
309   // The Reader the remapper is servicing.
310   SampleProfileReader &Reader;
311   // Indicate whether remapping has been applied to the profile read
312   // by Reader -- by calling applyRemapping.
313   bool RemappingApplied = false;
314 };
315 
316 /// Sample-based profile reader.
317 ///
318 /// Each profile contains sample counts for all the functions
319 /// executed. Inside each function, statements are annotated with the
320 /// collected samples on all the instructions associated with that
321 /// statement.
322 ///
323 /// For this to produce meaningful data, the program needs to be
324 /// compiled with some debug information (at minimum, line numbers:
325 /// -gline-tables-only). Otherwise, it will be impossible to match IR
326 /// instructions to the line numbers collected by the profiler.
327 ///
328 /// From the profile file, we are interested in collecting the
329 /// following information:
330 ///
331 /// * A list of functions included in the profile (mangled names).
332 ///
333 /// * For each function F:
334 ///   1. The total number of samples collected in F.
335 ///
336 ///   2. The samples collected at each line in F. To provide some
337 ///      protection against source code shuffling, line numbers should
338 ///      be relative to the start of the function.
339 ///
340 /// The reader supports two file formats: text and binary. The text format
341 /// is useful for debugging and testing, while the binary format is more
342 /// compact and I/O efficient. They can both be used interchangeably.
343 class SampleProfileReader {
344 public:
345   SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
346                       SampleProfileFormat Format = SPF_None)
347       : Profiles(0), Ctx(C), Buffer(std::move(B)), Format(Format) {}
348 
349   virtual ~SampleProfileReader() = default;
350 
351   /// Read and validate the file header.
352   virtual std::error_code readHeader() = 0;
353 
354   /// Set the bits for FS discriminators. Parameter Pass specify the sequence
355   /// number, Pass == i is for the i-th round of adding FS discriminators.
356   /// Pass == 0 is for using base discriminators.
357   void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P) {
358     MaskedBitFrom = getFSPassBitEnd(P);
359   }
360 
361   /// Get the bitmask the discriminators: For FS profiles, return the bit
362   /// mask for this pass. For non FS profiles, return (unsigned) -1.
363   uint32_t getDiscriminatorMask() const {
364     if (!ProfileIsFS)
365       return 0xFFFFFFFF;
366     assert((MaskedBitFrom != 0) && "MaskedBitFrom is not set properly");
367     return getN1Bits(MaskedBitFrom);
368   }
369 
370   /// The interface to read sample profiles from the associated file.
371   std::error_code read() {
372     if (std::error_code EC = readImpl())
373       return EC;
374     if (Remapper)
375       Remapper->applyRemapping(Ctx);
376     FunctionSamples::UseMD5 = useMD5();
377     return sampleprof_error::success;
378   }
379 
380   /// The implementaion to read sample profiles from the associated file.
381   virtual std::error_code readImpl() = 0;
382 
383   /// Print the profile for \p FName on stream \p OS.
384   void dumpFunctionProfile(StringRef FName, raw_ostream &OS = dbgs());
385 
386   /// Collect functions with definitions in Module M. For reader which
387   /// support loading function profiles on demand, return true when the
388   /// reader has been given a module. Always return false for reader
389   /// which doesn't support loading function profiles on demand.
390   virtual bool collectFuncsFromModule() { return false; }
391 
392   /// Print all the profiles on stream \p OS.
393   void dump(raw_ostream &OS = dbgs());
394 
395   /// Return the samples collected for function \p F.
396   FunctionSamples *getSamplesFor(const Function &F) {
397     // The function name may have been updated by adding suffix. Call
398     // a helper to (optionally) strip off suffixes so that we can
399     // match against the original function name in the profile.
400     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
401     return getSamplesFor(CanonName);
402   }
403 
404   /// Return the samples collected for function \p F, create empty
405   /// FunctionSamples if it doesn't exist.
406   FunctionSamples *getOrCreateSamplesFor(const Function &F) {
407     std::string FGUID;
408     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
409     CanonName = getRepInFormat(CanonName, useMD5(), FGUID);
410     return &Profiles[CanonName];
411   }
412 
413   /// Return the samples collected for function \p F.
414   virtual FunctionSamples *getSamplesFor(StringRef Fname) {
415     std::string FGUID;
416     Fname = getRepInFormat(Fname, useMD5(), FGUID);
417     auto It = Profiles.find(Fname);
418     if (It != Profiles.end())
419       return &It->second;
420 
421     if (Remapper) {
422       if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
423         auto It = Profiles.find(*NameInProfile);
424         if (It != Profiles.end())
425           return &It->second;
426       }
427     }
428     return nullptr;
429   }
430 
431   /// Return all the profiles.
432   StringMap<FunctionSamples> &getProfiles() { return Profiles; }
433 
434   /// Report a parse error message.
435   void reportError(int64_t LineNumber, const Twine &Msg) const {
436     Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
437                                              LineNumber, Msg));
438   }
439 
440   /// Create a sample profile reader appropriate to the file format.
441   /// Create a remapper underlying if RemapFilename is not empty.
442   /// Parameter P specifies the FSDiscriminatorPass.
443   static ErrorOr<std::unique_ptr<SampleProfileReader>>
444   create(const std::string Filename, LLVMContext &C,
445          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
446          const std::string RemapFilename = "");
447 
448   /// Create a sample profile reader from the supplied memory buffer.
449   /// Create a remapper underlying if RemapFilename is not empty.
450   /// Parameter P specifies the FSDiscriminatorPass.
451   static ErrorOr<std::unique_ptr<SampleProfileReader>>
452   create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
453          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
454          const std::string RemapFilename = "");
455 
456   /// Return the profile summary.
457   ProfileSummary &getSummary() const { return *(Summary.get()); }
458 
459   MemoryBuffer *getBuffer() const { return Buffer.get(); }
460 
461   /// \brief Return the profile format.
462   SampleProfileFormat getFormat() const { return Format; }
463 
464   /// Whether input profile is based on pseudo probes.
465   bool profileIsProbeBased() const { return ProfileIsProbeBased; }
466 
467   /// Whether input profile is fully context-sensitive
468   bool profileIsCS() const { return ProfileIsCS; }
469 
470   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
471     return nullptr;
472   };
473 
474   /// It includes all the names that have samples either in outline instance
475   /// or inline instance.
476   virtual std::vector<StringRef> *getNameTable() { return nullptr; }
477   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
478 
479   /// Return whether names in the profile are all MD5 numbers.
480   virtual bool useMD5() { return false; }
481 
482   /// Don't read profile without context if the flag is set. This is only meaningful
483   /// for ExtBinary format.
484   virtual void setSkipFlatProf(bool Skip) {}
485   /// Return whether any name in the profile contains ".__uniq." suffix.
486   virtual bool hasUniqSuffix() { return false; }
487 
488   SampleProfileReaderItaniumRemapper *getRemapper() { return Remapper.get(); }
489 
490   void setModule(const Module *Mod) { M = Mod; }
491 
492 protected:
493   /// Map every function to its associated profile.
494   ///
495   /// The profile of every function executed at runtime is collected
496   /// in the structure FunctionSamples. This maps function objects
497   /// to their corresponding profiles.
498   StringMap<FunctionSamples> Profiles;
499 
500   /// LLVM context used to emit diagnostics.
501   LLVMContext &Ctx;
502 
503   /// Memory buffer holding the profile file.
504   std::unique_ptr<MemoryBuffer> Buffer;
505 
506   /// Profile summary information.
507   std::unique_ptr<ProfileSummary> Summary;
508 
509   /// Take ownership of the summary of this reader.
510   static std::unique_ptr<ProfileSummary>
511   takeSummary(SampleProfileReader &Reader) {
512     return std::move(Reader.Summary);
513   }
514 
515   /// Compute summary for this profile.
516   void computeSummary();
517 
518   std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
519 
520   /// \brief Whether samples are collected based on pseudo probes.
521   bool ProfileIsProbeBased = false;
522 
523   /// Whether function profiles are context-sensitive.
524   bool ProfileIsCS = false;
525 
526   /// Number of context-sensitive profiles.
527   uint32_t CSProfileCount = 0;
528 
529   /// Whether the function profiles use FS discriminators.
530   bool ProfileIsFS = false;
531 
532   /// \brief The format of sample.
533   SampleProfileFormat Format = SPF_None;
534 
535   /// \brief The current module being compiled if SampleProfileReader
536   /// is used by compiler. If SampleProfileReader is used by other
537   /// tools which are not compiler, M is usually nullptr.
538   const Module *M = nullptr;
539 
540   /// Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
541   /// The default is to keep all the bits.
542   uint32_t MaskedBitFrom = 31;
543 };
544 
545 class SampleProfileReaderText : public SampleProfileReader {
546 public:
547   SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
548       : SampleProfileReader(std::move(B), C, SPF_Text) {}
549 
550   /// Read and validate the file header.
551   std::error_code readHeader() override { return sampleprof_error::success; }
552 
553   /// Read sample profiles from the associated file.
554   std::error_code readImpl() override;
555 
556   /// Return true if \p Buffer is in the format supported by this class.
557   static bool hasFormat(const MemoryBuffer &Buffer);
558 };
559 
560 class SampleProfileReaderBinary : public SampleProfileReader {
561 public:
562   SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
563                             SampleProfileFormat Format = SPF_None)
564       : SampleProfileReader(std::move(B), C, Format) {}
565 
566   /// Read and validate the file header.
567   virtual std::error_code readHeader() override;
568 
569   /// Read sample profiles from the associated file.
570   std::error_code readImpl() override;
571 
572   /// It includes all the names that have samples either in outline instance
573   /// or inline instance.
574   virtual std::vector<StringRef> *getNameTable() override { return &NameTable; }
575 
576 protected:
577   /// Read a numeric value of type T from the profile.
578   ///
579   /// If an error occurs during decoding, a diagnostic message is emitted and
580   /// EC is set.
581   ///
582   /// \returns the read value.
583   template <typename T> ErrorOr<T> readNumber();
584 
585   /// Read a numeric value of type T from the profile. The value is saved
586   /// without encoded.
587   template <typename T> ErrorOr<T> readUnencodedNumber();
588 
589   /// Read a string from the profile.
590   ///
591   /// If an error occurs during decoding, a diagnostic message is emitted and
592   /// EC is set.
593   ///
594   /// \returns the read value.
595   ErrorOr<StringRef> readString();
596 
597   /// Read the string index and check whether it overflows the table.
598   template <typename T> inline ErrorOr<uint32_t> readStringIndex(T &Table);
599 
600   /// Return true if we've reached the end of file.
601   bool at_eof() const { return Data >= End; }
602 
603   /// Read the next function profile instance.
604   std::error_code readFuncProfile(const uint8_t *Start);
605 
606   /// Read the contents of the given profile instance.
607   std::error_code readProfile(FunctionSamples &FProfile);
608 
609   /// Read the contents of Magic number and Version number.
610   std::error_code readMagicIdent();
611 
612   /// Read profile summary.
613   std::error_code readSummary();
614 
615   /// Read the whole name table.
616   virtual std::error_code readNameTable();
617 
618   /// Points to the current location in the buffer.
619   const uint8_t *Data = nullptr;
620 
621   /// Points to the end of the buffer.
622   const uint8_t *End = nullptr;
623 
624   /// Function name table.
625   std::vector<StringRef> NameTable;
626 
627   /// Read a string indirectly via the name table.
628   virtual ErrorOr<StringRef> readStringFromTable();
629 
630 private:
631   std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
632   virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
633 };
634 
635 class SampleProfileReaderRawBinary : public SampleProfileReaderBinary {
636 private:
637   virtual std::error_code verifySPMagic(uint64_t Magic) override;
638 
639 public:
640   SampleProfileReaderRawBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
641                                SampleProfileFormat Format = SPF_Binary)
642       : SampleProfileReaderBinary(std::move(B), C, Format) {}
643 
644   /// \brief Return true if \p Buffer is in the format supported by this class.
645   static bool hasFormat(const MemoryBuffer &Buffer);
646 };
647 
648 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
649 /// the basic structure of the extensible binary format.
650 /// The format is organized in sections except the magic and version number
651 /// at the beginning. There is a section table before all the sections, and
652 /// each entry in the table describes the entry type, start, size and
653 /// attributes. The format in each section is defined by the section itself.
654 ///
655 /// It is easy to add a new section while maintaining the backward
656 /// compatibility of the profile. Nothing extra needs to be done. If we want
657 /// to extend an existing section, like add cache misses information in
658 /// addition to the sample count in the profile body, we can add a new section
659 /// with the extension and retire the existing section, and we could choose
660 /// to keep the parser of the old section if we want the reader to be able
661 /// to read both new and old format profile.
662 ///
663 /// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
664 /// commonly used sections of a profile in extensible binary format. It is
665 /// possible to define other types of profile inherited from
666 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
667 class SampleProfileReaderExtBinaryBase : public SampleProfileReaderBinary {
668 private:
669   std::error_code decompressSection(const uint8_t *SecStart,
670                                     const uint64_t SecSize,
671                                     const uint8_t *&DecompressBuf,
672                                     uint64_t &DecompressBufSize);
673 
674   BumpPtrAllocator Allocator;
675 
676 protected:
677   std::vector<SecHdrTableEntry> SecHdrTable;
678   std::error_code readSecHdrTableEntry(uint32_t Idx);
679   std::error_code readSecHdrTable();
680 
681   std::error_code readFuncMetadata(bool ProfileHasAttribute);
682   std::error_code readFuncOffsetTable();
683   std::error_code readFuncProfiles();
684   std::error_code readMD5NameTable();
685   std::error_code readNameTableSec(bool IsMD5);
686   std::error_code readProfileSymbolList();
687 
688   virtual std::error_code readHeader() override;
689   virtual std::error_code verifySPMagic(uint64_t Magic) override = 0;
690   virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
691                                          const SecHdrTableEntry &Entry);
692   // placeholder for subclasses to dispatch their own section readers.
693   virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
694   virtual ErrorOr<StringRef> readStringFromTable() override;
695 
696   std::unique_ptr<ProfileSymbolList> ProfSymList;
697 
698   /// The table mapping from function name to the offset of its FunctionSample
699   /// towards file start.
700   DenseMap<StringRef, uint64_t> FuncOffsetTable;
701   /// The set containing the functions to use when compiling a module.
702   DenseSet<StringRef> FuncsToUse;
703 
704   /// Use fixed length MD5 instead of ULEB128 encoding so NameTable doesn't
705   /// need to be read in up front and can be directly accessed using index.
706   bool FixedLengthMD5 = false;
707   /// The starting address of NameTable containing fixed length MD5.
708   const uint8_t *MD5NameMemStart = nullptr;
709 
710   /// If MD5 is used in NameTable section, the section saves uint64_t data.
711   /// The uint64_t data has to be converted to a string and then the string
712   /// will be used to initialize StringRef in NameTable.
713   /// Note NameTable contains StringRef so it needs another buffer to own
714   /// the string data. MD5StringBuf serves as the string buffer that is
715   /// referenced by NameTable (vector of StringRef). We make sure
716   /// the lifetime of MD5StringBuf is not shorter than that of NameTable.
717   std::unique_ptr<std::vector<std::string>> MD5StringBuf;
718 
719   /// If SkipFlatProf is true, skip the sections with
720   /// SecFlagFlat flag.
721   bool SkipFlatProf = false;
722 
723 public:
724   SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,
725                                    LLVMContext &C, SampleProfileFormat Format)
726       : SampleProfileReaderBinary(std::move(B), C, Format) {}
727 
728   /// Read sample profiles in extensible format from the associated file.
729   std::error_code readImpl() override;
730 
731   /// Get the total size of all \p Type sections.
732   uint64_t getSectionSize(SecType Type);
733   /// Get the total size of header and all sections.
734   uint64_t getFileSize();
735   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
736 
737   /// Collect functions with definitions in Module M. Return true if
738   /// the reader has been given a module.
739   bool collectFuncsFromModule() override;
740 
741   /// Return whether names in the profile are all MD5 numbers.
742   virtual bool useMD5() override { return MD5StringBuf.get(); }
743 
744   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
745     return std::move(ProfSymList);
746   };
747 
748   virtual void setSkipFlatProf(bool Skip) override { SkipFlatProf = Skip; }
749 };
750 
751 class SampleProfileReaderExtBinary : public SampleProfileReaderExtBinaryBase {
752 private:
753   virtual std::error_code verifySPMagic(uint64_t Magic) override;
754   virtual std::error_code
755   readCustomSection(const SecHdrTableEntry &Entry) override {
756     return sampleprof_error::success;
757   };
758 
759 public:
760   SampleProfileReaderExtBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
761                                SampleProfileFormat Format = SPF_Ext_Binary)
762       : SampleProfileReaderExtBinaryBase(std::move(B), C, Format) {}
763 
764   /// \brief Return true if \p Buffer is in the format supported by this class.
765   static bool hasFormat(const MemoryBuffer &Buffer);
766 };
767 
768 class SampleProfileReaderCompactBinary : public SampleProfileReaderBinary {
769 private:
770   /// Function name table.
771   std::vector<std::string> NameTable;
772   /// The table mapping from function name to the offset of its FunctionSample
773   /// towards file start.
774   DenseMap<StringRef, uint64_t> FuncOffsetTable;
775   /// The set containing the functions to use when compiling a module.
776   DenseSet<StringRef> FuncsToUse;
777   virtual std::error_code verifySPMagic(uint64_t Magic) override;
778   virtual std::error_code readNameTable() override;
779   /// Read a string indirectly via the name table.
780   virtual ErrorOr<StringRef> readStringFromTable() override;
781   virtual std::error_code readHeader() override;
782   std::error_code readFuncOffsetTable();
783 
784 public:
785   SampleProfileReaderCompactBinary(std::unique_ptr<MemoryBuffer> B,
786                                    LLVMContext &C)
787       : SampleProfileReaderBinary(std::move(B), C, SPF_Compact_Binary) {}
788 
789   /// \brief Return true if \p Buffer is in the format supported by this class.
790   static bool hasFormat(const MemoryBuffer &Buffer);
791 
792   /// Read samples only for functions to use.
793   std::error_code readImpl() override;
794 
795   /// Collect functions with definitions in Module M. Return true if
796   /// the reader has been given a module.
797   bool collectFuncsFromModule() override;
798 
799   /// Return whether names in the profile are all MD5 numbers.
800   virtual bool useMD5() override { return true; }
801 };
802 
803 using InlineCallStack = SmallVector<FunctionSamples *, 10>;
804 
805 // Supported histogram types in GCC.  Currently, we only need support for
806 // call target histograms.
807 enum HistType {
808   HIST_TYPE_INTERVAL,
809   HIST_TYPE_POW2,
810   HIST_TYPE_SINGLE_VALUE,
811   HIST_TYPE_CONST_DELTA,
812   HIST_TYPE_INDIR_CALL,
813   HIST_TYPE_AVERAGE,
814   HIST_TYPE_IOR,
815   HIST_TYPE_INDIR_CALL_TOPN
816 };
817 
818 class SampleProfileReaderGCC : public SampleProfileReader {
819 public:
820   SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
821       : SampleProfileReader(std::move(B), C, SPF_GCC),
822         GcovBuffer(Buffer.get()) {}
823 
824   /// Read and validate the file header.
825   std::error_code readHeader() override;
826 
827   /// Read sample profiles from the associated file.
828   std::error_code readImpl() override;
829 
830   /// Return true if \p Buffer is in the format supported by this class.
831   static bool hasFormat(const MemoryBuffer &Buffer);
832 
833 protected:
834   std::error_code readNameTable();
835   std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
836                                          bool Update, uint32_t Offset);
837   std::error_code readFunctionProfiles();
838   std::error_code skipNextWord();
839   template <typename T> ErrorOr<T> readNumber();
840   ErrorOr<StringRef> readString();
841 
842   /// Read the section tag and check that it's the same as \p Expected.
843   std::error_code readSectionTag(uint32_t Expected);
844 
845   /// GCOV buffer containing the profile.
846   GCOVBuffer GcovBuffer;
847 
848   /// Function names in this profile.
849   std::vector<std::string> Names;
850 
851   /// GCOV tags used to separate sections in the profile file.
852   static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
853   static const uint32_t GCOVTagAFDOFunction = 0xac000000;
854 };
855 
856 } // end namespace sampleprof
857 
858 } // end namespace llvm
859 
860 #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
861