SamplePGO - Add dump routines for LineLocation, SampleRecord and FunctionSamples
[oota-llvm.git] / include / llvm / ProfileData / SampleProf.h
1 //=-- SampleProf.h - Sampling profiling format support --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains common definitions used in the reading and writing of
11 // sample profile data.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H_
16 #define LLVM_PROFILEDATA_SAMPLEPROF_H_
17
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <system_error>
25
26 namespace llvm {
27
28 const std::error_category &sampleprof_category();
29
30 enum class sampleprof_error {
31   success = 0,
32   bad_magic,
33   unsupported_version,
34   too_large,
35   truncated,
36   malformed,
37   unrecognized_format,
38   unsupported_writing_format,
39   truncated_name_table,
40   not_implemented
41 };
42
43 inline std::error_code make_error_code(sampleprof_error E) {
44   return std::error_code(static_cast<int>(E), sampleprof_category());
45 }
46
47 } // end namespace llvm
48
49 namespace std {
50 template <>
51 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
52 }
53
54 namespace llvm {
55
56 namespace sampleprof {
57
58 static inline uint64_t SPMagic() {
59   return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
60          uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
61          uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
62          uint64_t('2') << (64 - 56) | uint64_t(0xff);
63 }
64
65 static inline uint64_t SPVersion() { return 102; }
66
67 /// Represents the relative location of an instruction.
68 ///
69 /// Instruction locations are specified by the line offset from the
70 /// beginning of the function (marked by the line where the function
71 /// header is) and the discriminator value within that line.
72 ///
73 /// The discriminator value is useful to distinguish instructions
74 /// that are on the same line but belong to different basic blocks
75 /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
76 struct LineLocation {
77   LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
78   void print(raw_ostream &OS) const {
79     OS << LineOffset;
80     if (Discriminator > 0)
81       OS << "." << Discriminator;
82   }
83   void dump() const { print(dbgs()); }
84
85   uint32_t LineOffset;
86   uint32_t Discriminator;
87 };
88
89 inline raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc) {
90   Loc.print(OS);
91   return OS;
92 }
93
94 /// Represents the relative location of a callsite.
95 ///
96 /// Callsite locations are specified by the line offset from the
97 /// beginning of the function (marked by the line where the function
98 /// head is), the discriminator value within that line, and the callee
99 /// function name.
100 struct CallsiteLocation : public LineLocation {
101   CallsiteLocation(uint32_t L, uint32_t D, StringRef N)
102       : LineLocation(L, D), CalleeName(N) {}
103   StringRef CalleeName;
104
105   void print(raw_ostream &OS) const {
106     LineLocation::print(OS);
107     OS << ": inlined callee: " << CalleeName;
108   }
109   void dump() const { print(dbgs()); }
110 };
111
112 inline raw_ostream &operator<<(raw_ostream &OS, const CallsiteLocation &Loc) {
113   Loc.print(OS);
114   return OS;
115 }
116
117 } // End namespace sampleprof
118
119 template <> struct DenseMapInfo<sampleprof::LineLocation> {
120   typedef DenseMapInfo<uint32_t> OffsetInfo;
121   typedef DenseMapInfo<uint32_t> DiscriminatorInfo;
122   static inline sampleprof::LineLocation getEmptyKey() {
123     return sampleprof::LineLocation(OffsetInfo::getEmptyKey(),
124                                     DiscriminatorInfo::getEmptyKey());
125   }
126   static inline sampleprof::LineLocation getTombstoneKey() {
127     return sampleprof::LineLocation(OffsetInfo::getTombstoneKey(),
128                                     DiscriminatorInfo::getTombstoneKey());
129   }
130   static inline unsigned getHashValue(sampleprof::LineLocation Val) {
131     return DenseMapInfo<std::pair<uint32_t, uint32_t>>::getHashValue(
132         std::pair<uint32_t, uint32_t>(Val.LineOffset, Val.Discriminator));
133   }
134   static inline bool isEqual(sampleprof::LineLocation LHS,
135                              sampleprof::LineLocation RHS) {
136     return LHS.LineOffset == RHS.LineOffset &&
137            LHS.Discriminator == RHS.Discriminator;
138   }
139 };
140
141 template <> struct DenseMapInfo<sampleprof::CallsiteLocation> {
142   typedef DenseMapInfo<uint32_t> OffsetInfo;
143   typedef DenseMapInfo<uint32_t> DiscriminatorInfo;
144   typedef DenseMapInfo<StringRef> CalleeNameInfo;
145   static inline sampleprof::CallsiteLocation getEmptyKey() {
146     return sampleprof::CallsiteLocation(OffsetInfo::getEmptyKey(),
147                                         DiscriminatorInfo::getEmptyKey(), "");
148   }
149   static inline sampleprof::CallsiteLocation getTombstoneKey() {
150     return sampleprof::CallsiteLocation(OffsetInfo::getTombstoneKey(),
151                                         DiscriminatorInfo::getTombstoneKey(),
152                                         "");
153   }
154   static inline unsigned getHashValue(sampleprof::CallsiteLocation Val) {
155     return DenseMapInfo<std::pair<uint32_t, uint32_t>>::getHashValue(
156         std::pair<uint32_t, uint32_t>(Val.LineOffset, Val.Discriminator));
157   }
158   static inline bool isEqual(sampleprof::CallsiteLocation LHS,
159                              sampleprof::CallsiteLocation RHS) {
160     return LHS.LineOffset == RHS.LineOffset &&
161            LHS.Discriminator == RHS.Discriminator &&
162            LHS.CalleeName.equals(RHS.CalleeName);
163   }
164 };
165
166 namespace sampleprof {
167
168 /// Representation of a single sample record.
169 ///
170 /// A sample record is represented by a positive integer value, which
171 /// indicates how frequently was the associated line location executed.
172 ///
173 /// Additionally, if the associated location contains a function call,
174 /// the record will hold a list of all the possible called targets. For
175 /// direct calls, this will be the exact function being invoked. For
176 /// indirect calls (function pointers, virtual table dispatch), this
177 /// will be a list of one or more functions.
178 class SampleRecord {
179 public:
180   typedef StringMap<uint64_t> CallTargetMap;
181
182   SampleRecord() : NumSamples(0), CallTargets() {}
183
184   /// Increment the number of samples for this record by \p S.
185   ///
186   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
187   /// around unsigned integers.
188   void addSamples(uint64_t S) {
189     if (NumSamples <= std::numeric_limits<uint64_t>::max() - S)
190       NumSamples += S;
191     else
192       NumSamples = std::numeric_limits<uint64_t>::max();
193   }
194
195   /// Add called function \p F with samples \p S.
196   ///
197   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
198   /// around unsigned integers.
199   void addCalledTarget(StringRef F, uint64_t S) {
200     uint64_t &TargetSamples = CallTargets[F];
201     if (TargetSamples <= std::numeric_limits<uint64_t>::max() - S)
202       TargetSamples += S;
203     else
204       TargetSamples = std::numeric_limits<uint64_t>::max();
205   }
206
207   /// Return true if this sample record contains function calls.
208   bool hasCalls() const { return CallTargets.size() > 0; }
209
210   uint64_t getSamples() const { return NumSamples; }
211   const CallTargetMap &getCallTargets() const { return CallTargets; }
212
213   /// Merge the samples in \p Other into this record.
214   void merge(const SampleRecord &Other) {
215     addSamples(Other.getSamples());
216     for (const auto &I : Other.getCallTargets())
217       addCalledTarget(I.first(), I.second);
218   }
219
220   void print(raw_ostream &OS, unsigned Indent) const;
221   void dump() const { print(dbgs(), 0); }
222
223 private:
224   uint64_t NumSamples;
225   CallTargetMap CallTargets;
226 };
227
228 inline raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample) {
229   Sample.print(OS, 0);
230   return OS;
231 }
232
233 typedef DenseMap<LineLocation, SampleRecord> BodySampleMap;
234 class FunctionSamples;
235 typedef DenseMap<CallsiteLocation, FunctionSamples> CallsiteSampleMap;
236
237 /// Representation of the samples collected for a function.
238 ///
239 /// This data structure contains all the collected samples for the body
240 /// of a function. Each sample corresponds to a LineLocation instance
241 /// within the body of the function.
242 class FunctionSamples {
243 public:
244   FunctionSamples() : TotalSamples(0), TotalHeadSamples(0) {}
245   void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
246   void dump(void) const { print(); }
247   void addTotalSamples(uint64_t Num) { TotalSamples += Num; }
248   void addHeadSamples(uint64_t Num) { TotalHeadSamples += Num; }
249   void addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
250                       uint64_t Num) {
251     BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(Num);
252   }
253   void addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator,
254                               std::string FName, uint64_t Num) {
255     BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(FName,
256                                                                          Num);
257   }
258
259   /// Return the number of samples collected at the given location.
260   /// Each location is specified by \p LineOffset and \p Discriminator.
261   /// If the location is not found in profile, return error.
262   ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
263                                   uint32_t Discriminator) const {
264     const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
265     if (ret == BodySamples.end())
266       return std::error_code();
267     else
268       return ret->second.getSamples();
269   }
270
271   /// Return the function samples at the given callsite location.
272   FunctionSamples &functionSamplesAt(const CallsiteLocation &Loc) {
273     return CallsiteSamples[Loc];
274   }
275
276   /// Return a pointer to function samples at the given callsite location.
277   const FunctionSamples *
278   findFunctionSamplesAt(const CallsiteLocation &Loc) const {
279     auto iter = CallsiteSamples.find(Loc);
280     if (iter == CallsiteSamples.end()) {
281       return nullptr;
282     } else {
283       return &iter->second;
284     }
285   }
286
287   bool empty() const { return TotalSamples == 0; }
288
289   /// Return the total number of samples collected inside the function.
290   uint64_t getTotalSamples() const { return TotalSamples; }
291
292   /// Return the total number of samples collected at the head of the
293   /// function.
294   uint64_t getHeadSamples() const { return TotalHeadSamples; }
295
296   /// Return all the samples collected in the body of the function.
297   const BodySampleMap &getBodySamples() const { return BodySamples; }
298
299   /// Return all the callsite samples collected in the body of the function.
300   const CallsiteSampleMap &getCallsiteSamples() const {
301     return CallsiteSamples;
302   }
303
304   /// Merge the samples in \p Other into this one.
305   void merge(const FunctionSamples &Other) {
306     addTotalSamples(Other.getTotalSamples());
307     addHeadSamples(Other.getHeadSamples());
308     for (const auto &I : Other.getBodySamples()) {
309       const LineLocation &Loc = I.first;
310       const SampleRecord &Rec = I.second;
311       BodySamples[Loc].merge(Rec);
312     }
313     for (const auto &I : Other.getCallsiteSamples()) {
314       const CallsiteLocation &Loc = I.first;
315       const FunctionSamples &Rec = I.second;
316       functionSamplesAt(Loc).merge(Rec);
317     }
318   }
319
320 private:
321   /// Total number of samples collected inside this function.
322   ///
323   /// Samples are cumulative, they include all the samples collected
324   /// inside this function and all its inlined callees.
325   uint64_t TotalSamples;
326
327   /// Total number of samples collected at the head of the function.
328   /// This is an approximation of the number of calls made to this function
329   /// at runtime.
330   uint64_t TotalHeadSamples;
331
332   /// Map instruction locations to collected samples.
333   ///
334   /// Each entry in this map contains the number of samples
335   /// collected at the corresponding line offset. All line locations
336   /// are an offset from the start of the function.
337   BodySampleMap BodySamples;
338
339   /// Map call sites to collected samples for the called function.
340   ///
341   /// Each entry in this map corresponds to all the samples
342   /// collected for the inlined function call at the given
343   /// location. For example, given:
344   ///
345   ///     void foo() {
346   ///  1    bar();
347   ///  ...
348   ///  8    baz();
349   ///     }
350   ///
351   /// If the bar() and baz() calls were inlined inside foo(), this
352   /// map will contain two entries.  One for all the samples collected
353   /// in the call to bar() at line offset 1, the other for all the samples
354   /// collected in the call to baz() at line offset 8.
355   CallsiteSampleMap CallsiteSamples;
356 };
357
358 inline raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS) {
359   FS.print(OS);
360   return OS;
361 }
362
363 } // end namespace sampleprof
364
365 } // end namespace llvm
366
367 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H_