blob: a058274e8eeda846641c8c2840d1da1d238f137f [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 Novilloc572e922014-10-30 18:00:06 +000011// supports two file formats: text and binary. The textual representation
12// is useful for debugging and testing purposes. The binary representation
Diego Novillode1ab262014-09-09 12:40:50 +000013// is more compact, resulting in smaller file sizes. However, they can
14// both be used interchangeably.
15//
16// NOTE: If you are making changes to the file format, please remember
17// to document them in the Clang documentation at
18// tools/clang/docs/UsersManual.rst.
19//
20// Text format
21// -----------
22//
23// Sample profiles are written as ASCII text. The file is divided into
24// sections, which correspond to each of the functions executed at runtime.
25// Each section has the following format
26//
27// function1:total_samples:total_head_samples
Dehao Chen67226882015-09-30 00:42:46 +000028// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
29// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
30// ...
31// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
32// offsetA[.discriminator]: fnA:num_of_total_samples
33// offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
34// ...
Diego Novillode1ab262014-09-09 12:40:50 +000035//
Dehao Chen67226882015-09-30 00:42:46 +000036// This is a nested tree in which the identation represent the nest level
37// of the inline stack. There is no blank line in the file. And the spacing
38// within a single line is fixed. Additional spaces will result in an error
39// while reading the file.
40//
41// Inline stack is a stack of source locations in which the top of the stack
42// represents the leaf function, and the bottom of the stack represents the
43// actual symbol in which the instruction belongs.
Diego Novillode1ab262014-09-09 12:40:50 +000044//
45// Function names must be mangled in order for the profile loader to
46// match them in the current translation unit. The two numbers in the
47// function header specify how many total samples were accumulated in the
48// function (first number), and the total number of samples accumulated
49// in the prologue of the function (second number). This head sample
50// count provides an indicator of how frequently the function is invoked.
51//
Dehao Chen67226882015-09-30 00:42:46 +000052// There are two types of lines in the function body.
53//
54// * Sampled line represents the profile information of a source location.
55// * Callsite line represents the profile inofrmation of a callsite.
56//
Diego Novillode1ab262014-09-09 12:40:50 +000057// Each sampled line may contain several items. Some are optional (marked
58// below):
59//
60// a. Source line offset. This number represents the line number
61// in the function where the sample was collected. The line number is
62// always relative to the line where symbol of the function is
63// defined. So, if the function has its header at line 280, the offset
64// 13 is at line 293 in the file.
65//
66// Note that this offset should never be a negative number. This could
67// happen in cases like macros. The debug machinery will register the
68// line number at the point of macro expansion. So, if the macro was
69// expanded in a line before the start of the function, the profile
70// converter should emit a 0 as the offset (this means that the optimizers
71// will not be able to associate a meaningful weight to the instructions
72// in the macro).
73//
74// b. [OPTIONAL] Discriminator. This is used if the sampled program
75// was compiled with DWARF discriminator support
76// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
77// DWARF discriminators are unsigned integer values that allow the
78// compiler to distinguish between multiple execution paths on the
79// same source line location.
80//
81// For example, consider the line of code ``if (cond) foo(); else bar();``.
82// If the predicate ``cond`` is true 80% of the time, then the edge
83// into function ``foo`` should be considered to be taken most of the
84// time. But both calls to ``foo`` and ``bar`` are at the same source
85// line, so a sample count at that line is not sufficient. The
86// compiler needs to know which part of that line is taken more
87// frequently.
88//
89// This is what discriminators provide. In this case, the calls to
90// ``foo`` and ``bar`` will be at the same line, but will have
91// different discriminator values. This allows the compiler to correctly
92// set edge weights into ``foo`` and ``bar``.
93//
94// c. Number of samples. This is an integer quantity representing the
95// number of samples collected by the profiler at this source
96// location.
97//
98// d. [OPTIONAL] Potential call targets and samples. If present, this
99// line contains a call instruction. This models both direct and
100// number of samples. For example,
101//
102// 130: 7 foo:3 bar:2 baz:7
103//
104// The above means that at relative line offset 130 there is a call
105// instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
106// with ``baz()`` being the relatively more frequently called target.
107//
Dehao Chen67226882015-09-30 00:42:46 +0000108// Each callsite line may contain several items. Some are optional.
109//
110// a. Source line offset. This number represents the line number of the
111// callsite that is inlined in the profiled binary.
112//
113// b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
114//
115// c. Number of samples. This is an integer quantity representing the
116// total number of samples collected for the inlined instance at this
117// callsite
Diego Novillode1ab262014-09-09 12:40:50 +0000118//===----------------------------------------------------------------------===//
119
120#include "llvm/ProfileData/SampleProfReader.h"
121#include "llvm/Support/Debug.h"
122#include "llvm/Support/ErrorOr.h"
Diego Novilloc572e922014-10-30 18:00:06 +0000123#include "llvm/Support/LEB128.h"
Diego Novillode1ab262014-09-09 12:40:50 +0000124#include "llvm/Support/LineIterator.h"
Diego Novilloc572e922014-10-30 18:00:06 +0000125#include "llvm/Support/MemoryBuffer.h"
Dehao Chen67226882015-09-30 00:42:46 +0000126#include "llvm/ADT/DenseMap.h"
127#include "llvm/ADT/SmallVector.h"
Diego Novillode1ab262014-09-09 12:40:50 +0000128
Diego Novilloc572e922014-10-30 18:00:06 +0000129using namespace llvm::sampleprof;
Diego Novillode1ab262014-09-09 12:40:50 +0000130using namespace llvm;
131
132/// \brief Print the samples collected for a function on stream \p OS.
133///
134/// \param OS Stream to emit the output to.
Diego Novilloaae1ed82015-10-08 19:40:37 +0000135void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
Diego Novillode1ab262014-09-09 12:40:50 +0000136 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
137 << " sampled lines\n";
Diego Novillod5336ae2014-11-01 00:56:55 +0000138 for (const auto &SI : BodySamples) {
139 LineLocation Loc = SI.first;
140 const SampleRecord &Sample = SI.second;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000141 OS.indent(Indent);
142 OS << "line offset: " << Loc.LineOffset
Diego Novilloc572e922014-10-30 18:00:06 +0000143 << ", discriminator: " << Loc.Discriminator
144 << ", number of samples: " << Sample.getSamples();
145 if (Sample.hasCalls()) {
146 OS << ", calls:";
Diego Novillod5336ae2014-11-01 00:56:55 +0000147 for (const auto &I : Sample.getCallTargets())
148 OS << " " << I.first() << ":" << I.second;
Diego Novilloc572e922014-10-30 18:00:06 +0000149 }
150 OS << "\n";
151 }
Diego Novilloaae1ed82015-10-08 19:40:37 +0000152 for (const auto &CS : CallsiteSamples) {
153 CallsiteLocation Loc = CS.first;
154 const FunctionSamples &CalleeSamples = CS.second;
155 OS.indent(Indent);
156 OS << "line offset: " << Loc.LineOffset
157 << ", discriminator: " << Loc.Discriminator
158 << ", inlined callee: " << Loc.CalleeName << ": ";
159 CalleeSamples.print(OS, Indent + 2);
160 }
Diego Novillode1ab262014-09-09 12:40:50 +0000161}
162
Diego Novillod5336ae2014-11-01 00:56:55 +0000163/// \brief Dump the function profile for \p FName.
Diego Novillode1ab262014-09-09 12:40:50 +0000164///
Diego Novillode1ab262014-09-09 12:40:50 +0000165/// \param FName Name of the function to print.
Diego Novillod5336ae2014-11-01 00:56:55 +0000166/// \param OS Stream to emit the output to.
167void SampleProfileReader::dumpFunctionProfile(StringRef FName,
168 raw_ostream &OS) {
Diego Novilloc572e922014-10-30 18:00:06 +0000169 OS << "Function: " << FName << ": ";
Diego Novillode1ab262014-09-09 12:40:50 +0000170 Profiles[FName].print(OS);
171}
172
Diego Novillod5336ae2014-11-01 00:56:55 +0000173/// \brief Dump all the function profiles found on stream \p OS.
174void SampleProfileReader::dump(raw_ostream &OS) {
175 for (const auto &I : Profiles)
176 dumpFunctionProfile(I.getKey(), OS);
Diego Novillode1ab262014-09-09 12:40:50 +0000177}
178
Dehao Chen67226882015-09-30 00:42:46 +0000179/// \brief Parse \p Input as function head.
180///
181/// Parse one line of \p Input, and update function name in \p FName,
182/// function's total sample count in \p NumSamples, function's entry
183/// count in \p NumHeadSamples.
184///
185/// \returns true if parsing is successful.
186static bool ParseHead(const StringRef &Input, StringRef &FName,
187 unsigned &NumSamples, unsigned &NumHeadSamples) {
188 if (Input[0] == ' ')
189 return false;
190 size_t n2 = Input.rfind(':');
191 size_t n1 = Input.rfind(':', n2 - 1);
192 FName = Input.substr(0, n1);
193 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
194 return false;
195 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
196 return false;
197 return true;
198}
199
200/// \brief Parse \p Input as line sample.
201///
202/// \param Input input line.
203/// \param IsCallsite true if the line represents an inlined callsite.
204/// \param Depth the depth of the inline stack.
205/// \param NumSamples total samples of the line/inlined callsite.
206/// \param LineOffset line offset to the start of the function.
207/// \param Discriminator discriminator of the line.
208/// \param TargetCountMap map from indirect call target to count.
209///
210/// returns true if parsing is successful.
211static bool ParseLine(const StringRef &Input, bool &IsCallsite, unsigned &Depth,
212 unsigned &NumSamples, unsigned &LineOffset,
213 unsigned &Discriminator, StringRef &CalleeName,
214 DenseMap<StringRef, unsigned> &TargetCountMap) {
215 for (Depth = 0; Input[Depth] == ' '; Depth++)
216 ;
217 if (Depth == 0)
218 return false;
219
220 size_t n1 = Input.find(':');
221 StringRef Loc = Input.substr(Depth, n1 - Depth);
222 size_t n2 = Loc.find('.');
223 if (n2 == StringRef::npos) {
224 if (Loc.getAsInteger(10, LineOffset))
225 return false;
226 Discriminator = 0;
227 } else {
228 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
229 return false;
230 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
231 return false;
232 }
233
234 StringRef Rest = Input.substr(n1 + 2);
235 if (Rest[0] >= '0' && Rest[0] <= '9') {
236 IsCallsite = false;
237 size_t n3 = Rest.find(' ');
238 if (n3 == StringRef::npos) {
239 if (Rest.getAsInteger(10, NumSamples))
240 return false;
241 } else {
242 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
243 return false;
244 }
245 while (n3 != StringRef::npos) {
246 n3 += Rest.substr(n3).find_first_not_of(' ');
247 Rest = Rest.substr(n3);
248 n3 = Rest.find(' ');
249 StringRef pair = Rest;
250 if (n3 != StringRef::npos) {
251 pair = Rest.substr(0, n3);
252 }
253 int n4 = pair.find(':');
254 unsigned count;
255 if (pair.substr(n4 + 1).getAsInteger(10, count))
256 return false;
257 TargetCountMap[pair.substr(0, n4)] = count;
258 }
259 } else {
260 IsCallsite = true;
261 int n3 = Rest.find_last_of(':');
262 CalleeName = Rest.substr(0, n3);
263 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
264 return false;
265 }
266 return true;
267}
268
Diego Novillode1ab262014-09-09 12:40:50 +0000269/// \brief Load samples from a text file.
270///
271/// See the documentation at the top of the file for an explanation of
272/// the expected format.
273///
274/// \returns true if the file was loaded successfully, false otherwise.
Diego Novilloc572e922014-10-30 18:00:06 +0000275std::error_code SampleProfileReaderText::read() {
276 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
Diego Novillode1ab262014-09-09 12:40:50 +0000277
Diego Novilloaae1ed82015-10-08 19:40:37 +0000278 InlineCallStack InlineStack;
Dehao Chen67226882015-09-30 00:42:46 +0000279
280 for (; !LineIt.is_at_eof(); ++LineIt) {
281 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
282 continue;
Diego Novillode1ab262014-09-09 12:40:50 +0000283 // Read the header of each function.
284 //
285 // Note that for function identifiers we are actually expecting
286 // mangled names, but we may not always get them. This happens when
287 // the compiler decides not to emit the function (e.g., it was inlined
288 // and removed). In this case, the binary will not have the linkage
289 // name for the function, so the profiler will emit the function's
290 // unmangled name, which may contain characters like ':' and '>' in its
291 // name (member functions, templates, etc).
292 //
293 // The only requirement we place on the identifier, then, is that it
294 // should not begin with a number.
Dehao Chen67226882015-09-30 00:42:46 +0000295 if ((*LineIt)[0] != ' ') {
296 unsigned NumSamples, NumHeadSamples;
297 StringRef FName;
298 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
299 reportError(LineIt.line_number(),
300 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
301 return sampleprof_error::malformed;
302 }
303 Profiles[FName] = FunctionSamples();
304 FunctionSamples &FProfile = Profiles[FName];
305 FProfile.addTotalSamples(NumSamples);
306 FProfile.addHeadSamples(NumHeadSamples);
307 InlineStack.clear();
308 InlineStack.push_back(&FProfile);
309 } else {
310 unsigned NumSamples;
311 StringRef FName;
312 DenseMap<StringRef, unsigned> TargetCountMap;
313 bool IsCallsite;
314 unsigned Depth, LineOffset, Discriminator;
315 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
316 Discriminator, FName, TargetCountMap)) {
Diego Novillo3376a782015-09-17 00:17:24 +0000317 reportError(LineIt.line_number(),
318 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
319 *LineIt);
Diego Novilloc572e922014-10-30 18:00:06 +0000320 return sampleprof_error::malformed;
Diego Novillode1ab262014-09-09 12:40:50 +0000321 }
Dehao Chen67226882015-09-30 00:42:46 +0000322 if (IsCallsite) {
323 while (InlineStack.size() > Depth) {
324 InlineStack.pop_back();
Diego Novilloc572e922014-10-30 18:00:06 +0000325 }
Dehao Chen67226882015-09-30 00:42:46 +0000326 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
327 CallsiteLocation(LineOffset, Discriminator, FName));
328 FSamples.addTotalSamples(NumSamples);
329 InlineStack.push_back(&FSamples);
330 } else {
331 while (InlineStack.size() > Depth) {
332 InlineStack.pop_back();
333 }
334 FunctionSamples &FProfile = *InlineStack.back();
335 for (const auto &name_count : TargetCountMap) {
336 FProfile.addCalledTargetSamples(LineOffset, Discriminator,
337 name_count.first, name_count.second);
338 }
339 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
Diego Novilloc572e922014-10-30 18:00:06 +0000340 }
Diego Novillode1ab262014-09-09 12:40:50 +0000341 }
342 }
343
Diego Novilloc572e922014-10-30 18:00:06 +0000344 return sampleprof_error::success;
Diego Novillode1ab262014-09-09 12:40:50 +0000345}
346
Diego Novillod5336ae2014-11-01 00:56:55 +0000347template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
Diego Novilloc572e922014-10-30 18:00:06 +0000348 unsigned NumBytesRead = 0;
349 std::error_code EC;
350 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
351
352 if (Val > std::numeric_limits<T>::max())
353 EC = sampleprof_error::malformed;
354 else if (Data + NumBytesRead > End)
355 EC = sampleprof_error::truncated;
356 else
357 EC = sampleprof_error::success;
358
359 if (EC) {
Diego Novillo3376a782015-09-17 00:17:24 +0000360 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000361 return EC;
362 }
363
364 Data += NumBytesRead;
365 return static_cast<T>(Val);
366}
367
368ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
369 std::error_code EC;
370 StringRef Str(reinterpret_cast<const char *>(Data));
371 if (Data + Str.size() + 1 > End) {
372 EC = sampleprof_error::truncated;
Diego Novillo3376a782015-09-17 00:17:24 +0000373 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000374 return EC;
375 }
376
377 Data += Str.size() + 1;
378 return Str;
379}
380
Diego Novillo760c5a82015-10-13 22:48:46 +0000381ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
382 std::error_code EC;
383 auto Idx = readNumber<unsigned>();
384 if (std::error_code EC = Idx.getError())
385 return EC;
386 if (*Idx >= NameTable.size())
387 return sampleprof_error::truncated_name_table;
388 return NameTable[*Idx];
389}
390
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000391std::error_code
392SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
393 auto Val = readNumber<unsigned>();
394 if (std::error_code EC = Val.getError())
395 return EC;
396 FProfile.addTotalSamples(*Val);
397
398 Val = readNumber<unsigned>();
399 if (std::error_code EC = Val.getError())
400 return EC;
401 FProfile.addHeadSamples(*Val);
402
403 // Read the samples in the body.
404 auto NumRecords = readNumber<unsigned>();
405 if (std::error_code EC = NumRecords.getError())
406 return EC;
407
408 for (unsigned I = 0; I < *NumRecords; ++I) {
409 auto LineOffset = readNumber<uint64_t>();
410 if (std::error_code EC = LineOffset.getError())
411 return EC;
412
413 auto Discriminator = readNumber<uint64_t>();
414 if (std::error_code EC = Discriminator.getError())
415 return EC;
416
417 auto NumSamples = readNumber<uint64_t>();
418 if (std::error_code EC = NumSamples.getError())
419 return EC;
420
421 auto NumCalls = readNumber<unsigned>();
422 if (std::error_code EC = NumCalls.getError())
423 return EC;
424
425 for (unsigned J = 0; J < *NumCalls; ++J) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000426 auto CalledFunction(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000427 if (std::error_code EC = CalledFunction.getError())
428 return EC;
429
430 auto CalledFunctionSamples = readNumber<uint64_t>();
431 if (std::error_code EC = CalledFunctionSamples.getError())
432 return EC;
433
434 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
435 *CalledFunction, *CalledFunctionSamples);
436 }
437
438 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
439 }
440
441 // Read all the samples for inlined function calls.
442 auto NumCallsites = readNumber<unsigned>();
443 if (std::error_code EC = NumCallsites.getError())
444 return EC;
445
446 for (unsigned J = 0; J < *NumCallsites; ++J) {
447 auto LineOffset = readNumber<uint64_t>();
448 if (std::error_code EC = LineOffset.getError())
449 return EC;
450
451 auto Discriminator = readNumber<uint64_t>();
452 if (std::error_code EC = Discriminator.getError())
453 return EC;
454
Diego Novillo760c5a82015-10-13 22:48:46 +0000455 auto FName(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000456 if (std::error_code EC = FName.getError())
457 return EC;
458
459 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
460 CallsiteLocation(*LineOffset, *Discriminator, *FName));
461 if (std::error_code EC = readProfile(CalleeProfile))
462 return EC;
463 }
464
465 return sampleprof_error::success;
466}
467
Diego Novilloc572e922014-10-30 18:00:06 +0000468std::error_code SampleProfileReaderBinary::read() {
469 while (!at_eof()) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000470 auto FName(readStringFromTable());
Diego Novilloc572e922014-10-30 18:00:06 +0000471 if (std::error_code EC = FName.getError())
472 return EC;
473
474 Profiles[*FName] = FunctionSamples();
475 FunctionSamples &FProfile = Profiles[*FName];
476
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000477 if (std::error_code EC = readProfile(FProfile))
Diego Novilloc572e922014-10-30 18:00:06 +0000478 return EC;
Diego Novilloc572e922014-10-30 18:00:06 +0000479 }
480
481 return sampleprof_error::success;
482}
483
484std::error_code SampleProfileReaderBinary::readHeader() {
485 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
486 End = Data + Buffer->getBufferSize();
487
488 // Read and check the magic identifier.
489 auto Magic = readNumber<uint64_t>();
490 if (std::error_code EC = Magic.getError())
491 return EC;
492 else if (*Magic != SPMagic())
493 return sampleprof_error::bad_magic;
494
495 // Read the version number.
496 auto Version = readNumber<uint64_t>();
497 if (std::error_code EC = Version.getError())
498 return EC;
499 else if (*Version != SPVersion())
500 return sampleprof_error::unsupported_version;
501
Diego Novillo760c5a82015-10-13 22:48:46 +0000502 // Read the name table.
503 auto Size = readNumber<size_t>();
504 if (std::error_code EC = Size.getError())
505 return EC;
506 NameTable.reserve(*Size);
507 for (size_t I = 0; I < *Size; ++I) {
508 auto Name(readString());
509 if (std::error_code EC = Name.getError())
510 return EC;
511 NameTable.push_back(*Name);
512 }
513
Diego Novilloc572e922014-10-30 18:00:06 +0000514 return sampleprof_error::success;
515}
516
517bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
518 const uint8_t *Data =
519 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
520 uint64_t Magic = decodeULEB128(Data);
521 return Magic == SPMagic();
522}
523
Diego Novillo3376a782015-09-17 00:17:24 +0000524bool SourceInfo::operator<(const SourceInfo &P) const {
525 if (Line != P.Line)
526 return Line < P.Line;
527 if (StartLine != P.StartLine)
528 return StartLine < P.StartLine;
529 if (Discriminator != P.Discriminator)
530 return Discriminator < P.Discriminator;
531 return FuncName < P.FuncName;
532}
533
534std::error_code SampleProfileReaderGCC::skipNextWord() {
535 uint32_t dummy;
536 if (!GcovBuffer.readInt(dummy))
537 return sampleprof_error::truncated;
538 return sampleprof_error::success;
539}
540
541template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
542 if (sizeof(T) <= sizeof(uint32_t)) {
543 uint32_t Val;
544 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
545 return static_cast<T>(Val);
546 } else if (sizeof(T) <= sizeof(uint64_t)) {
547 uint64_t Val;
548 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
549 return static_cast<T>(Val);
550 }
551
552 std::error_code EC = sampleprof_error::malformed;
553 reportError(0, EC.message());
554 return EC;
555}
556
557ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
558 StringRef Str;
559 if (!GcovBuffer.readString(Str))
560 return sampleprof_error::truncated;
561 return Str;
562}
563
564std::error_code SampleProfileReaderGCC::readHeader() {
565 // Read the magic identifier.
566 if (!GcovBuffer.readGCDAFormat())
567 return sampleprof_error::unrecognized_format;
568
569 // Read the version number. Note - the GCC reader does not validate this
570 // version, but the profile creator generates v704.
571 GCOV::GCOVVersion version;
572 if (!GcovBuffer.readGCOVVersion(version))
573 return sampleprof_error::unrecognized_format;
574
575 if (version != GCOV::V704)
576 return sampleprof_error::unsupported_version;
577
578 // Skip the empty integer.
579 if (std::error_code EC = skipNextWord())
580 return EC;
581
582 return sampleprof_error::success;
583}
584
585std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
586 uint32_t Tag;
587 if (!GcovBuffer.readInt(Tag))
588 return sampleprof_error::truncated;
589
590 if (Tag != Expected)
591 return sampleprof_error::malformed;
592
593 if (std::error_code EC = skipNextWord())
594 return EC;
595
596 return sampleprof_error::success;
597}
598
599std::error_code SampleProfileReaderGCC::readNameTable() {
600 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
601 return EC;
602
603 uint32_t Size;
604 if (!GcovBuffer.readInt(Size))
605 return sampleprof_error::truncated;
606
607 for (uint32_t I = 0; I < Size; ++I) {
608 StringRef Str;
609 if (!GcovBuffer.readString(Str))
610 return sampleprof_error::truncated;
611 Names.push_back(Str);
612 }
613
614 return sampleprof_error::success;
615}
616
617std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
618 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
619 return EC;
620
621 uint32_t NumFunctions;
622 if (!GcovBuffer.readInt(NumFunctions))
623 return sampleprof_error::truncated;
624
Diego Novilloaae1ed82015-10-08 19:40:37 +0000625 InlineCallStack Stack;
Diego Novillo3376a782015-09-17 00:17:24 +0000626 for (uint32_t I = 0; I < NumFunctions; ++I)
Diego Novilloaae1ed82015-10-08 19:40:37 +0000627 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
Diego Novillo3376a782015-09-17 00:17:24 +0000628 return EC;
629
630 return sampleprof_error::success;
631}
632
Diego Novilloaae1ed82015-10-08 19:40:37 +0000633std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
634 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
Diego Novillo3376a782015-09-17 00:17:24 +0000635 uint64_t HeadCount = 0;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000636 if (InlineStack.size() == 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000637 if (!GcovBuffer.readInt64(HeadCount))
638 return sampleprof_error::truncated;
639
640 uint32_t NameIdx;
641 if (!GcovBuffer.readInt(NameIdx))
642 return sampleprof_error::truncated;
643
644 StringRef Name(Names[NameIdx]);
645
646 uint32_t NumPosCounts;
647 if (!GcovBuffer.readInt(NumPosCounts))
648 return sampleprof_error::truncated;
649
Diego Novilloaae1ed82015-10-08 19:40:37 +0000650 uint32_t NumCallsites;
651 if (!GcovBuffer.readInt(NumCallsites))
Diego Novillo3376a782015-09-17 00:17:24 +0000652 return sampleprof_error::truncated;
653
Diego Novilloaae1ed82015-10-08 19:40:37 +0000654 FunctionSamples *FProfile = nullptr;
655 if (InlineStack.size() == 0) {
656 // If this is a top function that we have already processed, do not
657 // update its profile again. This happens in the presence of
658 // function aliases. Since these aliases share the same function
659 // body, there will be identical replicated profiles for the
660 // original function. In this case, we simply not bother updating
661 // the profile of the original function.
662 FProfile = &Profiles[Name];
663 FProfile->addHeadSamples(HeadCount);
664 if (FProfile->getTotalSamples() > 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000665 Update = false;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000666 } else {
667 // Otherwise, we are reading an inlined instance. The top of the
668 // inline stack contains the profile of the caller. Insert this
669 // callee in the caller's CallsiteMap.
670 FunctionSamples *CallerProfile = InlineStack.front();
671 uint32_t LineOffset = Offset >> 16;
672 uint32_t Discriminator = Offset & 0xffff;
673 FProfile = &CallerProfile->functionSamplesAt(
674 CallsiteLocation(LineOffset, Discriminator, Name));
Diego Novillo3376a782015-09-17 00:17:24 +0000675 }
676
677 for (uint32_t I = 0; I < NumPosCounts; ++I) {
678 uint32_t Offset;
679 if (!GcovBuffer.readInt(Offset))
680 return sampleprof_error::truncated;
681
682 uint32_t NumTargets;
683 if (!GcovBuffer.readInt(NumTargets))
684 return sampleprof_error::truncated;
685
686 uint64_t Count;
687 if (!GcovBuffer.readInt64(Count))
688 return sampleprof_error::truncated;
689
Diego Novilloaae1ed82015-10-08 19:40:37 +0000690 // The line location is encoded in the offset as:
691 // high 16 bits: line offset to the start of the function.
692 // low 16 bits: discriminator.
693 uint32_t LineOffset = Offset >> 16;
694 uint32_t Discriminator = Offset & 0xffff;
Diego Novillo3376a782015-09-17 00:17:24 +0000695
Diego Novilloaae1ed82015-10-08 19:40:37 +0000696 InlineCallStack NewStack;
697 NewStack.push_back(FProfile);
698 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
699 if (Update) {
700 // Walk up the inline stack, adding the samples on this line to
701 // the total sample count of the callers in the chain.
702 for (auto CallerProfile : NewStack)
703 CallerProfile->addTotalSamples(Count);
704
705 // Update the body samples for the current profile.
706 FProfile->addBodySamples(LineOffset, Discriminator, Count);
707 }
708
709 // Process the list of functions called at an indirect call site.
710 // These are all the targets that a function pointer (or virtual
711 // function) resolved at runtime.
Diego Novillo3376a782015-09-17 00:17:24 +0000712 for (uint32_t J = 0; J < NumTargets; J++) {
713 uint32_t HistVal;
714 if (!GcovBuffer.readInt(HistVal))
715 return sampleprof_error::truncated;
716
717 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
718 return sampleprof_error::malformed;
719
720 uint64_t TargetIdx;
721 if (!GcovBuffer.readInt64(TargetIdx))
722 return sampleprof_error::truncated;
723 StringRef TargetName(Names[TargetIdx]);
724
725 uint64_t TargetCount;
726 if (!GcovBuffer.readInt64(TargetCount))
727 return sampleprof_error::truncated;
728
729 if (Update) {
730 FunctionSamples &TargetProfile = Profiles[TargetName];
Diego Novilloaae1ed82015-10-08 19:40:37 +0000731 TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
732 TargetName, TargetCount);
Diego Novillo3376a782015-09-17 00:17:24 +0000733 }
734 }
735 }
736
Diego Novilloaae1ed82015-10-08 19:40:37 +0000737 // Process all the inlined callers into the current function. These
738 // are all the callsites that were inlined into this function.
739 for (uint32_t I = 0; I < NumCallsites; I++) {
Diego Novillo3376a782015-09-17 00:17:24 +0000740 // The offset is encoded as:
741 // high 16 bits: line offset to the start of the function.
742 // low 16 bits: discriminator.
743 uint32_t Offset;
744 if (!GcovBuffer.readInt(Offset))
745 return sampleprof_error::truncated;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000746 InlineCallStack NewStack;
747 NewStack.push_back(FProfile);
748 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
749 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
Diego Novillo3376a782015-09-17 00:17:24 +0000750 return EC;
751 }
752
753 return sampleprof_error::success;
754}
755
Diego Novillo3376a782015-09-17 00:17:24 +0000756/// \brief Read a GCC AutoFDO profile.
757///
758/// This format is generated by the Linux Perf conversion tool at
759/// https://github.com/google/autofdo.
760std::error_code SampleProfileReaderGCC::read() {
761 // Read the string table.
762 if (std::error_code EC = readNameTable())
763 return EC;
764
765 // Read the source profile.
766 if (std::error_code EC = readFunctionProfiles())
767 return EC;
768
Diego Novillo3376a782015-09-17 00:17:24 +0000769 return sampleprof_error::success;
770}
771
772bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
773 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
774 return Magic == "adcg*704";
775}
776
Diego Novilloc572e922014-10-30 18:00:06 +0000777/// \brief Prepare a memory buffer for the contents of \p Filename.
Diego Novillode1ab262014-09-09 12:40:50 +0000778///
Diego Novilloc572e922014-10-30 18:00:06 +0000779/// \returns an error code indicating the status of the buffer.
Diego Novillofcd55602014-11-03 00:51:45 +0000780static ErrorOr<std::unique_ptr<MemoryBuffer>>
781setupMemoryBuffer(std::string Filename) {
Diego Novilloc572e922014-10-30 18:00:06 +0000782 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
783 if (std::error_code EC = BufferOrErr.getError())
784 return EC;
Diego Novillofcd55602014-11-03 00:51:45 +0000785 auto Buffer = std::move(BufferOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000786
787 // Sanity check the file.
788 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
789 return sampleprof_error::too_large;
790
Diego Novillofcd55602014-11-03 00:51:45 +0000791 return std::move(Buffer);
Diego Novilloc572e922014-10-30 18:00:06 +0000792}
793
794/// \brief Create a sample profile reader based on the format of the input file.
795///
796/// \param Filename The file to open.
797///
798/// \param Reader The reader to instantiate according to \p Filename's format.
799///
800/// \param C The LLVM context to use to emit diagnostics.
801///
802/// \returns an error code indicating the status of the created reader.
Diego Novillofcd55602014-11-03 00:51:45 +0000803ErrorOr<std::unique_ptr<SampleProfileReader>>
804SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
805 auto BufferOrError = setupMemoryBuffer(Filename);
806 if (std::error_code EC = BufferOrError.getError())
Diego Novilloc572e922014-10-30 18:00:06 +0000807 return EC;
808
Diego Novillofcd55602014-11-03 00:51:45 +0000809 auto Buffer = std::move(BufferOrError.get());
810 std::unique_ptr<SampleProfileReader> Reader;
Diego Novilloc572e922014-10-30 18:00:06 +0000811 if (SampleProfileReaderBinary::hasFormat(*Buffer))
812 Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
Diego Novillo3376a782015-09-17 00:17:24 +0000813 else if (SampleProfileReaderGCC::hasFormat(*Buffer))
814 Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
Diego Novilloc572e922014-10-30 18:00:06 +0000815 else
816 Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
817
Diego Novillofcd55602014-11-03 00:51:45 +0000818 if (std::error_code EC = Reader->readHeader())
819 return EC;
820
821 return std::move(Reader);
Diego Novillode1ab262014-09-09 12:40:50 +0000822}