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 (uint64_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 (uint64_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 (uint64_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/SmallVector.h"
229 #include "llvm/ADT/StringRef.h"
230 #include "llvm/IR/DiagnosticInfo.h"
231 #include "llvm/IR/LLVMContext.h"
232 #include "llvm/IR/ProfileSummary.h"
233 #include "llvm/ProfileData/GCOV.h"
234 #include "llvm/ProfileData/SampleProf.h"
235 #include "llvm/ProfileData/SymbolRemappingReader.h"
236 #include "llvm/Support/Debug.h"
237 #include "llvm/Support/Discriminator.h"
238 #include "llvm/Support/ErrorOr.h"
239 #include "llvm/Support/MemoryBuffer.h"
240 #include <cstdint>
241 #include <list>
242 #include <memory>
243 #include <optional>
244 #include <string>
245 #include <system_error>
246 #include <unordered_set>
247 #include <vector>
248 
249 namespace llvm {
250 
251 class raw_ostream;
252 class Twine;
253 
254 namespace vfs {
255 class FileSystem;
256 } // namespace vfs
257 
258 namespace sampleprof {
259 
260 class SampleProfileReader;
261 
262 /// SampleProfileReaderItaniumRemapper remaps the profile data from a
263 /// sample profile data reader, by applying a provided set of equivalences
264 /// between components of the symbol names in the profile.
265 class SampleProfileReaderItaniumRemapper {
266 public:
267   SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
268                                      std::unique_ptr<SymbolRemappingReader> SRR,
269                                      SampleProfileReader &R)
270       : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
271     assert(Remappings && "Remappings cannot be nullptr");
272   }
273 
274   /// Create a remapper from the given remapping file. The remapper will
275   /// be used for profile read in by Reader.
276   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
277   create(const std::string Filename, vfs::FileSystem &FS,
278          SampleProfileReader &Reader, LLVMContext &C);
279 
280   /// Create a remapper from the given Buffer. The remapper will
281   /// be used for profile read in by Reader.
282   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
283   create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
284          LLVMContext &C);
285 
286   /// Apply remappings to the profile read by Reader.
287   void applyRemapping(LLVMContext &Ctx);
288 
289   bool hasApplied() { return RemappingApplied; }
290 
291   /// Insert function name into remapper.
292   void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
293 
294   /// Query whether there is equivalent in the remapper which has been
295   /// inserted.
296   bool exist(StringRef FunctionName) {
297     return Remappings->lookup(FunctionName);
298   }
299 
300   /// Return the equivalent name in the profile for \p FunctionName if
301   /// it exists.
302   std::optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
303 
304 private:
305   // The buffer holding the content read from remapping file.
306   std::unique_ptr<MemoryBuffer> Buffer;
307   std::unique_ptr<SymbolRemappingReader> Remappings;
308   // Map remapping key to the name in the profile. By looking up the
309   // key in the remapper, a given new name can be mapped to the
310   // cannonical name using the NameMap.
311   DenseMap<SymbolRemappingReader::Key, StringRef> NameMap;
312   // The Reader the remapper is servicing.
313   SampleProfileReader &Reader;
314   // Indicate whether remapping has been applied to the profile read
315   // by Reader -- by calling applyRemapping.
316   bool RemappingApplied = false;
317 };
318 
319 /// Sample-based profile reader.
320 ///
321 /// Each profile contains sample counts for all the functions
322 /// executed. Inside each function, statements are annotated with the
323 /// collected samples on all the instructions associated with that
324 /// statement.
325 ///
326 /// For this to produce meaningful data, the program needs to be
327 /// compiled with some debug information (at minimum, line numbers:
328 /// -gline-tables-only). Otherwise, it will be impossible to match IR
329 /// instructions to the line numbers collected by the profiler.
330 ///
331 /// From the profile file, we are interested in collecting the
332 /// following information:
333 ///
334 /// * A list of functions included in the profile (mangled names).
335 ///
336 /// * For each function F:
337 ///   1. The total number of samples collected in F.
338 ///
339 ///   2. The samples collected at each line in F. To provide some
340 ///      protection against source code shuffling, line numbers should
341 ///      be relative to the start of the function.
342 ///
343 /// The reader supports two file formats: text and binary. The text format
344 /// is useful for debugging and testing, while the binary format is more
345 /// compact and I/O efficient. They can both be used interchangeably.
346 class SampleProfileReader {
347 public:
348   SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
349                       SampleProfileFormat Format = SPF_None)
350       : Profiles(0), Ctx(C), Buffer(std::move(B)), Format(Format) {}
351 
352   virtual ~SampleProfileReader() = default;
353 
354   /// Read and validate the file header.
355   virtual std::error_code readHeader() = 0;
356 
357   /// Set the bits for FS discriminators. Parameter Pass specify the sequence
358   /// number, Pass == i is for the i-th round of adding FS discriminators.
359   /// Pass == 0 is for using base discriminators.
360   void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P) {
361     MaskedBitFrom = getFSPassBitEnd(P);
362   }
363 
364   /// Get the bitmask the discriminators: For FS profiles, return the bit
365   /// mask for this pass. For non FS profiles, return (unsigned) -1.
366   uint32_t getDiscriminatorMask() const {
367     if (!ProfileIsFS)
368       return 0xFFFFFFFF;
369     assert((MaskedBitFrom != 0) && "MaskedBitFrom is not set properly");
370     return getN1Bits(MaskedBitFrom);
371   }
372 
373   /// The interface to read sample profiles from the associated file.
374   std::error_code read() {
375     if (std::error_code EC = readImpl())
376       return EC;
377     if (Remapper)
378       Remapper->applyRemapping(Ctx);
379     FunctionSamples::UseMD5 = useMD5();
380     return sampleprof_error::success;
381   }
382 
383   /// The implementaion to read sample profiles from the associated file.
384   virtual std::error_code readImpl() = 0;
385 
386   /// Print the profile for \p FContext on stream \p OS.
387   void dumpFunctionProfile(SampleContext FContext, raw_ostream &OS = dbgs());
388 
389   /// Collect functions with definitions in Module M. For reader which
390   /// support loading function profiles on demand, return true when the
391   /// reader has been given a module. Always return false for reader
392   /// which doesn't support loading function profiles on demand.
393   virtual bool collectFuncsFromModule() { return false; }
394 
395   /// Print all the profiles on stream \p OS.
396   void dump(raw_ostream &OS = dbgs());
397 
398   /// Print all the profiles on stream \p OS in the JSON format.
399   void dumpJson(raw_ostream &OS = dbgs());
400 
401   /// Return the samples collected for function \p F.
402   FunctionSamples *getSamplesFor(const Function &F) {
403     // The function name may have been updated by adding suffix. Call
404     // a helper to (optionally) strip off suffixes so that we can
405     // match against the original function name in the profile.
406     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
407     return getSamplesFor(CanonName);
408   }
409 
410   /// Return the samples collected for function \p F, create empty
411   /// FunctionSamples if it doesn't exist.
412   FunctionSamples *getOrCreateSamplesFor(const Function &F) {
413     std::string FGUID;
414     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
415     CanonName = getRepInFormat(CanonName, useMD5(), FGUID);
416     auto It = Profiles.find(CanonName);
417     if (It != Profiles.end())
418       return &It->second;
419     if (!FGUID.empty()) {
420       assert(useMD5() && "New name should only be generated for md5 profile");
421       CanonName = *MD5NameBuffer.insert(FGUID).first;
422     }
423     return &Profiles[CanonName];
424   }
425 
426   /// Return the samples collected for function \p F.
427   virtual FunctionSamples *getSamplesFor(StringRef Fname) {
428     std::string FGUID;
429     Fname = getRepInFormat(Fname, useMD5(), FGUID);
430     auto It = Profiles.find(Fname);
431     if (It != Profiles.end())
432       return &It->second;
433 
434     if (Remapper) {
435       if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
436         auto It = Profiles.find(*NameInProfile);
437         if (It != Profiles.end())
438           return &It->second;
439       }
440     }
441     return nullptr;
442   }
443 
444   /// Return all the profiles.
445   SampleProfileMap &getProfiles() { return Profiles; }
446 
447   /// Report a parse error message.
448   void reportError(int64_t LineNumber, const Twine &Msg) const {
449     Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
450                                              LineNumber, Msg));
451   }
452 
453   /// Create a sample profile reader appropriate to the file format.
454   /// Create a remapper underlying if RemapFilename is not empty.
455   /// Parameter P specifies the FSDiscriminatorPass.
456   static ErrorOr<std::unique_ptr<SampleProfileReader>>
457   create(const std::string Filename, LLVMContext &C, vfs::FileSystem &FS,
458          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
459          const std::string RemapFilename = "");
460 
461   /// Create a sample profile reader from the supplied memory buffer.
462   /// Create a remapper underlying if RemapFilename is not empty.
463   /// Parameter P specifies the FSDiscriminatorPass.
464   static ErrorOr<std::unique_ptr<SampleProfileReader>>
465   create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C, vfs::FileSystem &FS,
466          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
467          const std::string RemapFilename = "");
468 
469   /// Return the profile summary.
470   ProfileSummary &getSummary() const { return *(Summary.get()); }
471 
472   MemoryBuffer *getBuffer() const { return Buffer.get(); }
473 
474   /// \brief Return the profile format.
475   SampleProfileFormat getFormat() const { return Format; }
476 
477   /// Whether input profile is based on pseudo probes.
478   bool profileIsProbeBased() const { return ProfileIsProbeBased; }
479 
480   /// Whether input profile is fully context-sensitive.
481   bool profileIsCS() const { return ProfileIsCS; }
482 
483   /// Whether input profile contains ShouldBeInlined contexts.
484   bool profileIsPreInlined() const { return ProfileIsPreInlined; }
485 
486   /// Whether input profile is flow-sensitive.
487   bool profileIsFS() const { return ProfileIsFS; }
488 
489   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
490     return nullptr;
491   };
492 
493   /// It includes all the names that have samples either in outline instance
494   /// or inline instance.
495   virtual std::vector<StringRef> *getNameTable() { return nullptr; }
496   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
497 
498   /// Return whether names in the profile are all MD5 numbers.
499   bool useMD5() const { return ProfileIsMD5; }
500 
501   /// Force the profile to use MD5 in Sample contexts, even if function names
502   /// are present.
503   virtual void setProfileUseMD5() { ProfileIsMD5 = true; }
504 
505   /// Don't read profile without context if the flag is set. This is only meaningful
506   /// for ExtBinary format.
507   virtual void setSkipFlatProf(bool Skip) {}
508   /// Return whether any name in the profile contains ".__uniq." suffix.
509   virtual bool hasUniqSuffix() { return false; }
510 
511   SampleProfileReaderItaniumRemapper *getRemapper() { return Remapper.get(); }
512 
513   void setModule(const Module *Mod) { M = Mod; }
514 
515 protected:
516   /// Map every function to its associated profile.
517   ///
518   /// The profile of every function executed at runtime is collected
519   /// in the structure FunctionSamples. This maps function objects
520   /// to their corresponding profiles.
521   SampleProfileMap Profiles;
522 
523   /// LLVM context used to emit diagnostics.
524   LLVMContext &Ctx;
525 
526   /// Memory buffer holding the profile file.
527   std::unique_ptr<MemoryBuffer> Buffer;
528 
529   /// Extra name buffer holding names created on demand.
530   /// This should only be needed for md5 profiles.
531   std::unordered_set<std::string> MD5NameBuffer;
532 
533   /// Profile summary information.
534   std::unique_ptr<ProfileSummary> Summary;
535 
536   /// Take ownership of the summary of this reader.
537   static std::unique_ptr<ProfileSummary>
538   takeSummary(SampleProfileReader &Reader) {
539     return std::move(Reader.Summary);
540   }
541 
542   /// Compute summary for this profile.
543   void computeSummary();
544 
545   std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
546 
547   /// \brief Whether samples are collected based on pseudo probes.
548   bool ProfileIsProbeBased = false;
549 
550   /// Whether function profiles are context-sensitive flat profiles.
551   bool ProfileIsCS = false;
552 
553   /// Whether function profile contains ShouldBeInlined contexts.
554   bool ProfileIsPreInlined = false;
555 
556   /// Number of context-sensitive profiles.
557   uint32_t CSProfileCount = 0;
558 
559   /// Whether the function profiles use FS discriminators.
560   bool ProfileIsFS = false;
561 
562   /// \brief The format of sample.
563   SampleProfileFormat Format = SPF_None;
564 
565   /// \brief The current module being compiled if SampleProfileReader
566   /// is used by compiler. If SampleProfileReader is used by other
567   /// tools which are not compiler, M is usually nullptr.
568   const Module *M = nullptr;
569 
570   /// Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
571   /// The default is to keep all the bits.
572   uint32_t MaskedBitFrom = 31;
573 
574   /// Whether the profile uses MD5 for Sample Contexts and function names. This
575   /// can be one-way overriden by the user to force use MD5.
576   bool ProfileIsMD5 = false;
577 };
578 
579 class SampleProfileReaderText : public SampleProfileReader {
580 public:
581   SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
582       : SampleProfileReader(std::move(B), C, SPF_Text) {}
583 
584   /// Read and validate the file header.
585   std::error_code readHeader() override { return sampleprof_error::success; }
586 
587   /// Read sample profiles from the associated file.
588   std::error_code readImpl() override;
589 
590   /// Return true if \p Buffer is in the format supported by this class.
591   static bool hasFormat(const MemoryBuffer &Buffer);
592 
593   /// Text format sample profile does not support MD5 for now.
594   void setProfileUseMD5() override {}
595 
596 private:
597   /// CSNameTable is used to save full context vectors. This serves as an
598   /// underlying immutable buffer for all clients.
599   std::list<SampleContextFrameVector> CSNameTable;
600 };
601 
602 class SampleProfileReaderBinary : public SampleProfileReader {
603 public:
604   SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
605                             SampleProfileFormat Format = SPF_None)
606       : SampleProfileReader(std::move(B), C, Format) {}
607 
608   /// Read and validate the file header.
609   std::error_code readHeader() override;
610 
611   /// Read sample profiles from the associated file.
612   std::error_code readImpl() override;
613 
614   /// It includes all the names that have samples either in outline instance
615   /// or inline instance.
616   std::vector<StringRef> *getNameTable() override { return &NameTable; }
617 
618 protected:
619   /// Read a numeric value of type T from the profile.
620   ///
621   /// If an error occurs during decoding, a diagnostic message is emitted and
622   /// EC is set.
623   ///
624   /// \returns the read value.
625   template <typename T> ErrorOr<T> readNumber();
626 
627   /// Read a numeric value of type T from the profile. The value is saved
628   /// without encoded.
629   template <typename T> ErrorOr<T> readUnencodedNumber();
630 
631   /// Read a string from the profile.
632   ///
633   /// If an error occurs during decoding, a diagnostic message is emitted and
634   /// EC is set.
635   ///
636   /// \returns the read value.
637   ErrorOr<StringRef> readString();
638 
639   /// Read the string index and check whether it overflows the table.
640   template <typename T> inline ErrorOr<size_t> readStringIndex(T &Table);
641 
642   /// Read the next function profile instance.
643   std::error_code readFuncProfile(const uint8_t *Start);
644 
645   /// Read the contents of the given profile instance.
646   std::error_code readProfile(FunctionSamples &FProfile);
647 
648   /// Read the contents of Magic number and Version number.
649   std::error_code readMagicIdent();
650 
651   /// Read profile summary.
652   std::error_code readSummary();
653 
654   /// Read the whole name table.
655   std::error_code readNameTable();
656 
657   /// Read a string indirectly via the name table.
658   ErrorOr<StringRef> readStringFromTable();
659 
660   /// Read a context indirectly via the CSNameTable.
661   ErrorOr<SampleContextFrames> readContextFromTable();
662 
663   /// Read a context indirectly via the CSNameTable if the profile has context,
664   /// otherwise same as readStringFromTable.
665   ErrorOr<SampleContext> readSampleContextFromTable();
666 
667   /// Points to the current location in the buffer.
668   const uint8_t *Data = nullptr;
669 
670   /// Points to the end of the buffer.
671   const uint8_t *End = nullptr;
672 
673   /// Function name table.
674   std::vector<StringRef> NameTable;
675 
676   /// If MD5 is used in NameTable section, the section saves uint64_t data.
677   /// The uint64_t data has to be converted to a string and then the string
678   /// will be used to initialize StringRef in NameTable.
679   /// Note NameTable contains StringRef so it needs another buffer to own
680   /// the string data. MD5StringBuf serves as the string buffer that is
681   /// referenced by NameTable (vector of StringRef). We make sure
682   /// the lifetime of MD5StringBuf is not shorter than that of NameTable.
683   std::vector<std::string> MD5StringBuf;
684 
685   /// The starting address of NameTable containing fixed length MD5.
686   const uint8_t *MD5NameMemStart = nullptr;
687 
688   /// CSNameTable is used to save full context vectors. It is the backing buffer
689   /// for SampleContextFrames.
690   std::vector<SampleContextFrameVector> CSNameTable;
691 
692 private:
693   std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
694   virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
695 };
696 
697 class SampleProfileReaderRawBinary : public SampleProfileReaderBinary {
698 private:
699   std::error_code verifySPMagic(uint64_t Magic) override;
700 
701 public:
702   SampleProfileReaderRawBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
703                                SampleProfileFormat Format = SPF_Binary)
704       : SampleProfileReaderBinary(std::move(B), C, Format) {}
705 
706   /// \brief Return true if \p Buffer is in the format supported by this class.
707   static bool hasFormat(const MemoryBuffer &Buffer);
708 };
709 
710 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
711 /// the basic structure of the extensible binary format.
712 /// The format is organized in sections except the magic and version number
713 /// at the beginning. There is a section table before all the sections, and
714 /// each entry in the table describes the entry type, start, size and
715 /// attributes. The format in each section is defined by the section itself.
716 ///
717 /// It is easy to add a new section while maintaining the backward
718 /// compatibility of the profile. Nothing extra needs to be done. If we want
719 /// to extend an existing section, like add cache misses information in
720 /// addition to the sample count in the profile body, we can add a new section
721 /// with the extension and retire the existing section, and we could choose
722 /// to keep the parser of the old section if we want the reader to be able
723 /// to read both new and old format profile.
724 ///
725 /// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
726 /// commonly used sections of a profile in extensible binary format. It is
727 /// possible to define other types of profile inherited from
728 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
729 class SampleProfileReaderExtBinaryBase : public SampleProfileReaderBinary {
730 private:
731   std::error_code decompressSection(const uint8_t *SecStart,
732                                     const uint64_t SecSize,
733                                     const uint8_t *&DecompressBuf,
734                                     uint64_t &DecompressBufSize);
735 
736   BumpPtrAllocator Allocator;
737 
738 protected:
739   std::vector<SecHdrTableEntry> SecHdrTable;
740   std::error_code readSecHdrTableEntry(uint64_t Idx);
741   std::error_code readSecHdrTable();
742 
743   std::error_code readFuncMetadata(bool ProfileHasAttribute);
744   std::error_code readFuncMetadata(bool ProfileHasAttribute,
745                                    FunctionSamples *FProfile);
746   std::error_code readFuncOffsetTable();
747   std::error_code readFuncProfiles();
748   std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5);
749   std::error_code readCSNameTableSec();
750   std::error_code readProfileSymbolList();
751 
752   std::error_code readHeader() override;
753   std::error_code verifySPMagic(uint64_t Magic) override = 0;
754   virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
755                                          const SecHdrTableEntry &Entry);
756   // placeholder for subclasses to dispatch their own section readers.
757   virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
758 
759   /// Determine which container readFuncOffsetTable() should populate, the list
760   /// FuncOffsetList or the map FuncOffsetTable.
761   bool useFuncOffsetList() const;
762 
763   std::unique_ptr<ProfileSymbolList> ProfSymList;
764 
765   /// The table mapping from function context to the offset of its
766   /// FunctionSample towards file start.
767   /// At most one of FuncOffsetTable and FuncOffsetList is populated.
768   DenseMap<SampleContext, uint64_t> FuncOffsetTable;
769 
770   /// The list version of FuncOffsetTable. This is used if every entry is
771   /// being accessed.
772   std::vector<std::pair<SampleContext, uint64_t>> FuncOffsetList;
773 
774   /// The set containing the functions to use when compiling a module.
775   DenseSet<StringRef> FuncsToUse;
776 
777   /// If SkipFlatProf is true, skip the sections with
778   /// SecFlagFlat flag.
779   bool SkipFlatProf = false;
780 
781 public:
782   SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,
783                                    LLVMContext &C, SampleProfileFormat Format)
784       : SampleProfileReaderBinary(std::move(B), C, Format) {}
785 
786   /// Read sample profiles in extensible format from the associated file.
787   std::error_code readImpl() override;
788 
789   /// Get the total size of all \p Type sections.
790   uint64_t getSectionSize(SecType Type);
791   /// Get the total size of header and all sections.
792   uint64_t getFileSize();
793   bool dumpSectionInfo(raw_ostream &OS = dbgs()) 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   std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
800     return std::move(ProfSymList);
801   };
802 
803   void setSkipFlatProf(bool Skip) override { SkipFlatProf = Skip; }
804 };
805 
806 class SampleProfileReaderExtBinary : public SampleProfileReaderExtBinaryBase {
807 private:
808   std::error_code verifySPMagic(uint64_t Magic) override;
809   std::error_code readCustomSection(const SecHdrTableEntry &Entry) override {
810     // Update the data reader pointer to the end of the section.
811     Data = End;
812     return sampleprof_error::success;
813   };
814 
815 public:
816   SampleProfileReaderExtBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
817                                SampleProfileFormat Format = SPF_Ext_Binary)
818       : SampleProfileReaderExtBinaryBase(std::move(B), C, Format) {}
819 
820   /// \brief Return true if \p Buffer is in the format supported by this class.
821   static bool hasFormat(const MemoryBuffer &Buffer);
822 };
823 
824 using InlineCallStack = SmallVector<FunctionSamples *, 10>;
825 
826 // Supported histogram types in GCC.  Currently, we only need support for
827 // call target histograms.
828 enum HistType {
829   HIST_TYPE_INTERVAL,
830   HIST_TYPE_POW2,
831   HIST_TYPE_SINGLE_VALUE,
832   HIST_TYPE_CONST_DELTA,
833   HIST_TYPE_INDIR_CALL,
834   HIST_TYPE_AVERAGE,
835   HIST_TYPE_IOR,
836   HIST_TYPE_INDIR_CALL_TOPN
837 };
838 
839 class SampleProfileReaderGCC : public SampleProfileReader {
840 public:
841   SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
842       : SampleProfileReader(std::move(B), C, SPF_GCC),
843         GcovBuffer(Buffer.get()) {}
844 
845   /// Read and validate the file header.
846   std::error_code readHeader() override;
847 
848   /// Read sample profiles from the associated file.
849   std::error_code readImpl() override;
850 
851   /// Return true if \p Buffer is in the format supported by this class.
852   static bool hasFormat(const MemoryBuffer &Buffer);
853 
854 protected:
855   std::error_code readNameTable();
856   std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
857                                          bool Update, uint32_t Offset);
858   std::error_code readFunctionProfiles();
859   std::error_code skipNextWord();
860   template <typename T> ErrorOr<T> readNumber();
861   ErrorOr<StringRef> readString();
862 
863   /// Read the section tag and check that it's the same as \p Expected.
864   std::error_code readSectionTag(uint32_t Expected);
865 
866   /// GCOV buffer containing the profile.
867   GCOVBuffer GcovBuffer;
868 
869   /// Function names in this profile.
870   std::vector<std::string> Names;
871 
872   /// GCOV tags used to separate sections in the profile file.
873   static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
874   static const uint32_t GCOVTagAFDOFunction = 0xac000000;
875 };
876 
877 } // end namespace sampleprof
878 
879 } // end namespace llvm
880 
881 #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
882