LLVM  5.0.0
SampleProfWriter.cpp
Go to the documentation of this file.
1 //===- SampleProfWriter.cpp - Write LLVM sample profile data --------------===//
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 implements the class that writes LLVM sample profiles. It
11 // supports two file formats: text and binary. The textual representation
12 // is useful for debugging and testing purposes. The binary representation
13 // is more compact, resulting in smaller file sizes. However, they can
14 // both be used interchangeably.
15 //
16 // See lib/ProfileData/SampleProfReader.cpp for documentation on each of the
17 // supported formats.
18 //
19 //===----------------------------------------------------------------------===//
20 
22 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/LEB128.h"
29 #include <algorithm>
30 #include <cstdint>
31 #include <memory>
32 #include <set>
33 #include <system_error>
34 #include <utility>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace sampleprof;
39 
40 std::error_code
42  if (std::error_code EC = writeHeader(ProfileMap))
43  return EC;
44 
45  // Sort the ProfileMap by total samples.
46  typedef std::pair<StringRef, const FunctionSamples *> NameFunctionSamples;
47  std::vector<NameFunctionSamples> V;
48  for (const auto &I : ProfileMap)
49  V.push_back(std::make_pair(I.getKey(), &I.second));
50 
51  std::stable_sort(
52  V.begin(), V.end(),
53  [](const NameFunctionSamples &A, const NameFunctionSamples &B) {
54  if (A.second->getTotalSamples() == B.second->getTotalSamples())
55  return A.first > B.first;
56  return A.second->getTotalSamples() > B.second->getTotalSamples();
57  });
58 
59  for (const auto &I : V) {
60  if (std::error_code EC = write(*I.second))
61  return EC;
62  }
64 }
65 
66 /// \brief Write samples to a text file.
67 ///
68 /// Note: it may be tempting to implement this in terms of
69 /// FunctionSamples::print(). Please don't. The dump functionality is intended
70 /// for debugging and has no specified form.
71 ///
72 /// The format used here is more structured and deliberate because
73 /// it needs to be parsed by the SampleProfileReaderText class.
75  auto &OS = *OutputStream;
76  OS << S.getName() << ":" << S.getTotalSamples();
77  if (Indent == 0)
78  OS << ":" << S.getHeadSamples();
79  OS << "\n";
80 
82  for (const auto &I : SortedSamples.get()) {
83  LineLocation Loc = I->first;
84  const SampleRecord &Sample = I->second;
85  OS.indent(Indent + 1);
86  if (Loc.Discriminator == 0)
87  OS << Loc.LineOffset << ": ";
88  else
89  OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
90 
91  OS << Sample.getSamples();
92 
93  for (const auto &J : Sample.getCallTargets())
94  OS << " " << J.first() << ":" << J.second;
95  OS << "\n";
96  }
97 
99  S.getCallsiteSamples());
100  Indent += 1;
101  for (const auto &I : SortedCallsiteSamples.get())
102  for (const auto &FS : I->second) {
103  LineLocation Loc = I->first;
104  const FunctionSamples &CalleeSamples = FS.second;
105  OS.indent(Indent);
106  if (Loc.Discriminator == 0)
107  OS << Loc.LineOffset << ": ";
108  else
109  OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
110  if (std::error_code EC = write(CalleeSamples))
111  return EC;
112  }
113  Indent -= 1;
114 
116 }
117 
119  const auto &ret = NameTable.find(FName);
120  if (ret == NameTable.end())
122  encodeULEB128(ret->second, *OutputStream);
124 }
125 
126 void SampleProfileWriterBinary::addName(StringRef FName) {
127  NameTable.insert(std::make_pair(FName, 0));
128 }
129 
130 void SampleProfileWriterBinary::addNames(const FunctionSamples &S) {
131  // Add all the names in indirect call targets.
132  for (const auto &I : S.getBodySamples()) {
133  const SampleRecord &Sample = I.second;
134  for (const auto &J : Sample.getCallTargets())
135  addName(J.first());
136  }
137 
138  // Recursively add all the names for inlined callsites.
139  for (const auto &J : S.getCallsiteSamples())
140  for (const auto &FS : J.second) {
141  const FunctionSamples &CalleeSamples = FS.second;
142  addName(CalleeSamples.getName());
143  addNames(CalleeSamples);
144  }
145 }
146 
148  const StringMap<FunctionSamples> &ProfileMap) {
149  auto &OS = *OutputStream;
150 
151  // Write file magic identifier.
152  encodeULEB128(SPMagic(), OS);
153  encodeULEB128(SPVersion(), OS);
154 
155  computeSummary(ProfileMap);
156  if (auto EC = writeSummary())
157  return EC;
158 
159  // Generate the name table for all the functions referenced in the profile.
160  for (const auto &I : ProfileMap) {
161  addName(I.first());
162  addNames(I.second);
163  }
164 
165  // Sort the names to make NameTable is deterministic.
166  std::set<StringRef> V;
167  for (const auto &I : NameTable)
168  V.insert(I.first);
169  int i = 0;
170  for (const StringRef &N : V)
171  NameTable[N] = i++;
172 
173  // Write out the name table.
174  encodeULEB128(NameTable.size(), OS);
175  for (auto N : V) {
176  OS << N;
177  encodeULEB128(0, OS);
178  }
180 }
181 
183  auto &OS = *OutputStream;
184  encodeULEB128(Summary->getTotalCount(), OS);
185  encodeULEB128(Summary->getMaxCount(), OS);
186  encodeULEB128(Summary->getMaxFunctionCount(), OS);
187  encodeULEB128(Summary->getNumCounts(), OS);
188  encodeULEB128(Summary->getNumFunctions(), OS);
189  std::vector<ProfileSummaryEntry> &Entries = Summary->getDetailedSummary();
190  encodeULEB128(Entries.size(), OS);
191  for (auto Entry : Entries) {
192  encodeULEB128(Entry.Cutoff, OS);
193  encodeULEB128(Entry.MinCount, OS);
194  encodeULEB128(Entry.NumCounts, OS);
195  }
197 }
199  auto &OS = *OutputStream;
200 
201  if (std::error_code EC = writeNameIdx(S.getName()))
202  return EC;
203 
205 
206  // Emit all the body samples.
207  encodeULEB128(S.getBodySamples().size(), OS);
208  for (const auto &I : S.getBodySamples()) {
209  LineLocation Loc = I.first;
210  const SampleRecord &Sample = I.second;
211  encodeULEB128(Loc.LineOffset, OS);
212  encodeULEB128(Loc.Discriminator, OS);
213  encodeULEB128(Sample.getSamples(), OS);
214  encodeULEB128(Sample.getCallTargets().size(), OS);
215  for (const auto &J : Sample.getCallTargets()) {
216  StringRef Callee = J.first();
217  uint64_t CalleeSamples = J.second;
218  if (std::error_code EC = writeNameIdx(Callee))
219  return EC;
220  encodeULEB128(CalleeSamples, OS);
221  }
222  }
223 
224  // Recursively emit all the callsite samples.
225  encodeULEB128(S.getCallsiteSamples().size(), OS);
226  for (const auto &J : S.getCallsiteSamples())
227  for (const auto &FS : J.second) {
228  LineLocation Loc = J.first;
229  const FunctionSamples &CalleeSamples = FS.second;
230  encodeULEB128(Loc.LineOffset, OS);
231  encodeULEB128(Loc.Discriminator, OS);
232  if (std::error_code EC = writeBody(CalleeSamples))
233  return EC;
234  }
235 
237 }
238 
239 /// \brief Write samples of a top-level function to a binary file.
240 ///
241 /// \returns true if the samples were written successfully, false otherwise.
244  return writeBody(S);
245 }
246 
247 /// \brief Create a sample profile file writer based on the specified format.
248 ///
249 /// \param Filename The file to create.
250 ///
251 /// \param Writer The writer to instantiate according to the specified format.
252 ///
253 /// \param Format Encoding format for the profile file.
254 ///
255 /// \returns an error code indicating the status of the created writer.
258  std::error_code EC;
259  std::unique_ptr<raw_ostream> OS;
260  if (Format == SPF_Binary)
261  OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::F_None));
262  else
263  OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::F_Text));
264  if (EC)
265  return EC;
266 
267  return create(OS, Format);
268 }
269 
270 /// \brief Create a sample profile stream writer based on the specified format.
271 ///
272 /// \param OS The output stream to store the profile data to.
273 ///
274 /// \param Writer The writer to instantiate according to the specified format.
275 ///
276 /// \param Format Encoding format for the profile file.
277 ///
278 /// \returns an error code indicating the status of the created writer.
280 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
281  SampleProfileFormat Format) {
282  std::error_code EC;
283  std::unique_ptr<SampleProfileWriter> Writer;
284 
285  if (Format == SPF_Binary)
286  Writer.reset(new SampleProfileWriterBinary(OS));
287  else if (Format == SPF_Text)
288  Writer.reset(new SampleProfileWriterText(OS));
289  else if (Format == SPF_GCC)
291  else
293 
294  if (EC)
295  return EC;
296 
297  return std::move(Writer);
298 }
299 
301  const StringMap<FunctionSamples> &ProfileMap) {
303  for (const auto &I : ProfileMap) {
304  const FunctionSamples &Profile = I.second;
305  Builder.addRecord(Profile);
306  }
307  Summary = Builder.getSummary();
308 }
Represents either an error or a value T.
Definition: ErrorOr.h:69
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
Definition: SampleProf.h:304
std::unique_ptr< raw_ostream > OutputStream
Output stream where to emit the profile to.
static const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Definition: ProfileCommon.h:65
const StringRef & getName() const
Return the function name.
Definition: SampleProf.h:351
const CallTargetMap & getCallTargets() const
Definition: SampleProf.h:163
std::error_code writeHeader(const StringMap< FunctionSamples > &ProfileMap) override
Write a file header for the profile file.
Representation of the samples collected for a function.
Definition: SampleProf.h:196
std::error_code writeNameIdx(StringRef FName)
uint64_t getHeadSamples() const
Return the total number of samples collected at the head of the function.
Definition: SampleProf.h:301
Representation of a single sample record.
Definition: SampleProf.h:126
static uint64_t SPVersion()
Definition: SampleProf.h:88
Sort a LocationT->SampleT map by LocationT.
Definition: SampleProf.h:400
std::unique_ptr< ProfileSummary > Summary
Profile summary.
#define A
Definition: LargeTest.cpp:12
unsigned size() const
Definition: StringMap.h:111
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition: SampleProf.h:297
Sample-based profile writer (binary format).
std::error_code write(const FunctionSamples &S) override
Write samples of a top-level function to a binary file.
virtual std::error_code write(const FunctionSamples &S)=0
Write sample profiles in S.
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
Definition: SampleProf.h:307
#define B
Definition: LargeTest.cpp:24
uint64_t getSamples() const
Definition: SampleProf.h:162
static ErrorOr< std::unique_ptr< SampleProfileWriter > > create(StringRef Filename, SampleProfileFormat Format)
Profile writer factory.
void addRecord(const sampleprof::FunctionSamples &FS)
const size_t N
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
std::error_code writeBody(const FunctionSamples &S)
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:708
std::unique_ptr< ProfileSummary > getSummary()
static uint64_t SPMagic()
Definition: SampleProf.h:81
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:357
Represents the relative location of an instruction.
Definition: SampleProf.h:99
#define I(x, y, z)
Definition: MD5.cpp:58
Provides ErrorOr<T> smart pointer.
virtual std::error_code writeHeader(const StringMap< FunctionSamples > &ProfileMap)=0
Write a file header for the profile file.
void encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned Padding=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:73
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void computeSummary(const StringMap< FunctionSamples > &ProfileMap)
Compute summary for this profile.
std::error_code write(const FunctionSamples &S) override
Write samples to a text file.
Sample-based profile writer (text format).