1 //===- InstrProfWriter.h - Instrumented profiling writer --------*- 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 support for writing profiling data for instrumentation
10 // based PGO and coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_PROFILEDATA_INSTRPROFWRITER_H
15 #define LLVM_PROFILEDATA_INSTRPROFWRITER_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/Object/BuildID.h"
22 #include "llvm/ProfileData/InstrProf.h"
23 #include "llvm/ProfileData/MemProf.h"
24 #include "llvm/Support/Error.h"
25 #include <cstdint>
26 #include <memory>
27 #include <random>
28 
29 namespace llvm {
30 
31 /// Writer for instrumentation based profile data.
32 class InstrProfRecordWriterTrait;
33 class ProfOStream;
34 class MemoryBuffer;
35 class raw_fd_ostream;
36 
37 class InstrProfWriter {
38 public:
39   using ProfilingData = SmallDenseMap<uint64_t, InstrProfRecord>;
40 
41 private:
42   bool Sparse;
43   StringMap<ProfilingData> FunctionData;
44   /// The maximum length of a single temporal profile trace.
45   uint64_t MaxTemporalProfTraceLength;
46   /// The maximum number of stored temporal profile traces.
47   uint64_t TemporalProfTraceReservoirSize;
48   /// The total number of temporal profile traces seen.
49   uint64_t TemporalProfTraceStreamSize = 0;
50   /// The list of temporal profile traces.
51   SmallVector<TemporalProfTraceTy> TemporalProfTraces;
52   std::mt19937 RNG;
53 
54   // A map to hold memprof data per function. The lower 64 bits obtained from
55   // the md5 hash of the function name is used to index into the map.
56   llvm::MapVector<GlobalValue::GUID, memprof::IndexedMemProfRecord>
57       MemProfRecordData;
58   // A map to hold frame id to frame mappings. The mappings are used to
59   // convert IndexedMemProfRecord to MemProfRecords with frame information
60   // inline.
61   llvm::MapVector<memprof::FrameId, memprof::Frame> MemProfFrameData;
62 
63   // List of binary ids.
64   std::vector<llvm::object::BuildID> BinaryIds;
65 
66   // An enum describing the attributes of the profile.
67   InstrProfKind ProfileKind = InstrProfKind::Unknown;
68   // Use raw pointer here for the incomplete type object.
69   InstrProfRecordWriterTrait *InfoObj;
70 
71   // Temporary support for writing the previous version of the format, to enable
72   // some forward compatibility. Currently this suppresses the writing of the
73   // new vtable names section and header fields.
74   // TODO: Consider enabling this with future version changes as well, to ease
75   // deployment of newer versions of llvm-profdata.
76   bool WritePrevVersion = false;
77 
78 public:
79   InstrProfWriter(bool Sparse = false,
80                   uint64_t TemporalProfTraceReservoirSize = 0,
81                   uint64_t MaxTemporalProfTraceLength = 0,
82                   bool WritePrevVersion = false);
83   ~InstrProfWriter();
84 
getProfileData()85   StringMap<ProfilingData> &getProfileData() { return FunctionData; }
86 
87   /// Add function counts for the given function. If there are already counts
88   /// for this function and the hash and number of counts match, each counter is
89   /// summed. Optionally scale counts by \p Weight.
90   void addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
91                  function_ref<void(Error)> Warn);
addRecord(NamedInstrProfRecord && I,function_ref<void (Error)> Warn)92   void addRecord(NamedInstrProfRecord &&I, function_ref<void(Error)> Warn) {
93     addRecord(std::move(I), 1, Warn);
94   }
95 
96   /// Add \p SrcTraces using reservoir sampling where \p SrcStreamSize is the
97   /// total number of temporal profiling traces the source has seen.
98   void addTemporalProfileTraces(SmallVectorImpl<TemporalProfTraceTy> &SrcTraces,
99                                 uint64_t SrcStreamSize);
100 
101   /// Add a memprof record for a function identified by its \p Id.
102   void addMemProfRecord(const GlobalValue::GUID Id,
103                         const memprof::IndexedMemProfRecord &Record);
104 
105   /// Add a memprof frame identified by the hash of the contents of the frame in
106   /// \p FrameId.
107   bool addMemProfFrame(const memprof::FrameId, const memprof::Frame &F,
108                        function_ref<void(Error)> Warn);
109 
110   // Add a binary id to the binary ids list.
111   void addBinaryIds(ArrayRef<llvm::object::BuildID> BIs);
112 
113   /// Merge existing function counts from the given writer.
114   void mergeRecordsFromWriter(InstrProfWriter &&IPW,
115                               function_ref<void(Error)> Warn);
116 
117   /// Write the profile to \c OS
118   Error write(raw_fd_ostream &OS);
119 
120   /// Write the profile to a string output stream \c OS
121   Error write(raw_string_ostream &OS);
122 
123   /// Write the profile in text format to \c OS
124   Error writeText(raw_fd_ostream &OS);
125 
126   /// Write temporal profile trace data to the header in text format to \c OS
127   void writeTextTemporalProfTraceData(raw_fd_ostream &OS,
128                                       InstrProfSymtab &Symtab);
129 
130   Error validateRecord(const InstrProfRecord &Func);
131 
132   /// Write \c Record in text format to \c OS
133   static void writeRecordInText(StringRef Name, uint64_t Hash,
134                                 const InstrProfRecord &Counters,
135                                 InstrProfSymtab &Symtab, raw_fd_ostream &OS);
136 
137   /// Write the profile, returning the raw data. For testing.
138   std::unique_ptr<MemoryBuffer> writeBuffer();
139 
140   /// Update the attributes of the current profile from the attributes
141   /// specified. An error is returned if IR and FE profiles are mixed.
mergeProfileKind(const InstrProfKind Other)142   Error mergeProfileKind(const InstrProfKind Other) {
143     // If the kind is unset, this is the first profile we are merging so just
144     // set it to the given type.
145     if (ProfileKind == InstrProfKind::Unknown) {
146       ProfileKind = Other;
147       return Error::success();
148     }
149 
150     // Returns true if merging is should fail assuming A and B are incompatible.
151     auto testIncompatible = [&](InstrProfKind A, InstrProfKind B) {
152       return (static_cast<bool>(ProfileKind & A) &&
153               static_cast<bool>(Other & B)) ||
154              (static_cast<bool>(ProfileKind & B) &&
155               static_cast<bool>(Other & A));
156     };
157 
158     // Check if the profiles are in-compatible. Clang frontend profiles can't be
159     // merged with other profile types.
160     if (static_cast<bool>(
161             (ProfileKind & InstrProfKind::FrontendInstrumentation) ^
162             (Other & InstrProfKind::FrontendInstrumentation))) {
163       return make_error<InstrProfError>(instrprof_error::unsupported_version);
164     }
165     if (testIncompatible(InstrProfKind::FunctionEntryOnly,
166                          InstrProfKind::FunctionEntryInstrumentation)) {
167       return make_error<InstrProfError>(
168           instrprof_error::unsupported_version,
169           "cannot merge FunctionEntryOnly profiles and BB profiles together");
170     }
171 
172     // Now we update the profile type with the bits that are set.
173     ProfileKind |= Other;
174     return Error::success();
175   }
176 
getProfileKind()177   InstrProfKind getProfileKind() const { return ProfileKind; }
178 
hasSingleByteCoverage()179   bool hasSingleByteCoverage() const {
180     return static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage);
181   }
182 
183   // Internal interface for testing purpose only.
184   void setValueProfDataEndianness(llvm::endianness Endianness);
185   void setOutputSparse(bool Sparse);
186   // Compute the overlap b/w this object and Other. Program level result is
187   // stored in Overlap and function level result is stored in FuncLevelOverlap.
188   void overlapRecord(NamedInstrProfRecord &&Other, OverlapStats &Overlap,
189                      OverlapStats &FuncLevelOverlap,
190                      const OverlapFuncFilters &FuncFilter);
191 
192 private:
193   void addRecord(StringRef Name, uint64_t Hash, InstrProfRecord &&I,
194                  uint64_t Weight, function_ref<void(Error)> Warn);
195   bool shouldEncodeData(const ProfilingData &PD);
196   /// Add \p Trace using reservoir sampling.
197   void addTemporalProfileTrace(TemporalProfTraceTy Trace);
198 
199   Error writeImpl(ProfOStream &OS);
200 };
201 
202 } // end namespace llvm
203 
204 #endif // LLVM_PROFILEDATA_INSTRPROFWRITER_H
205