1 //=-- SampleProf.h - Sampling profiling format support --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains common definitions used in the reading and writing of
11 // sample profile data.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H_
16 #define LLVM_PROFILEDATA_SAMPLEPROF_H_
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorOr.h"
22 #include "llvm/Support/raw_ostream.h"
25 #include <system_error>
29 const std::error_category &sampleprof_category();
31 enum class sampleprof_error {
39 unsupported_writing_format,
45 inline std::error_code make_error_code(sampleprof_error E) {
46 return std::error_code(static_cast<int>(E), sampleprof_category());
49 inline sampleprof_error MergeResult(sampleprof_error &Accumulator,
50 sampleprof_error Result) {
51 // Prefer first error encountered as later errors may be secondary effects of
52 // the initial problem.
53 if (Accumulator == sampleprof_error::success &&
54 Result != sampleprof_error::success)
59 } // end namespace llvm
63 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
68 namespace sampleprof {
70 static inline uint64_t SPMagic() {
71 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
72 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
73 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
74 uint64_t('2') << (64 - 56) | uint64_t(0xff);
77 static inline uint64_t SPVersion() { return 102; }
79 /// Represents the relative location of an instruction.
81 /// Instruction locations are specified by the line offset from the
82 /// beginning of the function (marked by the line where the function
83 /// header is) and the discriminator value within that line.
85 /// The discriminator value is useful to distinguish instructions
86 /// that are on the same line but belong to different basic blocks
87 /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
89 LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
90 void print(raw_ostream &OS) const;
92 bool operator<(const LineLocation &O) const {
93 return LineOffset < O.LineOffset ||
94 (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
98 uint32_t Discriminator;
101 raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc);
103 /// Represents the relative location of a callsite.
105 /// Callsite locations are specified by the line offset from the
106 /// beginning of the function (marked by the line where the function
107 /// head is), the discriminator value within that line, and the callee
109 struct CallsiteLocation : public LineLocation {
110 CallsiteLocation(uint32_t L, uint32_t D, StringRef N)
111 : LineLocation(L, D), CalleeName(N) {}
112 void print(raw_ostream &OS) const;
115 StringRef CalleeName;
118 raw_ostream &operator<<(raw_ostream &OS, const CallsiteLocation &Loc);
120 /// Representation of a single sample record.
122 /// A sample record is represented by a positive integer value, which
123 /// indicates how frequently was the associated line location executed.
125 /// Additionally, if the associated location contains a function call,
126 /// the record will hold a list of all the possible called targets. For
127 /// direct calls, this will be the exact function being invoked. For
128 /// indirect calls (function pointers, virtual table dispatch), this
129 /// will be a list of one or more functions.
132 typedef StringMap<uint64_t> CallTargetMap;
134 SampleRecord() : NumSamples(0), CallTargets() {}
136 /// Increment the number of samples for this record by \p S.
137 /// Optionally scale sample count \p S by \p Weight.
139 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
140 /// around unsigned integers.
141 sampleprof_error addSamples(uint64_t S, uint64_t Weight = 1) {
143 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
144 return Overflowed ? sampleprof_error::counter_overflow
145 : sampleprof_error::success;
148 /// Add called function \p F with samples \p S.
149 /// Optionally scale sample count \p S by \p Weight.
151 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
152 /// around unsigned integers.
153 sampleprof_error addCalledTarget(StringRef F, uint64_t S,
154 uint64_t Weight = 1) {
155 uint64_t &TargetSamples = CallTargets[F];
158 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
159 return Overflowed ? sampleprof_error::counter_overflow
160 : sampleprof_error::success;
163 /// Return true if this sample record contains function calls.
164 bool hasCalls() const { return CallTargets.size() > 0; }
166 uint64_t getSamples() const { return NumSamples; }
167 const CallTargetMap &getCallTargets() const { return CallTargets; }
169 /// Merge the samples in \p Other into this record.
170 /// Optionally scale sample counts by \p Weight.
171 sampleprof_error merge(const SampleRecord &Other, uint64_t Weight = 1) {
172 sampleprof_error Result = addSamples(Other.getSamples(), Weight);
173 for (const auto &I : Other.getCallTargets()) {
174 MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
179 void print(raw_ostream &OS, unsigned Indent) const;
184 CallTargetMap CallTargets;
187 raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample);
189 typedef std::map<LineLocation, SampleRecord> BodySampleMap;
190 class FunctionSamples;
191 typedef std::map<CallsiteLocation, FunctionSamples> CallsiteSampleMap;
193 /// Representation of the samples collected for a function.
195 /// This data structure contains all the collected samples for the body
196 /// of a function. Each sample corresponds to a LineLocation instance
197 /// within the body of the function.
198 class FunctionSamples {
200 FunctionSamples() : TotalSamples(0), TotalHeadSamples(0) {}
201 void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
203 sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight = 1) {
206 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
207 return Overflowed ? sampleprof_error::counter_overflow
208 : sampleprof_error::success;
210 sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight = 1) {
213 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
214 return Overflowed ? sampleprof_error::counter_overflow
215 : sampleprof_error::success;
217 sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
218 uint64_t Num, uint64_t Weight = 1) {
219 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
222 sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
223 uint32_t Discriminator,
224 std::string FName, uint64_t Num,
225 uint64_t Weight = 1) {
226 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
230 /// Return the number of samples collected at the given location.
231 /// Each location is specified by \p LineOffset and \p Discriminator.
232 /// If the location is not found in profile, return error.
233 ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
234 uint32_t Discriminator) const {
235 const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
236 if (ret == BodySamples.end())
237 return std::error_code();
239 return ret->second.getSamples();
242 /// Return the function samples at the given callsite location.
243 FunctionSamples &functionSamplesAt(const CallsiteLocation &Loc) {
244 return CallsiteSamples[Loc];
247 /// Return a pointer to function samples at the given callsite location.
248 const FunctionSamples *
249 findFunctionSamplesAt(const CallsiteLocation &Loc) const {
250 auto iter = CallsiteSamples.find(Loc);
251 if (iter == CallsiteSamples.end()) {
254 return &iter->second;
258 bool empty() const { return TotalSamples == 0; }
260 /// Return the total number of samples collected inside the function.
261 uint64_t getTotalSamples() const { return TotalSamples; }
263 /// Return the total number of samples collected at the head of the
265 uint64_t getHeadSamples() const { return TotalHeadSamples; }
267 /// Return all the samples collected in the body of the function.
268 const BodySampleMap &getBodySamples() const { return BodySamples; }
270 /// Return all the callsite samples collected in the body of the function.
271 const CallsiteSampleMap &getCallsiteSamples() const {
272 return CallsiteSamples;
275 /// Merge the samples in \p Other into this one.
276 /// Optionally scale samples by \p Weight.
277 sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight = 1) {
278 sampleprof_error Result = sampleprof_error::success;
279 MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
280 MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
281 for (const auto &I : Other.getBodySamples()) {
282 const LineLocation &Loc = I.first;
283 const SampleRecord &Rec = I.second;
284 MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
286 for (const auto &I : Other.getCallsiteSamples()) {
287 const CallsiteLocation &Loc = I.first;
288 const FunctionSamples &Rec = I.second;
289 MergeResult(Result, functionSamplesAt(Loc).merge(Rec, Weight));
295 /// Total number of samples collected inside this function.
297 /// Samples are cumulative, they include all the samples collected
298 /// inside this function and all its inlined callees.
299 uint64_t TotalSamples;
301 /// Total number of samples collected at the head of the function.
302 /// This is an approximation of the number of calls made to this function
304 uint64_t TotalHeadSamples;
306 /// Map instruction locations to collected samples.
308 /// Each entry in this map contains the number of samples
309 /// collected at the corresponding line offset. All line locations
310 /// are an offset from the start of the function.
311 BodySampleMap BodySamples;
313 /// Map call sites to collected samples for the called function.
315 /// Each entry in this map corresponds to all the samples
316 /// collected for the inlined function call at the given
317 /// location. For example, given:
325 /// If the bar() and baz() calls were inlined inside foo(), this
326 /// map will contain two entries. One for all the samples collected
327 /// in the call to bar() at line offset 1, the other for all the samples
328 /// collected in the call to baz() at line offset 8.
329 CallsiteSampleMap CallsiteSamples;
332 raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
334 /// Sort a LocationT->SampleT map by LocationT.
336 /// It produces a sorted list of <LocationT, SampleT> records by ascending
337 /// order of LocationT.
338 template <class LocationT, class SampleT> class SampleSorter {
340 typedef std::pair<const LocationT, SampleT> SamplesWithLoc;
341 typedef SmallVector<const SamplesWithLoc *, 20> SamplesWithLocList;
343 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
344 for (const auto &I : Samples)
346 std::stable_sort(V.begin(), V.end(),
347 [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
348 return A->first < B->first;
351 const SamplesWithLocList &get() const { return V; }
354 SamplesWithLocList V;
357 } // end namespace sampleprof
359 } // end namespace llvm
361 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H_