blob: e71d0bae07bdbc367dfdc99f5cb3cf12f85b869d [file] [log] [blame]
Diego Novillode1ab262014-09-09 12:40:50 +00001//===- SampleProfReader.cpp - Read 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 reads LLVM sample profiles. It
Diego Novillobb5605c2015-10-14 18:36:30 +000011// supports three file formats: text, binary and gcov.
Diego Novillode1ab262014-09-09 12:40:50 +000012//
Diego Novillobb5605c2015-10-14 18:36:30 +000013// The textual representation is useful for debugging and testing purposes. The
14// binary representation is more compact, resulting in smaller file sizes.
Diego Novillode1ab262014-09-09 12:40:50 +000015//
Diego Novillobb5605c2015-10-14 18:36:30 +000016// The gcov encoding is the one generated by GCC's AutoFDO profile creation
17// tool (https://github.com/google/autofdo)
Diego Novillode1ab262014-09-09 12:40:50 +000018//
Diego Novillobb5605c2015-10-14 18:36:30 +000019// All three encodings can be used interchangeably as an input sample profile.
Diego Novillode1ab262014-09-09 12:40:50 +000020//
Diego Novillode1ab262014-09-09 12:40:50 +000021//===----------------------------------------------------------------------===//
22
23#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillob93483d2015-10-16 18:54:35 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/SmallVector.h"
Diego Novillode1ab262014-09-09 12:40:50 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorOr.h"
Diego Novilloc572e922014-10-30 18:00:06 +000028#include "llvm/Support/LEB128.h"
Diego Novillode1ab262014-09-09 12:40:50 +000029#include "llvm/Support/LineIterator.h"
Diego Novilloc572e922014-10-30 18:00:06 +000030#include "llvm/Support/MemoryBuffer.h"
Diego Novillode1ab262014-09-09 12:40:50 +000031
Diego Novilloc572e922014-10-30 18:00:06 +000032using namespace llvm::sampleprof;
Diego Novillode1ab262014-09-09 12:40:50 +000033using namespace llvm;
34
Diego Novillod5336ae2014-11-01 00:56:55 +000035/// \brief Dump the function profile for \p FName.
Diego Novillode1ab262014-09-09 12:40:50 +000036///
Diego Novillode1ab262014-09-09 12:40:50 +000037/// \param FName Name of the function to print.
Diego Novillod5336ae2014-11-01 00:56:55 +000038/// \param OS Stream to emit the output to.
39void SampleProfileReader::dumpFunctionProfile(StringRef FName,
40 raw_ostream &OS) {
Diego Novillo8e415a82015-11-13 20:24:28 +000041 OS << "Function: " << FName << ": " << Profiles[FName];
Diego Novillode1ab262014-09-09 12:40:50 +000042}
43
Diego Novillod5336ae2014-11-01 00:56:55 +000044/// \brief Dump all the function profiles found on stream \p OS.
45void SampleProfileReader::dump(raw_ostream &OS) {
46 for (const auto &I : Profiles)
47 dumpFunctionProfile(I.getKey(), OS);
Diego Novillode1ab262014-09-09 12:40:50 +000048}
49
Dehao Chen67226882015-09-30 00:42:46 +000050/// \brief Parse \p Input as function head.
51///
52/// Parse one line of \p Input, and update function name in \p FName,
53/// function's total sample count in \p NumSamples, function's entry
54/// count in \p NumHeadSamples.
55///
56/// \returns true if parsing is successful.
57static bool ParseHead(const StringRef &Input, StringRef &FName,
Diego Novillo38be3332015-10-15 16:36:21 +000058 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
Dehao Chen67226882015-09-30 00:42:46 +000059 if (Input[0] == ' ')
60 return false;
61 size_t n2 = Input.rfind(':');
62 size_t n1 = Input.rfind(':', n2 - 1);
63 FName = Input.substr(0, n1);
64 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
65 return false;
66 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
67 return false;
68 return true;
69}
70
Dehao Chen10042412015-10-21 01:22:27 +000071
72/// \brief Returns true if line offset \p L is legal (only has 16 bits).
73static bool isOffsetLegal(unsigned L) {
74 return (L & 0xffff) == L;
75}
76
Dehao Chen67226882015-09-30 00:42:46 +000077/// \brief Parse \p Input as line sample.
78///
79/// \param Input input line.
80/// \param IsCallsite true if the line represents an inlined callsite.
81/// \param Depth the depth of the inline stack.
82/// \param NumSamples total samples of the line/inlined callsite.
83/// \param LineOffset line offset to the start of the function.
84/// \param Discriminator discriminator of the line.
85/// \param TargetCountMap map from indirect call target to count.
86///
87/// returns true if parsing is successful.
Diego Novillo38be3332015-10-15 16:36:21 +000088static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
89 uint64_t &NumSamples, uint32_t &LineOffset,
90 uint32_t &Discriminator, StringRef &CalleeName,
91 DenseMap<StringRef, uint64_t> &TargetCountMap) {
Dehao Chen67226882015-09-30 00:42:46 +000092 for (Depth = 0; Input[Depth] == ' '; Depth++)
93 ;
94 if (Depth == 0)
95 return false;
96
97 size_t n1 = Input.find(':');
98 StringRef Loc = Input.substr(Depth, n1 - Depth);
99 size_t n2 = Loc.find('.');
100 if (n2 == StringRef::npos) {
Dehao Chen10042412015-10-21 01:22:27 +0000101 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
Dehao Chen67226882015-09-30 00:42:46 +0000102 return false;
103 Discriminator = 0;
104 } else {
105 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
106 return false;
107 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
108 return false;
109 }
110
111 StringRef Rest = Input.substr(n1 + 2);
112 if (Rest[0] >= '0' && Rest[0] <= '9') {
113 IsCallsite = false;
114 size_t n3 = Rest.find(' ');
115 if (n3 == StringRef::npos) {
116 if (Rest.getAsInteger(10, NumSamples))
117 return false;
118 } else {
119 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
120 return false;
121 }
122 while (n3 != StringRef::npos) {
123 n3 += Rest.substr(n3).find_first_not_of(' ');
124 Rest = Rest.substr(n3);
125 n3 = Rest.find(' ');
126 StringRef pair = Rest;
127 if (n3 != StringRef::npos) {
128 pair = Rest.substr(0, n3);
129 }
Diego Novillo38be3332015-10-15 16:36:21 +0000130 size_t n4 = pair.find(':');
131 uint64_t count;
Dehao Chen67226882015-09-30 00:42:46 +0000132 if (pair.substr(n4 + 1).getAsInteger(10, count))
133 return false;
134 TargetCountMap[pair.substr(0, n4)] = count;
135 }
136 } else {
137 IsCallsite = true;
Diego Novillo38be3332015-10-15 16:36:21 +0000138 size_t n3 = Rest.find_last_of(':');
Dehao Chen67226882015-09-30 00:42:46 +0000139 CalleeName = Rest.substr(0, n3);
140 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
141 return false;
142 }
143 return true;
144}
145
Diego Novillode1ab262014-09-09 12:40:50 +0000146/// \brief Load samples from a text file.
147///
148/// See the documentation at the top of the file for an explanation of
149/// the expected format.
150///
151/// \returns true if the file was loaded successfully, false otherwise.
Diego Novilloc572e922014-10-30 18:00:06 +0000152std::error_code SampleProfileReaderText::read() {
153 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
Diego Novillode1ab262014-09-09 12:40:50 +0000154
Diego Novilloaae1ed82015-10-08 19:40:37 +0000155 InlineCallStack InlineStack;
Dehao Chen67226882015-09-30 00:42:46 +0000156
157 for (; !LineIt.is_at_eof(); ++LineIt) {
158 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
159 continue;
Diego Novillode1ab262014-09-09 12:40:50 +0000160 // Read the header of each function.
161 //
162 // Note that for function identifiers we are actually expecting
163 // mangled names, but we may not always get them. This happens when
164 // the compiler decides not to emit the function (e.g., it was inlined
165 // and removed). In this case, the binary will not have the linkage
166 // name for the function, so the profiler will emit the function's
167 // unmangled name, which may contain characters like ':' and '>' in its
168 // name (member functions, templates, etc).
169 //
170 // The only requirement we place on the identifier, then, is that it
171 // should not begin with a number.
Dehao Chen67226882015-09-30 00:42:46 +0000172 if ((*LineIt)[0] != ' ') {
Diego Novillo38be3332015-10-15 16:36:21 +0000173 uint64_t NumSamples, NumHeadSamples;
Dehao Chen67226882015-09-30 00:42:46 +0000174 StringRef FName;
175 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
176 reportError(LineIt.line_number(),
177 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
178 return sampleprof_error::malformed;
179 }
180 Profiles[FName] = FunctionSamples();
181 FunctionSamples &FProfile = Profiles[FName];
182 FProfile.addTotalSamples(NumSamples);
183 FProfile.addHeadSamples(NumHeadSamples);
184 InlineStack.clear();
185 InlineStack.push_back(&FProfile);
186 } else {
Diego Novillo38be3332015-10-15 16:36:21 +0000187 uint64_t NumSamples;
Dehao Chen67226882015-09-30 00:42:46 +0000188 StringRef FName;
Diego Novillo38be3332015-10-15 16:36:21 +0000189 DenseMap<StringRef, uint64_t> TargetCountMap;
Dehao Chen67226882015-09-30 00:42:46 +0000190 bool IsCallsite;
Diego Novillo38be3332015-10-15 16:36:21 +0000191 uint32_t Depth, LineOffset, Discriminator;
Dehao Chen67226882015-09-30 00:42:46 +0000192 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
193 Discriminator, FName, TargetCountMap)) {
Diego Novillo3376a782015-09-17 00:17:24 +0000194 reportError(LineIt.line_number(),
195 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
196 *LineIt);
Diego Novilloc572e922014-10-30 18:00:06 +0000197 return sampleprof_error::malformed;
Diego Novillode1ab262014-09-09 12:40:50 +0000198 }
Dehao Chen67226882015-09-30 00:42:46 +0000199 if (IsCallsite) {
200 while (InlineStack.size() > Depth) {
201 InlineStack.pop_back();
Diego Novilloc572e922014-10-30 18:00:06 +0000202 }
Dehao Chen67226882015-09-30 00:42:46 +0000203 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
204 CallsiteLocation(LineOffset, Discriminator, FName));
205 FSamples.addTotalSamples(NumSamples);
206 InlineStack.push_back(&FSamples);
207 } else {
208 while (InlineStack.size() > Depth) {
209 InlineStack.pop_back();
210 }
211 FunctionSamples &FProfile = *InlineStack.back();
212 for (const auto &name_count : TargetCountMap) {
213 FProfile.addCalledTargetSamples(LineOffset, Discriminator,
214 name_count.first, name_count.second);
215 }
216 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
Diego Novilloc572e922014-10-30 18:00:06 +0000217 }
Diego Novillode1ab262014-09-09 12:40:50 +0000218 }
219 }
220
Diego Novilloc572e922014-10-30 18:00:06 +0000221 return sampleprof_error::success;
Diego Novillode1ab262014-09-09 12:40:50 +0000222}
223
Nathan Slingerland4f823662015-11-13 03:47:58 +0000224bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
225 bool result = false;
226
227 // Check that the first non-comment line is a valid function header.
228 line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
229 if (!LineIt.is_at_eof()) {
230 if ((*LineIt)[0] != ' ') {
231 uint64_t NumSamples, NumHeadSamples;
232 StringRef FName;
233 result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
234 }
235 }
236
237 return result;
238}
239
Diego Novillod5336ae2014-11-01 00:56:55 +0000240template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
Diego Novilloc572e922014-10-30 18:00:06 +0000241 unsigned NumBytesRead = 0;
242 std::error_code EC;
243 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
244
245 if (Val > std::numeric_limits<T>::max())
246 EC = sampleprof_error::malformed;
247 else if (Data + NumBytesRead > End)
248 EC = sampleprof_error::truncated;
249 else
250 EC = sampleprof_error::success;
251
252 if (EC) {
Diego Novillo3376a782015-09-17 00:17:24 +0000253 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000254 return EC;
255 }
256
257 Data += NumBytesRead;
258 return static_cast<T>(Val);
259}
260
261ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
262 std::error_code EC;
263 StringRef Str(reinterpret_cast<const char *>(Data));
264 if (Data + Str.size() + 1 > End) {
265 EC = sampleprof_error::truncated;
Diego Novillo3376a782015-09-17 00:17:24 +0000266 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000267 return EC;
268 }
269
270 Data += Str.size() + 1;
271 return Str;
272}
273
Diego Novillo760c5a82015-10-13 22:48:46 +0000274ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
275 std::error_code EC;
Diego Novillo38be3332015-10-15 16:36:21 +0000276 auto Idx = readNumber<uint32_t>();
Diego Novillo760c5a82015-10-13 22:48:46 +0000277 if (std::error_code EC = Idx.getError())
278 return EC;
279 if (*Idx >= NameTable.size())
280 return sampleprof_error::truncated_name_table;
281 return NameTable[*Idx];
282}
283
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000284std::error_code
285SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
Diego Novillob93483d2015-10-16 18:54:35 +0000286 auto NumSamples = readNumber<uint64_t>();
287 if (std::error_code EC = NumSamples.getError())
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000288 return EC;
Diego Novillob93483d2015-10-16 18:54:35 +0000289 FProfile.addTotalSamples(*NumSamples);
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000290
291 // Read the samples in the body.
Diego Novillo38be3332015-10-15 16:36:21 +0000292 auto NumRecords = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000293 if (std::error_code EC = NumRecords.getError())
294 return EC;
295
Diego Novillo38be3332015-10-15 16:36:21 +0000296 for (uint32_t I = 0; I < *NumRecords; ++I) {
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000297 auto LineOffset = readNumber<uint64_t>();
298 if (std::error_code EC = LineOffset.getError())
299 return EC;
300
Dehao Chen10042412015-10-21 01:22:27 +0000301 if (!isOffsetLegal(*LineOffset)) {
302 return std::error_code();
303 }
304
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000305 auto Discriminator = readNumber<uint64_t>();
306 if (std::error_code EC = Discriminator.getError())
307 return EC;
308
309 auto NumSamples = readNumber<uint64_t>();
310 if (std::error_code EC = NumSamples.getError())
311 return EC;
312
Diego Novillo38be3332015-10-15 16:36:21 +0000313 auto NumCalls = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000314 if (std::error_code EC = NumCalls.getError())
315 return EC;
316
Diego Novillo38be3332015-10-15 16:36:21 +0000317 for (uint32_t J = 0; J < *NumCalls; ++J) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000318 auto CalledFunction(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000319 if (std::error_code EC = CalledFunction.getError())
320 return EC;
321
322 auto CalledFunctionSamples = readNumber<uint64_t>();
323 if (std::error_code EC = CalledFunctionSamples.getError())
324 return EC;
325
326 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
327 *CalledFunction, *CalledFunctionSamples);
328 }
329
330 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
331 }
332
333 // Read all the samples for inlined function calls.
Diego Novillo38be3332015-10-15 16:36:21 +0000334 auto NumCallsites = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000335 if (std::error_code EC = NumCallsites.getError())
336 return EC;
337
Diego Novillo38be3332015-10-15 16:36:21 +0000338 for (uint32_t J = 0; J < *NumCallsites; ++J) {
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000339 auto LineOffset = readNumber<uint64_t>();
340 if (std::error_code EC = LineOffset.getError())
341 return EC;
342
343 auto Discriminator = readNumber<uint64_t>();
344 if (std::error_code EC = Discriminator.getError())
345 return EC;
346
Diego Novillo760c5a82015-10-13 22:48:46 +0000347 auto FName(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000348 if (std::error_code EC = FName.getError())
349 return EC;
350
351 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
352 CallsiteLocation(*LineOffset, *Discriminator, *FName));
353 if (std::error_code EC = readProfile(CalleeProfile))
354 return EC;
355 }
356
357 return sampleprof_error::success;
358}
359
Diego Novilloc572e922014-10-30 18:00:06 +0000360std::error_code SampleProfileReaderBinary::read() {
361 while (!at_eof()) {
Diego Novillob93483d2015-10-16 18:54:35 +0000362 auto NumHeadSamples = readNumber<uint64_t>();
363 if (std::error_code EC = NumHeadSamples.getError())
364 return EC;
365
Diego Novillo760c5a82015-10-13 22:48:46 +0000366 auto FName(readStringFromTable());
Diego Novilloc572e922014-10-30 18:00:06 +0000367 if (std::error_code EC = FName.getError())
368 return EC;
369
370 Profiles[*FName] = FunctionSamples();
371 FunctionSamples &FProfile = Profiles[*FName];
372
Diego Novillob93483d2015-10-16 18:54:35 +0000373 FProfile.addHeadSamples(*NumHeadSamples);
374
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000375 if (std::error_code EC = readProfile(FProfile))
Diego Novilloc572e922014-10-30 18:00:06 +0000376 return EC;
Diego Novilloc572e922014-10-30 18:00:06 +0000377 }
378
379 return sampleprof_error::success;
380}
381
382std::error_code SampleProfileReaderBinary::readHeader() {
383 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
384 End = Data + Buffer->getBufferSize();
385
386 // Read and check the magic identifier.
387 auto Magic = readNumber<uint64_t>();
388 if (std::error_code EC = Magic.getError())
389 return EC;
390 else if (*Magic != SPMagic())
391 return sampleprof_error::bad_magic;
392
393 // Read the version number.
394 auto Version = readNumber<uint64_t>();
395 if (std::error_code EC = Version.getError())
396 return EC;
397 else if (*Version != SPVersion())
398 return sampleprof_error::unsupported_version;
399
Diego Novillo760c5a82015-10-13 22:48:46 +0000400 // Read the name table.
Diego Novillo38be3332015-10-15 16:36:21 +0000401 auto Size = readNumber<uint32_t>();
Diego Novillo760c5a82015-10-13 22:48:46 +0000402 if (std::error_code EC = Size.getError())
403 return EC;
404 NameTable.reserve(*Size);
Diego Novillo38be3332015-10-15 16:36:21 +0000405 for (uint32_t I = 0; I < *Size; ++I) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000406 auto Name(readString());
407 if (std::error_code EC = Name.getError())
408 return EC;
409 NameTable.push_back(*Name);
410 }
411
Diego Novilloc572e922014-10-30 18:00:06 +0000412 return sampleprof_error::success;
413}
414
415bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
416 const uint8_t *Data =
417 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
418 uint64_t Magic = decodeULEB128(Data);
419 return Magic == SPMagic();
420}
421
Diego Novillo3376a782015-09-17 00:17:24 +0000422std::error_code SampleProfileReaderGCC::skipNextWord() {
423 uint32_t dummy;
424 if (!GcovBuffer.readInt(dummy))
425 return sampleprof_error::truncated;
426 return sampleprof_error::success;
427}
428
429template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
430 if (sizeof(T) <= sizeof(uint32_t)) {
431 uint32_t Val;
432 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
433 return static_cast<T>(Val);
434 } else if (sizeof(T) <= sizeof(uint64_t)) {
435 uint64_t Val;
436 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
437 return static_cast<T>(Val);
438 }
439
440 std::error_code EC = sampleprof_error::malformed;
441 reportError(0, EC.message());
442 return EC;
443}
444
445ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
446 StringRef Str;
447 if (!GcovBuffer.readString(Str))
448 return sampleprof_error::truncated;
449 return Str;
450}
451
452std::error_code SampleProfileReaderGCC::readHeader() {
453 // Read the magic identifier.
454 if (!GcovBuffer.readGCDAFormat())
455 return sampleprof_error::unrecognized_format;
456
457 // Read the version number. Note - the GCC reader does not validate this
458 // version, but the profile creator generates v704.
459 GCOV::GCOVVersion version;
460 if (!GcovBuffer.readGCOVVersion(version))
461 return sampleprof_error::unrecognized_format;
462
463 if (version != GCOV::V704)
464 return sampleprof_error::unsupported_version;
465
466 // Skip the empty integer.
467 if (std::error_code EC = skipNextWord())
468 return EC;
469
470 return sampleprof_error::success;
471}
472
473std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
474 uint32_t Tag;
475 if (!GcovBuffer.readInt(Tag))
476 return sampleprof_error::truncated;
477
478 if (Tag != Expected)
479 return sampleprof_error::malformed;
480
481 if (std::error_code EC = skipNextWord())
482 return EC;
483
484 return sampleprof_error::success;
485}
486
487std::error_code SampleProfileReaderGCC::readNameTable() {
488 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
489 return EC;
490
491 uint32_t Size;
492 if (!GcovBuffer.readInt(Size))
493 return sampleprof_error::truncated;
494
495 for (uint32_t I = 0; I < Size; ++I) {
496 StringRef Str;
497 if (!GcovBuffer.readString(Str))
498 return sampleprof_error::truncated;
499 Names.push_back(Str);
500 }
501
502 return sampleprof_error::success;
503}
504
505std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
506 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
507 return EC;
508
509 uint32_t NumFunctions;
510 if (!GcovBuffer.readInt(NumFunctions))
511 return sampleprof_error::truncated;
512
Diego Novilloaae1ed82015-10-08 19:40:37 +0000513 InlineCallStack Stack;
Diego Novillo3376a782015-09-17 00:17:24 +0000514 for (uint32_t I = 0; I < NumFunctions; ++I)
Diego Novilloaae1ed82015-10-08 19:40:37 +0000515 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
Diego Novillo3376a782015-09-17 00:17:24 +0000516 return EC;
517
518 return sampleprof_error::success;
519}
520
Diego Novilloaae1ed82015-10-08 19:40:37 +0000521std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
522 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
Diego Novillo3376a782015-09-17 00:17:24 +0000523 uint64_t HeadCount = 0;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000524 if (InlineStack.size() == 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000525 if (!GcovBuffer.readInt64(HeadCount))
526 return sampleprof_error::truncated;
527
528 uint32_t NameIdx;
529 if (!GcovBuffer.readInt(NameIdx))
530 return sampleprof_error::truncated;
531
532 StringRef Name(Names[NameIdx]);
533
534 uint32_t NumPosCounts;
535 if (!GcovBuffer.readInt(NumPosCounts))
536 return sampleprof_error::truncated;
537
Diego Novilloaae1ed82015-10-08 19:40:37 +0000538 uint32_t NumCallsites;
539 if (!GcovBuffer.readInt(NumCallsites))
Diego Novillo3376a782015-09-17 00:17:24 +0000540 return sampleprof_error::truncated;
541
Diego Novilloaae1ed82015-10-08 19:40:37 +0000542 FunctionSamples *FProfile = nullptr;
543 if (InlineStack.size() == 0) {
544 // If this is a top function that we have already processed, do not
545 // update its profile again. This happens in the presence of
546 // function aliases. Since these aliases share the same function
547 // body, there will be identical replicated profiles for the
548 // original function. In this case, we simply not bother updating
549 // the profile of the original function.
550 FProfile = &Profiles[Name];
551 FProfile->addHeadSamples(HeadCount);
552 if (FProfile->getTotalSamples() > 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000553 Update = false;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000554 } else {
555 // Otherwise, we are reading an inlined instance. The top of the
556 // inline stack contains the profile of the caller. Insert this
557 // callee in the caller's CallsiteMap.
558 FunctionSamples *CallerProfile = InlineStack.front();
559 uint32_t LineOffset = Offset >> 16;
560 uint32_t Discriminator = Offset & 0xffff;
561 FProfile = &CallerProfile->functionSamplesAt(
562 CallsiteLocation(LineOffset, Discriminator, Name));
Diego Novillo3376a782015-09-17 00:17:24 +0000563 }
564
565 for (uint32_t I = 0; I < NumPosCounts; ++I) {
566 uint32_t Offset;
567 if (!GcovBuffer.readInt(Offset))
568 return sampleprof_error::truncated;
569
570 uint32_t NumTargets;
571 if (!GcovBuffer.readInt(NumTargets))
572 return sampleprof_error::truncated;
573
574 uint64_t Count;
575 if (!GcovBuffer.readInt64(Count))
576 return sampleprof_error::truncated;
577
Diego Novilloaae1ed82015-10-08 19:40:37 +0000578 // The line location is encoded in the offset as:
579 // high 16 bits: line offset to the start of the function.
580 // low 16 bits: discriminator.
581 uint32_t LineOffset = Offset >> 16;
582 uint32_t Discriminator = Offset & 0xffff;
Diego Novillo3376a782015-09-17 00:17:24 +0000583
Diego Novilloaae1ed82015-10-08 19:40:37 +0000584 InlineCallStack NewStack;
585 NewStack.push_back(FProfile);
586 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
587 if (Update) {
588 // Walk up the inline stack, adding the samples on this line to
589 // the total sample count of the callers in the chain.
590 for (auto CallerProfile : NewStack)
591 CallerProfile->addTotalSamples(Count);
592
593 // Update the body samples for the current profile.
594 FProfile->addBodySamples(LineOffset, Discriminator, Count);
595 }
596
597 // Process the list of functions called at an indirect call site.
598 // These are all the targets that a function pointer (or virtual
599 // function) resolved at runtime.
Diego Novillo3376a782015-09-17 00:17:24 +0000600 for (uint32_t J = 0; J < NumTargets; J++) {
601 uint32_t HistVal;
602 if (!GcovBuffer.readInt(HistVal))
603 return sampleprof_error::truncated;
604
605 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
606 return sampleprof_error::malformed;
607
608 uint64_t TargetIdx;
609 if (!GcovBuffer.readInt64(TargetIdx))
610 return sampleprof_error::truncated;
611 StringRef TargetName(Names[TargetIdx]);
612
613 uint64_t TargetCount;
614 if (!GcovBuffer.readInt64(TargetCount))
615 return sampleprof_error::truncated;
616
617 if (Update) {
618 FunctionSamples &TargetProfile = Profiles[TargetName];
Diego Novilloaae1ed82015-10-08 19:40:37 +0000619 TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
620 TargetName, TargetCount);
Diego Novillo3376a782015-09-17 00:17:24 +0000621 }
622 }
623 }
624
Diego Novilloaae1ed82015-10-08 19:40:37 +0000625 // Process all the inlined callers into the current function. These
626 // are all the callsites that were inlined into this function.
627 for (uint32_t I = 0; I < NumCallsites; I++) {
Diego Novillo3376a782015-09-17 00:17:24 +0000628 // The offset is encoded as:
629 // high 16 bits: line offset to the start of the function.
630 // low 16 bits: discriminator.
631 uint32_t Offset;
632 if (!GcovBuffer.readInt(Offset))
633 return sampleprof_error::truncated;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000634 InlineCallStack NewStack;
635 NewStack.push_back(FProfile);
636 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
637 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
Diego Novillo3376a782015-09-17 00:17:24 +0000638 return EC;
639 }
640
641 return sampleprof_error::success;
642}
643
Diego Novillo3376a782015-09-17 00:17:24 +0000644/// \brief Read a GCC AutoFDO profile.
645///
646/// This format is generated by the Linux Perf conversion tool at
647/// https://github.com/google/autofdo.
648std::error_code SampleProfileReaderGCC::read() {
649 // Read the string table.
650 if (std::error_code EC = readNameTable())
651 return EC;
652
653 // Read the source profile.
654 if (std::error_code EC = readFunctionProfiles())
655 return EC;
656
Diego Novillo3376a782015-09-17 00:17:24 +0000657 return sampleprof_error::success;
658}
659
660bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
661 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
662 return Magic == "adcg*704";
663}
664
Diego Novilloc572e922014-10-30 18:00:06 +0000665/// \brief Prepare a memory buffer for the contents of \p Filename.
Diego Novillode1ab262014-09-09 12:40:50 +0000666///
Diego Novilloc572e922014-10-30 18:00:06 +0000667/// \returns an error code indicating the status of the buffer.
Diego Novillofcd55602014-11-03 00:51:45 +0000668static ErrorOr<std::unique_ptr<MemoryBuffer>>
669setupMemoryBuffer(std::string Filename) {
Diego Novilloc572e922014-10-30 18:00:06 +0000670 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
671 if (std::error_code EC = BufferOrErr.getError())
672 return EC;
Diego Novillofcd55602014-11-03 00:51:45 +0000673 auto Buffer = std::move(BufferOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000674
675 // Sanity check the file.
Diego Novillo38be3332015-10-15 16:36:21 +0000676 if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
Diego Novilloc572e922014-10-30 18:00:06 +0000677 return sampleprof_error::too_large;
678
Diego Novillofcd55602014-11-03 00:51:45 +0000679 return std::move(Buffer);
Diego Novilloc572e922014-10-30 18:00:06 +0000680}
681
682/// \brief Create a sample profile reader based on the format of the input file.
683///
684/// \param Filename The file to open.
685///
686/// \param Reader The reader to instantiate according to \p Filename's format.
687///
688/// \param C The LLVM context to use to emit diagnostics.
689///
690/// \returns an error code indicating the status of the created reader.
Diego Novillofcd55602014-11-03 00:51:45 +0000691ErrorOr<std::unique_ptr<SampleProfileReader>>
692SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
693 auto BufferOrError = setupMemoryBuffer(Filename);
694 if (std::error_code EC = BufferOrError.getError())
Diego Novilloc572e922014-10-30 18:00:06 +0000695 return EC;
696
Diego Novillofcd55602014-11-03 00:51:45 +0000697 auto Buffer = std::move(BufferOrError.get());
698 std::unique_ptr<SampleProfileReader> Reader;
Diego Novilloc572e922014-10-30 18:00:06 +0000699 if (SampleProfileReaderBinary::hasFormat(*Buffer))
700 Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
Diego Novillo3376a782015-09-17 00:17:24 +0000701 else if (SampleProfileReaderGCC::hasFormat(*Buffer))
702 Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
Nathan Slingerland4f823662015-11-13 03:47:58 +0000703 else if (SampleProfileReaderText::hasFormat(*Buffer))
Nathan Slingerland911ced62015-11-12 18:39:26 +0000704 Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
Nathan Slingerland4f823662015-11-13 03:47:58 +0000705 else
706 return sampleprof_error::unrecognized_format;
Diego Novilloc572e922014-10-30 18:00:06 +0000707
Diego Novillofcd55602014-11-03 00:51:45 +0000708 if (std::error_code EC = Reader->readHeader())
709 return EC;
710
711 return std::move(Reader);
Diego Novillode1ab262014-09-09 12:40:50 +0000712}