Add show and merge tools for sample PGO profiles.
[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 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H_
15 #define LLVM_PROFILEDATA_SAMPLEPROF_H_
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22
23 #include <system_error>
24
25 namespace llvm {
26
27 const std::error_category &sampleprof_category();
28
29 enum class sampleprof_error {
30   success = 0,
31   bad_magic,
32   unsupported_version,
33   too_large,
34   truncated,
35   malformed,
36   unrecognized_format
37 };
38
39 inline std::error_code make_error_code(sampleprof_error E) {
40   return std::error_code(static_cast<int>(E), sampleprof_category());
41 }
42
43 } // end namespace llvm
44
45 namespace std {
46 template <>
47 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
48 }
49
50 namespace llvm {
51
52 namespace sampleprof {
53
54 static inline uint64_t SPMagic() {
55   return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
56          uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
57          uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
58          uint64_t('2') << (64 - 56) | uint64_t(0xff);
59 }
60
61 static inline uint64_t SPVersion() { return 100; }
62
63 /// \brief Represents the relative location of an instruction.
64 ///
65 /// Instruction locations are specified by the line offset from the
66 /// beginning of the function (marked by the line where the function
67 /// header is) and the discriminator value within that line.
68 ///
69 /// The discriminator value is useful to distinguish instructions
70 /// that are on the same line but belong to different basic blocks
71 /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
72 struct LineLocation {
73   LineLocation(int L, unsigned D) : LineOffset(L), Discriminator(D) {}
74   int LineOffset;
75   unsigned Discriminator;
76 };
77
78 } // End namespace sampleprof
79
80 template <> struct DenseMapInfo<sampleprof::LineLocation> {
81   typedef DenseMapInfo<int> OffsetInfo;
82   typedef DenseMapInfo<unsigned> DiscriminatorInfo;
83   static inline sampleprof::LineLocation getEmptyKey() {
84     return sampleprof::LineLocation(OffsetInfo::getEmptyKey(),
85                                     DiscriminatorInfo::getEmptyKey());
86   }
87   static inline sampleprof::LineLocation getTombstoneKey() {
88     return sampleprof::LineLocation(OffsetInfo::getTombstoneKey(),
89                                     DiscriminatorInfo::getTombstoneKey());
90   }
91   static inline unsigned getHashValue(sampleprof::LineLocation Val) {
92     return DenseMapInfo<std::pair<int, unsigned>>::getHashValue(
93         std::pair<int, unsigned>(Val.LineOffset, Val.Discriminator));
94   }
95   static inline bool isEqual(sampleprof::LineLocation LHS,
96                              sampleprof::LineLocation RHS) {
97     return LHS.LineOffset == RHS.LineOffset &&
98            LHS.Discriminator == RHS.Discriminator;
99   }
100 };
101
102 namespace sampleprof {
103
104 /// \brief Representation of a single sample record.
105 ///
106 /// A sample record is represented by a positive integer value, which
107 /// indicates how frequently was the associated line location executed.
108 ///
109 /// Additionally, if the associated location contains a function call,
110 /// the record will hold a list of all the possible called targets. For
111 /// direct calls, this will be the exact function being invoked. For
112 /// indirect calls (function pointers, virtual table dispatch), this
113 /// will be a list of one or more functions.
114 class SampleRecord {
115 public:
116   typedef StringMap<unsigned> CallTargetMap;
117
118   SampleRecord() : NumSamples(0), CallTargets() {}
119
120   /// \brief Increment the number of samples for this record by \p S.
121   ///
122   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
123   /// around unsigned integers.
124   void addSamples(unsigned S) {
125     if (NumSamples <= std::numeric_limits<unsigned>::max() - S)
126       NumSamples += S;
127     else
128       NumSamples = std::numeric_limits<unsigned>::max();
129   }
130
131   /// \brief Add called function \p F with samples \p S.
132   ///
133   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
134   /// around unsigned integers.
135   void addCalledTarget(StringRef F, unsigned S) {
136     unsigned &TargetSamples = CallTargets[F];
137     if (TargetSamples <= std::numeric_limits<unsigned>::max() - S)
138       TargetSamples += S;
139     else
140       TargetSamples = std::numeric_limits<unsigned>::max();
141   }
142
143   /// \brief Return true if this sample record contains function calls.
144   bool hasCalls() const { return CallTargets.size() > 0; }
145
146   unsigned getSamples() const { return NumSamples; }
147   const CallTargetMap &getCallTargets() const { return CallTargets; }
148
149   /// \brief Merge the samples in \p Other into this record.
150   void merge(const SampleRecord &Other) {
151     addSamples(Other.getSamples());
152     for (const auto &I : Other.getCallTargets())
153       addCalledTarget(I.first(), I.second);
154   }
155
156 private:
157   unsigned NumSamples;
158   CallTargetMap CallTargets;
159 };
160
161 typedef DenseMap<LineLocation, SampleRecord> BodySampleMap;
162
163 /// \brief Representation of the samples collected for a function.
164 ///
165 /// This data structure contains all the collected samples for the body
166 /// of a function. Each sample corresponds to a LineLocation instance
167 /// within the body of the function.
168 class FunctionSamples {
169 public:
170   FunctionSamples() : TotalSamples(0), TotalHeadSamples(0) {}
171   void print(raw_ostream &OS = dbgs());
172   void addTotalSamples(unsigned Num) { TotalSamples += Num; }
173   void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
174   void addBodySamples(int LineOffset, unsigned Discriminator, unsigned Num) {
175     assert(LineOffset >= 0);
176     // When dealing with instruction weights, we use the value
177     // zero to indicate the absence of a sample. If we read an
178     // actual zero from the profile file, use the value 1 to
179     // avoid the confusion later on.
180     if (Num == 0)
181       Num = 1;
182     BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(Num);
183   }
184   void addCalledTargetSamples(int LineOffset, unsigned Discriminator,
185                               std::string FName, unsigned Num) {
186     assert(LineOffset >= 0);
187     BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(FName,
188                                                                          Num);
189   }
190
191   /// \brief Return the sample record at the given location.
192   /// Each location is specified by \p LineOffset and \p Discriminator.
193   SampleRecord &sampleRecordAt(const LineLocation &Loc) {
194     return BodySamples[Loc];
195   }
196
197   /// \brief Return the number of samples collected at the given location.
198   /// Each location is specified by \p LineOffset and \p Discriminator.
199   unsigned samplesAt(int LineOffset, unsigned Discriminator) {
200     return sampleRecordAt(LineLocation(LineOffset, Discriminator)).getSamples();
201   }
202
203   bool empty() const { return BodySamples.empty(); }
204
205   /// \brief Return the total number of samples collected inside the function.
206   unsigned getTotalSamples() const { return TotalSamples; }
207
208   /// \brief Return the total number of samples collected at the head of the
209   /// function.
210   unsigned getHeadSamples() const { return TotalHeadSamples; }
211
212   /// \brief Return all the samples collected in the body of the function.
213   const BodySampleMap &getBodySamples() const { return BodySamples; }
214
215   /// \brief Merge the samples in \p Other into this one.
216   void merge(const FunctionSamples &Other) {
217     addTotalSamples(Other.getTotalSamples());
218     addHeadSamples(Other.getHeadSamples());
219     for (const auto &I : Other.getBodySamples()) {
220       const LineLocation &Loc = I.first;
221       const SampleRecord &Rec = I.second;
222       sampleRecordAt(Loc).merge(Rec);
223     }
224   }
225
226 private:
227   /// \brief Total number of samples collected inside this function.
228   ///
229   /// Samples are cumulative, they include all the samples collected
230   /// inside this function and all its inlined callees.
231   unsigned TotalSamples;
232
233   /// \brief Total number of samples collected at the head of the function.
234   unsigned TotalHeadSamples;
235
236   /// \brief Map instruction locations to collected samples.
237   ///
238   /// Each entry in this map contains the number of samples
239   /// collected at the corresponding line offset. All line locations
240   /// are an offset from the start of the function.
241   BodySampleMap BodySamples;
242 };
243
244 } // End namespace sampleprof
245
246 } // End namespace llvm
247
248 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H_