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