blob: e192b58de9c2d5b41972309d71c8a72db19ffbf1 [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"
Easwaran Raman40ee23d2016-02-19 03:15:33 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000026#include "llvm/ADT/StringRef.h"
27#include "llvm/IR/ProfileSummary.h"
28#include "llvm/ProfileData/ProfileCommon.h"
29#include "llvm/ProfileData/SampleProf.h"
Diego Novillode1ab262014-09-09 12:40:50 +000030#include "llvm/Support/ErrorOr.h"
Diego Novilloc572e922014-10-30 18:00:06 +000031#include "llvm/Support/LEB128.h"
Diego Novillode1ab262014-09-09 12:40:50 +000032#include "llvm/Support/LineIterator.h"
Diego Novilloc572e922014-10-30 18:00:06 +000033#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000034#include "llvm/Support/raw_ostream.h"
35#include <algorithm>
36#include <cstddef>
37#include <cstdint>
38#include <limits>
39#include <memory>
40#include <system_error>
41#include <vector>
Diego Novillode1ab262014-09-09 12:40:50 +000042
Diego Novillode1ab262014-09-09 12:40:50 +000043using namespace llvm;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000044using namespace sampleprof;
Diego Novillode1ab262014-09-09 12:40:50 +000045
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000046/// Dump the function profile for \p FName.
Diego Novillode1ab262014-09-09 12:40:50 +000047///
Diego Novillode1ab262014-09-09 12:40:50 +000048/// \param FName Name of the function to print.
Diego Novillod5336ae2014-11-01 00:56:55 +000049/// \param OS Stream to emit the output to.
50void SampleProfileReader::dumpFunctionProfile(StringRef FName,
51 raw_ostream &OS) {
Diego Novillo8e415a82015-11-13 20:24:28 +000052 OS << "Function: " << FName << ": " << Profiles[FName];
Diego Novillode1ab262014-09-09 12:40:50 +000053}
54
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000055/// Dump all the function profiles found on stream \p OS.
Diego Novillod5336ae2014-11-01 00:56:55 +000056void SampleProfileReader::dump(raw_ostream &OS) {
57 for (const auto &I : Profiles)
58 dumpFunctionProfile(I.getKey(), OS);
Diego Novillode1ab262014-09-09 12:40:50 +000059}
60
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000061/// Parse \p Input as function head.
Dehao Chen67226882015-09-30 00:42:46 +000062///
63/// Parse one line of \p Input, and update function name in \p FName,
64/// function's total sample count in \p NumSamples, function's entry
65/// count in \p NumHeadSamples.
66///
67/// \returns true if parsing is successful.
68static bool ParseHead(const StringRef &Input, StringRef &FName,
Diego Novillo38be3332015-10-15 16:36:21 +000069 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
Dehao Chen67226882015-09-30 00:42:46 +000070 if (Input[0] == ' ')
71 return false;
72 size_t n2 = Input.rfind(':');
73 size_t n1 = Input.rfind(':', n2 - 1);
74 FName = Input.substr(0, n1);
75 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
76 return false;
77 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
78 return false;
79 return true;
80}
81
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000082/// Returns true if line offset \p L is legal (only has 16 bits).
Dehao Chen57d1dda2016-03-03 18:09:32 +000083static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
Dehao Chen10042412015-10-21 01:22:27 +000084
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000085/// Parse \p Input as line sample.
Dehao Chen67226882015-09-30 00:42:46 +000086///
87/// \param Input input line.
88/// \param IsCallsite true if the line represents an inlined callsite.
89/// \param Depth the depth of the inline stack.
90/// \param NumSamples total samples of the line/inlined callsite.
91/// \param LineOffset line offset to the start of the function.
92/// \param Discriminator discriminator of the line.
93/// \param TargetCountMap map from indirect call target to count.
94///
95/// returns true if parsing is successful.
Diego Novillo38be3332015-10-15 16:36:21 +000096static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
97 uint64_t &NumSamples, uint32_t &LineOffset,
98 uint32_t &Discriminator, StringRef &CalleeName,
99 DenseMap<StringRef, uint64_t> &TargetCountMap) {
Dehao Chen67226882015-09-30 00:42:46 +0000100 for (Depth = 0; Input[Depth] == ' '; Depth++)
101 ;
102 if (Depth == 0)
103 return false;
104
105 size_t n1 = Input.find(':');
106 StringRef Loc = Input.substr(Depth, n1 - Depth);
107 size_t n2 = Loc.find('.');
108 if (n2 == StringRef::npos) {
Dehao Chen10042412015-10-21 01:22:27 +0000109 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
Dehao Chen67226882015-09-30 00:42:46 +0000110 return false;
111 Discriminator = 0;
112 } else {
113 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
114 return false;
115 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
116 return false;
117 }
118
119 StringRef Rest = Input.substr(n1 + 2);
120 if (Rest[0] >= '0' && Rest[0] <= '9') {
121 IsCallsite = false;
122 size_t n3 = Rest.find(' ');
123 if (n3 == StringRef::npos) {
124 if (Rest.getAsInteger(10, NumSamples))
125 return false;
126 } else {
127 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
128 return false;
129 }
Wei Mi984ab0f2018-03-07 16:45:33 +0000130 // Find call targets and their sample counts.
131 // Note: In some cases, there are symbols in the profile which are not
132 // mangled. To accommodate such cases, use colon + integer pairs as the
133 // anchor points.
134 // An example:
135 // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
136 // ":1000" and ":437" are used as anchor points so the string above will
137 // be interpreted as
138 // target: _M_construct<char *>
139 // count: 1000
140 // target: string_view<std::allocator<char> >
141 // count: 437
Dehao Chen67226882015-09-30 00:42:46 +0000142 while (n3 != StringRef::npos) {
143 n3 += Rest.substr(n3).find_first_not_of(' ');
144 Rest = Rest.substr(n3);
Wei Mi984ab0f2018-03-07 16:45:33 +0000145 n3 = Rest.find_first_of(':');
146 if (n3 == StringRef::npos || n3 == 0)
Dehao Chen67226882015-09-30 00:42:46 +0000147 return false;
Wei Mi984ab0f2018-03-07 16:45:33 +0000148
149 StringRef Target;
150 uint64_t count, n4;
151 while (true) {
152 // Get the segment after the current colon.
153 StringRef AfterColon = Rest.substr(n3 + 1);
154 // Get the target symbol before the current colon.
155 Target = Rest.substr(0, n3);
156 // Check if the word after the current colon is an integer.
157 n4 = AfterColon.find_first_of(' ');
158 n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
159 StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
160 if (!WordAfterColon.getAsInteger(10, count))
161 break;
162
163 // Try to find the next colon.
164 uint64_t n5 = AfterColon.find_first_of(':');
165 if (n5 == StringRef::npos)
166 return false;
167 n3 += n5 + 1;
168 }
169
170 // An anchor point is found. Save the {target, count} pair
171 TargetCountMap[Target] = count;
172 if (n4 == Rest.size())
173 break;
174 // Change n3 to the next blank space after colon + integer pair.
175 n3 = n4;
Dehao Chen67226882015-09-30 00:42:46 +0000176 }
177 } else {
178 IsCallsite = true;
Diego Novillo38be3332015-10-15 16:36:21 +0000179 size_t n3 = Rest.find_last_of(':');
Dehao Chen67226882015-09-30 00:42:46 +0000180 CalleeName = Rest.substr(0, n3);
181 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
182 return false;
183 }
184 return true;
185}
186
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000187/// Load samples from a text file.
Diego Novillode1ab262014-09-09 12:40:50 +0000188///
189/// See the documentation at the top of the file for an explanation of
190/// the expected format.
191///
192/// \returns true if the file was loaded successfully, false otherwise.
Diego Novilloc572e922014-10-30 18:00:06 +0000193std::error_code SampleProfileReaderText::read() {
194 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000195 sampleprof_error Result = sampleprof_error::success;
Diego Novillode1ab262014-09-09 12:40:50 +0000196
Diego Novilloaae1ed82015-10-08 19:40:37 +0000197 InlineCallStack InlineStack;
Dehao Chen67226882015-09-30 00:42:46 +0000198
199 for (; !LineIt.is_at_eof(); ++LineIt) {
200 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
201 continue;
Diego Novillode1ab262014-09-09 12:40:50 +0000202 // Read the header of each function.
203 //
204 // Note that for function identifiers we are actually expecting
205 // mangled names, but we may not always get them. This happens when
206 // the compiler decides not to emit the function (e.g., it was inlined
207 // and removed). In this case, the binary will not have the linkage
208 // name for the function, so the profiler will emit the function's
209 // unmangled name, which may contain characters like ':' and '>' in its
210 // name (member functions, templates, etc).
211 //
212 // The only requirement we place on the identifier, then, is that it
213 // should not begin with a number.
Dehao Chen67226882015-09-30 00:42:46 +0000214 if ((*LineIt)[0] != ' ') {
Diego Novillo38be3332015-10-15 16:36:21 +0000215 uint64_t NumSamples, NumHeadSamples;
Dehao Chen67226882015-09-30 00:42:46 +0000216 StringRef FName;
217 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
218 reportError(LineIt.line_number(),
219 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
220 return sampleprof_error::malformed;
221 }
222 Profiles[FName] = FunctionSamples();
223 FunctionSamples &FProfile = Profiles[FName];
Dehao Chen57d1dda2016-03-03 18:09:32 +0000224 FProfile.setName(FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000225 MergeResult(Result, FProfile.addTotalSamples(NumSamples));
226 MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
Dehao Chen67226882015-09-30 00:42:46 +0000227 InlineStack.clear();
228 InlineStack.push_back(&FProfile);
229 } else {
Diego Novillo38be3332015-10-15 16:36:21 +0000230 uint64_t NumSamples;
Dehao Chen67226882015-09-30 00:42:46 +0000231 StringRef FName;
Diego Novillo38be3332015-10-15 16:36:21 +0000232 DenseMap<StringRef, uint64_t> TargetCountMap;
Dehao Chen67226882015-09-30 00:42:46 +0000233 bool IsCallsite;
Diego Novillo38be3332015-10-15 16:36:21 +0000234 uint32_t Depth, LineOffset, Discriminator;
Dehao Chen67226882015-09-30 00:42:46 +0000235 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
236 Discriminator, FName, TargetCountMap)) {
Diego Novillo3376a782015-09-17 00:17:24 +0000237 reportError(LineIt.line_number(),
238 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
239 *LineIt);
Diego Novilloc572e922014-10-30 18:00:06 +0000240 return sampleprof_error::malformed;
Diego Novillode1ab262014-09-09 12:40:50 +0000241 }
Dehao Chen67226882015-09-30 00:42:46 +0000242 if (IsCallsite) {
243 while (InlineStack.size() > Depth) {
244 InlineStack.pop_back();
Diego Novilloc572e922014-10-30 18:00:06 +0000245 }
Dehao Chen67226882015-09-30 00:42:46 +0000246 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000247 LineLocation(LineOffset, Discriminator))[FName];
Dehao Chen57d1dda2016-03-03 18:09:32 +0000248 FSamples.setName(FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000249 MergeResult(Result, FSamples.addTotalSamples(NumSamples));
Dehao Chen67226882015-09-30 00:42:46 +0000250 InlineStack.push_back(&FSamples);
251 } else {
252 while (InlineStack.size() > Depth) {
253 InlineStack.pop_back();
254 }
255 FunctionSamples &FProfile = *InlineStack.back();
256 for (const auto &name_count : TargetCountMap) {
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000257 MergeResult(Result, FProfile.addCalledTargetSamples(
258 LineOffset, Discriminator, name_count.first,
259 name_count.second));
Dehao Chen67226882015-09-30 00:42:46 +0000260 }
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000261 MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
262 NumSamples));
Diego Novilloc572e922014-10-30 18:00:06 +0000263 }
Diego Novillode1ab262014-09-09 12:40:50 +0000264 }
265 }
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000266 if (Result == sampleprof_error::success)
267 computeSummary();
Diego Novillode1ab262014-09-09 12:40:50 +0000268
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000269 return Result;
Diego Novillode1ab262014-09-09 12:40:50 +0000270}
271
Nathan Slingerland4f823662015-11-13 03:47:58 +0000272bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
273 bool result = false;
274
275 // Check that the first non-comment line is a valid function header.
276 line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
277 if (!LineIt.is_at_eof()) {
278 if ((*LineIt)[0] != ' ') {
279 uint64_t NumSamples, NumHeadSamples;
280 StringRef FName;
281 result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
282 }
283 }
284
285 return result;
286}
287
Diego Novillod5336ae2014-11-01 00:56:55 +0000288template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
Diego Novilloc572e922014-10-30 18:00:06 +0000289 unsigned NumBytesRead = 0;
290 std::error_code EC;
291 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
292
293 if (Val > std::numeric_limits<T>::max())
294 EC = sampleprof_error::malformed;
295 else if (Data + NumBytesRead > End)
296 EC = sampleprof_error::truncated;
297 else
298 EC = sampleprof_error::success;
299
300 if (EC) {
Diego Novillo3376a782015-09-17 00:17:24 +0000301 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000302 return EC;
303 }
304
305 Data += NumBytesRead;
306 return static_cast<T>(Val);
307}
308
309ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
310 std::error_code EC;
311 StringRef Str(reinterpret_cast<const char *>(Data));
312 if (Data + Str.size() + 1 > End) {
313 EC = sampleprof_error::truncated;
Diego Novillo3376a782015-09-17 00:17:24 +0000314 reportError(0, EC.message());
Diego Novilloc572e922014-10-30 18:00:06 +0000315 return EC;
316 }
317
318 Data += Str.size() + 1;
319 return Str;
320}
321
Diego Novillo760c5a82015-10-13 22:48:46 +0000322ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
323 std::error_code EC;
Diego Novillo38be3332015-10-15 16:36:21 +0000324 auto Idx = readNumber<uint32_t>();
Diego Novillo760c5a82015-10-13 22:48:46 +0000325 if (std::error_code EC = Idx.getError())
326 return EC;
327 if (*Idx >= NameTable.size())
328 return sampleprof_error::truncated_name_table;
329 return NameTable[*Idx];
330}
331
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000332std::error_code
333SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
Diego Novillob93483d2015-10-16 18:54:35 +0000334 auto NumSamples = readNumber<uint64_t>();
335 if (std::error_code EC = NumSamples.getError())
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000336 return EC;
Diego Novillob93483d2015-10-16 18:54:35 +0000337 FProfile.addTotalSamples(*NumSamples);
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000338
339 // Read the samples in the body.
Diego Novillo38be3332015-10-15 16:36:21 +0000340 auto NumRecords = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000341 if (std::error_code EC = NumRecords.getError())
342 return EC;
343
Diego Novillo38be3332015-10-15 16:36:21 +0000344 for (uint32_t I = 0; I < *NumRecords; ++I) {
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000345 auto LineOffset = readNumber<uint64_t>();
346 if (std::error_code EC = LineOffset.getError())
347 return EC;
348
Dehao Chen10042412015-10-21 01:22:27 +0000349 if (!isOffsetLegal(*LineOffset)) {
350 return std::error_code();
351 }
352
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000353 auto Discriminator = readNumber<uint64_t>();
354 if (std::error_code EC = Discriminator.getError())
355 return EC;
356
357 auto NumSamples = readNumber<uint64_t>();
358 if (std::error_code EC = NumSamples.getError())
359 return EC;
360
Diego Novillo38be3332015-10-15 16:36:21 +0000361 auto NumCalls = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000362 if (std::error_code EC = NumCalls.getError())
363 return EC;
364
Diego Novillo38be3332015-10-15 16:36:21 +0000365 for (uint32_t J = 0; J < *NumCalls; ++J) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000366 auto CalledFunction(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000367 if (std::error_code EC = CalledFunction.getError())
368 return EC;
369
370 auto CalledFunctionSamples = readNumber<uint64_t>();
371 if (std::error_code EC = CalledFunctionSamples.getError())
372 return EC;
373
374 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
375 *CalledFunction, *CalledFunctionSamples);
376 }
377
378 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
379 }
380
381 // Read all the samples for inlined function calls.
Diego Novillo38be3332015-10-15 16:36:21 +0000382 auto NumCallsites = readNumber<uint32_t>();
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000383 if (std::error_code EC = NumCallsites.getError())
384 return EC;
385
Diego Novillo38be3332015-10-15 16:36:21 +0000386 for (uint32_t J = 0; J < *NumCallsites; ++J) {
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000387 auto LineOffset = readNumber<uint64_t>();
388 if (std::error_code EC = LineOffset.getError())
389 return EC;
390
391 auto Discriminator = readNumber<uint64_t>();
392 if (std::error_code EC = Discriminator.getError())
393 return EC;
394
Diego Novillo760c5a82015-10-13 22:48:46 +0000395 auto FName(readStringFromTable());
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000396 if (std::error_code EC = FName.getError())
397 return EC;
398
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000399 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
400 LineLocation(*LineOffset, *Discriminator))[*FName];
Dehao Chen57d1dda2016-03-03 18:09:32 +0000401 CalleeProfile.setName(*FName);
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000402 if (std::error_code EC = readProfile(CalleeProfile))
403 return EC;
404 }
405
406 return sampleprof_error::success;
407}
408
Diego Novilloc572e922014-10-30 18:00:06 +0000409std::error_code SampleProfileReaderBinary::read() {
410 while (!at_eof()) {
Diego Novillob93483d2015-10-16 18:54:35 +0000411 auto NumHeadSamples = readNumber<uint64_t>();
412 if (std::error_code EC = NumHeadSamples.getError())
413 return EC;
414
Diego Novillo760c5a82015-10-13 22:48:46 +0000415 auto FName(readStringFromTable());
Diego Novilloc572e922014-10-30 18:00:06 +0000416 if (std::error_code EC = FName.getError())
417 return EC;
418
419 Profiles[*FName] = FunctionSamples();
420 FunctionSamples &FProfile = Profiles[*FName];
Dehao Chen57d1dda2016-03-03 18:09:32 +0000421 FProfile.setName(*FName);
Diego Novilloc572e922014-10-30 18:00:06 +0000422
Diego Novillob93483d2015-10-16 18:54:35 +0000423 FProfile.addHeadSamples(*NumHeadSamples);
424
Diego Novilloa7f1e8e2015-10-09 17:54:24 +0000425 if (std::error_code EC = readProfile(FProfile))
Diego Novilloc572e922014-10-30 18:00:06 +0000426 return EC;
Diego Novilloc572e922014-10-30 18:00:06 +0000427 }
428
429 return sampleprof_error::success;
430}
431
432std::error_code SampleProfileReaderBinary::readHeader() {
433 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
434 End = Data + Buffer->getBufferSize();
435
436 // Read and check the magic identifier.
437 auto Magic = readNumber<uint64_t>();
438 if (std::error_code EC = Magic.getError())
439 return EC;
440 else if (*Magic != SPMagic())
441 return sampleprof_error::bad_magic;
442
443 // Read the version number.
444 auto Version = readNumber<uint64_t>();
445 if (std::error_code EC = Version.getError())
446 return EC;
447 else if (*Version != SPVersion())
448 return sampleprof_error::unsupported_version;
449
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000450 if (std::error_code EC = readSummary())
451 return EC;
452
Diego Novillo760c5a82015-10-13 22:48:46 +0000453 // Read the name table.
Diego Novillo38be3332015-10-15 16:36:21 +0000454 auto Size = readNumber<uint32_t>();
Diego Novillo760c5a82015-10-13 22:48:46 +0000455 if (std::error_code EC = Size.getError())
456 return EC;
457 NameTable.reserve(*Size);
Diego Novillo38be3332015-10-15 16:36:21 +0000458 for (uint32_t I = 0; I < *Size; ++I) {
Diego Novillo760c5a82015-10-13 22:48:46 +0000459 auto Name(readString());
460 if (std::error_code EC = Name.getError())
461 return EC;
462 NameTable.push_back(*Name);
463 }
464
Diego Novilloc572e922014-10-30 18:00:06 +0000465 return sampleprof_error::success;
466}
467
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000468std::error_code SampleProfileReaderBinary::readSummaryEntry(
469 std::vector<ProfileSummaryEntry> &Entries) {
470 auto Cutoff = readNumber<uint64_t>();
471 if (std::error_code EC = Cutoff.getError())
472 return EC;
473
474 auto MinBlockCount = readNumber<uint64_t>();
475 if (std::error_code EC = MinBlockCount.getError())
476 return EC;
477
478 auto NumBlocks = readNumber<uint64_t>();
479 if (std::error_code EC = NumBlocks.getError())
480 return EC;
481
482 Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
483 return sampleprof_error::success;
484}
485
486std::error_code SampleProfileReaderBinary::readSummary() {
487 auto TotalCount = readNumber<uint64_t>();
488 if (std::error_code EC = TotalCount.getError())
489 return EC;
490
491 auto MaxBlockCount = readNumber<uint64_t>();
492 if (std::error_code EC = MaxBlockCount.getError())
493 return EC;
494
495 auto MaxFunctionCount = readNumber<uint64_t>();
496 if (std::error_code EC = MaxFunctionCount.getError())
497 return EC;
498
499 auto NumBlocks = readNumber<uint64_t>();
500 if (std::error_code EC = NumBlocks.getError())
501 return EC;
502
503 auto NumFunctions = readNumber<uint64_t>();
504 if (std::error_code EC = NumFunctions.getError())
505 return EC;
506
507 auto NumSummaryEntries = readNumber<uint64_t>();
508 if (std::error_code EC = NumSummaryEntries.getError())
509 return EC;
510
511 std::vector<ProfileSummaryEntry> Entries;
512 for (unsigned i = 0; i < *NumSummaryEntries; i++) {
513 std::error_code EC = readSummaryEntry(Entries);
514 if (EC != sampleprof_error::success)
515 return EC;
516 }
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000517 Summary = llvm::make_unique<ProfileSummary>(
518 ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
519 *MaxFunctionCount, *NumBlocks, *NumFunctions);
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000520
521 return sampleprof_error::success;
522}
523
Diego Novilloc572e922014-10-30 18:00:06 +0000524bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
525 const uint8_t *Data =
526 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
527 uint64_t Magic = decodeULEB128(Data);
528 return Magic == SPMagic();
529}
530
Diego Novillo3376a782015-09-17 00:17:24 +0000531std::error_code SampleProfileReaderGCC::skipNextWord() {
532 uint32_t dummy;
533 if (!GcovBuffer.readInt(dummy))
534 return sampleprof_error::truncated;
535 return sampleprof_error::success;
536}
537
538template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
539 if (sizeof(T) <= sizeof(uint32_t)) {
540 uint32_t Val;
541 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
542 return static_cast<T>(Val);
543 } else if (sizeof(T) <= sizeof(uint64_t)) {
544 uint64_t Val;
545 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
546 return static_cast<T>(Val);
547 }
548
549 std::error_code EC = sampleprof_error::malformed;
550 reportError(0, EC.message());
551 return EC;
552}
553
554ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
555 StringRef Str;
556 if (!GcovBuffer.readString(Str))
557 return sampleprof_error::truncated;
558 return Str;
559}
560
561std::error_code SampleProfileReaderGCC::readHeader() {
562 // Read the magic identifier.
563 if (!GcovBuffer.readGCDAFormat())
564 return sampleprof_error::unrecognized_format;
565
566 // Read the version number. Note - the GCC reader does not validate this
567 // version, but the profile creator generates v704.
568 GCOV::GCOVVersion version;
569 if (!GcovBuffer.readGCOVVersion(version))
570 return sampleprof_error::unrecognized_format;
571
572 if (version != GCOV::V704)
573 return sampleprof_error::unsupported_version;
574
575 // Skip the empty integer.
576 if (std::error_code EC = skipNextWord())
577 return EC;
578
579 return sampleprof_error::success;
580}
581
582std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
583 uint32_t Tag;
584 if (!GcovBuffer.readInt(Tag))
585 return sampleprof_error::truncated;
586
587 if (Tag != Expected)
588 return sampleprof_error::malformed;
589
590 if (std::error_code EC = skipNextWord())
591 return EC;
592
593 return sampleprof_error::success;
594}
595
596std::error_code SampleProfileReaderGCC::readNameTable() {
597 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
598 return EC;
599
600 uint32_t Size;
601 if (!GcovBuffer.readInt(Size))
602 return sampleprof_error::truncated;
603
604 for (uint32_t I = 0; I < Size; ++I) {
605 StringRef Str;
606 if (!GcovBuffer.readString(Str))
607 return sampleprof_error::truncated;
608 Names.push_back(Str);
609 }
610
611 return sampleprof_error::success;
612}
613
614std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
615 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
616 return EC;
617
618 uint32_t NumFunctions;
619 if (!GcovBuffer.readInt(NumFunctions))
620 return sampleprof_error::truncated;
621
Diego Novilloaae1ed82015-10-08 19:40:37 +0000622 InlineCallStack Stack;
Diego Novillo3376a782015-09-17 00:17:24 +0000623 for (uint32_t I = 0; I < NumFunctions; ++I)
Diego Novilloaae1ed82015-10-08 19:40:37 +0000624 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
Diego Novillo3376a782015-09-17 00:17:24 +0000625 return EC;
626
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000627 computeSummary();
Diego Novillo3376a782015-09-17 00:17:24 +0000628 return sampleprof_error::success;
629}
630
Diego Novilloaae1ed82015-10-08 19:40:37 +0000631std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
632 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
Diego Novillo3376a782015-09-17 00:17:24 +0000633 uint64_t HeadCount = 0;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000634 if (InlineStack.size() == 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000635 if (!GcovBuffer.readInt64(HeadCount))
636 return sampleprof_error::truncated;
637
638 uint32_t NameIdx;
639 if (!GcovBuffer.readInt(NameIdx))
640 return sampleprof_error::truncated;
641
642 StringRef Name(Names[NameIdx]);
643
644 uint32_t NumPosCounts;
645 if (!GcovBuffer.readInt(NumPosCounts))
646 return sampleprof_error::truncated;
647
Diego Novilloaae1ed82015-10-08 19:40:37 +0000648 uint32_t NumCallsites;
649 if (!GcovBuffer.readInt(NumCallsites))
Diego Novillo3376a782015-09-17 00:17:24 +0000650 return sampleprof_error::truncated;
651
Diego Novilloaae1ed82015-10-08 19:40:37 +0000652 FunctionSamples *FProfile = nullptr;
653 if (InlineStack.size() == 0) {
654 // If this is a top function that we have already processed, do not
655 // update its profile again. This happens in the presence of
656 // function aliases. Since these aliases share the same function
657 // body, there will be identical replicated profiles for the
658 // original function. In this case, we simply not bother updating
659 // the profile of the original function.
660 FProfile = &Profiles[Name];
661 FProfile->addHeadSamples(HeadCount);
662 if (FProfile->getTotalSamples() > 0)
Diego Novillo3376a782015-09-17 00:17:24 +0000663 Update = false;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000664 } else {
665 // Otherwise, we are reading an inlined instance. The top of the
666 // inline stack contains the profile of the caller. Insert this
667 // callee in the caller's CallsiteMap.
668 FunctionSamples *CallerProfile = InlineStack.front();
669 uint32_t LineOffset = Offset >> 16;
670 uint32_t Discriminator = Offset & 0xffff;
671 FProfile = &CallerProfile->functionSamplesAt(
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000672 LineLocation(LineOffset, Discriminator))[Name];
Diego Novillo3376a782015-09-17 00:17:24 +0000673 }
Dehao Chen57d1dda2016-03-03 18:09:32 +0000674 FProfile->setName(Name);
Diego Novillo3376a782015-09-17 00:17:24 +0000675
676 for (uint32_t I = 0; I < NumPosCounts; ++I) {
677 uint32_t Offset;
678 if (!GcovBuffer.readInt(Offset))
679 return sampleprof_error::truncated;
680
681 uint32_t NumTargets;
682 if (!GcovBuffer.readInt(NumTargets))
683 return sampleprof_error::truncated;
684
685 uint64_t Count;
686 if (!GcovBuffer.readInt64(Count))
687 return sampleprof_error::truncated;
688
Diego Novilloaae1ed82015-10-08 19:40:37 +0000689 // The line location is encoded in the offset as:
690 // high 16 bits: line offset to the start of the function.
691 // low 16 bits: discriminator.
692 uint32_t LineOffset = Offset >> 16;
693 uint32_t Discriminator = Offset & 0xffff;
Diego Novillo3376a782015-09-17 00:17:24 +0000694
Diego Novilloaae1ed82015-10-08 19:40:37 +0000695 InlineCallStack NewStack;
696 NewStack.push_back(FProfile);
697 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
698 if (Update) {
699 // Walk up the inline stack, adding the samples on this line to
700 // the total sample count of the callers in the chain.
701 for (auto CallerProfile : NewStack)
702 CallerProfile->addTotalSamples(Count);
703
704 // Update the body samples for the current profile.
705 FProfile->addBodySamples(LineOffset, Discriminator, Count);
706 }
707
708 // Process the list of functions called at an indirect call site.
709 // These are all the targets that a function pointer (or virtual
710 // function) resolved at runtime.
Diego Novillo3376a782015-09-17 00:17:24 +0000711 for (uint32_t J = 0; J < NumTargets; J++) {
712 uint32_t HistVal;
713 if (!GcovBuffer.readInt(HistVal))
714 return sampleprof_error::truncated;
715
716 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
717 return sampleprof_error::malformed;
718
719 uint64_t TargetIdx;
720 if (!GcovBuffer.readInt64(TargetIdx))
721 return sampleprof_error::truncated;
722 StringRef TargetName(Names[TargetIdx]);
723
724 uint64_t TargetCount;
725 if (!GcovBuffer.readInt64(TargetCount))
726 return sampleprof_error::truncated;
727
Dehao Chen920677a2017-02-22 17:27:21 +0000728 if (Update)
729 FProfile->addCalledTargetSamples(LineOffset, Discriminator,
730 TargetName, TargetCount);
Diego Novillo3376a782015-09-17 00:17:24 +0000731 }
732 }
733
Diego Novilloaae1ed82015-10-08 19:40:37 +0000734 // Process all the inlined callers into the current function. These
735 // are all the callsites that were inlined into this function.
736 for (uint32_t I = 0; I < NumCallsites; I++) {
Diego Novillo3376a782015-09-17 00:17:24 +0000737 // The offset is encoded as:
738 // high 16 bits: line offset to the start of the function.
739 // low 16 bits: discriminator.
740 uint32_t Offset;
741 if (!GcovBuffer.readInt(Offset))
742 return sampleprof_error::truncated;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000743 InlineCallStack NewStack;
744 NewStack.push_back(FProfile);
745 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
746 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
Diego Novillo3376a782015-09-17 00:17:24 +0000747 return EC;
748 }
749
750 return sampleprof_error::success;
751}
752
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000753/// Read a GCC AutoFDO profile.
Diego Novillo3376a782015-09-17 00:17:24 +0000754///
755/// This format is generated by the Linux Perf conversion tool at
756/// https://github.com/google/autofdo.
757std::error_code SampleProfileReaderGCC::read() {
758 // Read the string table.
759 if (std::error_code EC = readNameTable())
760 return EC;
761
762 // Read the source profile.
763 if (std::error_code EC = readFunctionProfiles())
764 return EC;
765
Diego Novillo3376a782015-09-17 00:17:24 +0000766 return sampleprof_error::success;
767}
768
769bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
770 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
771 return Magic == "adcg*704";
772}
773
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000774/// Prepare a memory buffer for the contents of \p Filename.
Diego Novillode1ab262014-09-09 12:40:50 +0000775///
Diego Novilloc572e922014-10-30 18:00:06 +0000776/// \returns an error code indicating the status of the buffer.
Diego Novillofcd55602014-11-03 00:51:45 +0000777static ErrorOr<std::unique_ptr<MemoryBuffer>>
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000778setupMemoryBuffer(const Twine &Filename) {
Diego Novilloc572e922014-10-30 18:00:06 +0000779 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
780 if (std::error_code EC = BufferOrErr.getError())
781 return EC;
Diego Novillofcd55602014-11-03 00:51:45 +0000782 auto Buffer = std::move(BufferOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000783
784 // Sanity check the file.
Zachary Turner260fe3e2017-12-14 22:07:03 +0000785 if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
Diego Novilloc572e922014-10-30 18:00:06 +0000786 return sampleprof_error::too_large;
787
Diego Novillofcd55602014-11-03 00:51:45 +0000788 return std::move(Buffer);
Diego Novilloc572e922014-10-30 18:00:06 +0000789}
790
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000791/// Create a sample profile reader based on the format of the input file.
Diego Novilloc572e922014-10-30 18:00:06 +0000792///
793/// \param Filename The file to open.
794///
Diego Novilloc572e922014-10-30 18:00:06 +0000795/// \param C The LLVM context to use to emit diagnostics.
796///
797/// \returns an error code indicating the status of the created reader.
Diego Novillofcd55602014-11-03 00:51:45 +0000798ErrorOr<std::unique_ptr<SampleProfileReader>>
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000799SampleProfileReader::create(const Twine &Filename, LLVMContext &C) {
Diego Novillofcd55602014-11-03 00:51:45 +0000800 auto BufferOrError = setupMemoryBuffer(Filename);
801 if (std::error_code EC = BufferOrError.getError())
Diego Novilloc572e922014-10-30 18:00:06 +0000802 return EC;
Nathan Slingerland51abea72015-12-10 17:21:42 +0000803 return create(BufferOrError.get(), C);
804}
Diego Novilloc572e922014-10-30 18:00:06 +0000805
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000806/// Create a sample profile reader based on the format of the input data.
Nathan Slingerland51abea72015-12-10 17:21:42 +0000807///
808/// \param B The memory buffer to create the reader from (assumes ownership).
809///
Nathan Slingerland51abea72015-12-10 17:21:42 +0000810/// \param C The LLVM context to use to emit diagnostics.
811///
812/// \returns an error code indicating the status of the created reader.
813ErrorOr<std::unique_ptr<SampleProfileReader>>
814SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
Diego Novillofcd55602014-11-03 00:51:45 +0000815 std::unique_ptr<SampleProfileReader> Reader;
Nathan Slingerland51abea72015-12-10 17:21:42 +0000816 if (SampleProfileReaderBinary::hasFormat(*B))
817 Reader.reset(new SampleProfileReaderBinary(std::move(B), C));
818 else if (SampleProfileReaderGCC::hasFormat(*B))
819 Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
820 else if (SampleProfileReaderText::hasFormat(*B))
821 Reader.reset(new SampleProfileReaderText(std::move(B), C));
Nathan Slingerland4f823662015-11-13 03:47:58 +0000822 else
823 return sampleprof_error::unrecognized_format;
Diego Novilloc572e922014-10-30 18:00:06 +0000824
Diego Novillofcd55602014-11-03 00:51:45 +0000825 if (std::error_code EC = Reader->readHeader())
826 return EC;
827
828 return std::move(Reader);
Diego Novillode1ab262014-09-09 12:40:50 +0000829}
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000830
831// For text and GCC file formats, we compute the summary after reading the
832// profile. Binary format has the profile summary in its header.
833void SampleProfileReader::computeSummary() {
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000834 SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000835 for (const auto &I : Profiles) {
836 const FunctionSamples &Profile = I.second;
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000837 Builder.addRecord(Profile);
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000838 }
Benjamin Kramer38de59e2016-05-20 09:18:37 +0000839 Summary = Builder.getSummary();
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000840}