LLVM 22.0.0git
SampleProfReader.cpp
Go to the documentation of this file.
1//===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class that reads LLVM sample profiles. It
10// supports three file formats: text, binary and gcov.
11//
12// The textual representation is useful for debugging and testing purposes. The
13// binary representation is more compact, resulting in smaller file sizes.
14//
15// The gcov encoding is the one generated by GCC's AutoFDO profile creation
16// tool (https://github.com/google/autofdo)
17//
18// All three encodings can be used interchangeably as an input sample profile.
19//
20//===----------------------------------------------------------------------===//
21
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/IR/Module.h"
33#include "llvm/Support/JSON.h"
34#include "llvm/Support/LEB128.h"
36#include "llvm/Support/MD5.h"
40#include <algorithm>
41#include <cstddef>
42#include <cstdint>
43#include <limits>
44#include <memory>
45#include <system_error>
46#include <vector>
47
48using namespace llvm;
49using namespace sampleprof;
50
51#define DEBUG_TYPE "samplepgo-reader"
52
53// This internal option specifies if the profile uses FS discriminators.
54// It only applies to text, and binary format profiles.
55// For ext-binary format profiles, the flag is set in the summary.
57 "profile-isfs", cl::Hidden, cl::init(false),
58 cl::desc("Profile uses flow sensitive discriminators"));
59
60/// Dump the function profile for \p FName.
61///
62/// \param FContext Name + context of the function to print.
63/// \param OS Stream to emit the output to.
65 raw_ostream &OS) {
66 OS << "Function: " << FS.getContext().toString() << ": " << FS;
67}
68
69/// Dump all the function profiles found on stream \p OS.
71 std::vector<NameFunctionSamples> V;
73 for (const auto &I : V)
74 dumpFunctionProfile(*I.second, OS);
75}
76
78 json::OStream &JOS, bool TopLevel = false) {
79 auto DumpBody = [&](const BodySampleMap &BodySamples) {
80 for (const auto &I : BodySamples) {
81 const LineLocation &Loc = I.first;
82 const SampleRecord &Sample = I.second;
83 JOS.object([&] {
84 JOS.attribute("line", Loc.LineOffset);
85 if (Loc.Discriminator)
86 JOS.attribute("discriminator", Loc.Discriminator);
87 JOS.attribute("samples", Sample.getSamples());
88
89 auto CallTargets = Sample.getSortedCallTargets();
90 if (!CallTargets.empty()) {
91 JOS.attributeArray("calls", [&] {
92 for (const auto &J : CallTargets) {
93 JOS.object([&] {
94 JOS.attribute("function", J.first.str());
95 JOS.attribute("samples", J.second);
96 });
97 }
98 });
99 }
100 });
101 }
102 };
103
104 auto DumpCallsiteSamples = [&](const CallsiteSampleMap &CallsiteSamples) {
105 for (const auto &I : CallsiteSamples)
106 for (const auto &FS : I.second) {
107 const LineLocation &Loc = I.first;
108 const FunctionSamples &CalleeSamples = FS.second;
109 JOS.object([&] {
110 JOS.attribute("line", Loc.LineOffset);
111 if (Loc.Discriminator)
112 JOS.attribute("discriminator", Loc.Discriminator);
113 JOS.attributeArray(
114 "samples", [&] { dumpFunctionProfileJson(CalleeSamples, JOS); });
115 });
116 }
117 };
118
119 JOS.object([&] {
120 JOS.attribute("name", S.getFunction().str());
121 JOS.attribute("total", S.getTotalSamples());
122 if (TopLevel)
123 JOS.attribute("head", S.getHeadSamples());
124
125 const auto &BodySamples = S.getBodySamples();
126 if (!BodySamples.empty())
127 JOS.attributeArray("body", [&] { DumpBody(BodySamples); });
128
129 const auto &CallsiteSamples = S.getCallsiteSamples();
130 if (!CallsiteSamples.empty())
131 JOS.attributeArray("callsites",
132 [&] { DumpCallsiteSamples(CallsiteSamples); });
133 });
134}
135
136/// Dump all the function profiles found on stream \p OS in the JSON format.
138 std::vector<NameFunctionSamples> V;
140 json::OStream JOS(OS, 2);
141 JOS.arrayBegin();
142 for (const auto &F : V)
143 dumpFunctionProfileJson(*F.second, JOS, true);
144 JOS.arrayEnd();
145
146 // Emit a newline character at the end as json::OStream doesn't emit one.
147 OS << "\n";
148}
149
150/// Parse \p Input as function head.
151///
152/// Parse one line of \p Input, and update function name in \p FName,
153/// function's total sample count in \p NumSamples, function's entry
154/// count in \p NumHeadSamples.
155///
156/// \returns true if parsing is successful.
157static bool ParseHead(const StringRef &Input, StringRef &FName,
158 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
159 if (Input[0] == ' ')
160 return false;
161 size_t n2 = Input.rfind(':');
162 size_t n1 = Input.rfind(':', n2 - 1);
163 FName = Input.substr(0, n1);
164 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
165 return false;
166 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
167 return false;
168 return true;
169}
170
171/// Returns true if line offset \p L is legal (only has 16 bits).
172static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
173
174/// Parse \p Input that contains metadata.
175/// Possible metadata:
176/// - CFG Checksum information:
177/// !CFGChecksum: 12345
178/// - CFG Checksum information:
179/// !Attributes: 1
180/// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
181static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash,
182 uint32_t &Attributes) {
183 if (Input.starts_with("!CFGChecksum:")) {
184 StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
185 return !CFGInfo.getAsInteger(10, FunctionHash);
186 }
187
188 if (Input.starts_with("!Attributes:")) {
189 StringRef Attrib = Input.substr(strlen("!Attributes:")).trim();
190 return !Attrib.getAsInteger(10, Attributes);
191 }
192
193 return false;
194}
195
196enum class LineType {
199 Metadata,
200};
201
202/// Parse \p Input as line sample.
203///
204/// \param Input input line.
205/// \param LineTy Type of this line.
206/// \param Depth the depth of the inline stack.
207/// \param NumSamples total samples of the line/inlined callsite.
208/// \param LineOffset line offset to the start of the function.
209/// \param Discriminator discriminator of the line.
210/// \param TargetCountMap map from indirect call target to count.
211/// \param FunctionHash the function's CFG hash, used by pseudo probe.
212///
213/// returns true if parsing is successful.
214static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
215 uint64_t &NumSamples, uint32_t &LineOffset,
216 uint32_t &Discriminator, StringRef &CalleeName,
217 DenseMap<StringRef, uint64_t> &TargetCountMap,
218 uint64_t &FunctionHash, uint32_t &Attributes,
219 bool &IsFlat) {
220 for (Depth = 0; Input[Depth] == ' '; Depth++)
221 ;
222 if (Depth == 0)
223 return false;
224
225 if (Input[Depth] == '!') {
226 LineTy = LineType::Metadata;
227 // This metadata is only for manual inspection only. We already created a
228 // FunctionSamples and put it in the profile map, so there is no point
229 // to skip profiles even they have no use for ThinLTO.
230 if (Input == StringRef(" !Flat")) {
231 IsFlat = true;
232 return true;
233 }
234 return parseMetadata(Input.substr(Depth), FunctionHash, Attributes);
235 }
236
237 size_t n1 = Input.find(':');
238 StringRef Loc = Input.substr(Depth, n1 - Depth);
239 size_t n2 = Loc.find('.');
240 if (n2 == StringRef::npos) {
241 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
242 return false;
243 Discriminator = 0;
244 } else {
245 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
246 return false;
247 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
248 return false;
249 }
250
251 StringRef Rest = Input.substr(n1 + 2);
252 if (isDigit(Rest[0])) {
253 LineTy = LineType::BodyProfile;
254 size_t n3 = Rest.find(' ');
255 if (n3 == StringRef::npos) {
256 if (Rest.getAsInteger(10, NumSamples))
257 return false;
258 } else {
259 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
260 return false;
261 }
262 // Find call targets and their sample counts.
263 // Note: In some cases, there are symbols in the profile which are not
264 // mangled. To accommodate such cases, use colon + integer pairs as the
265 // anchor points.
266 // An example:
267 // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
268 // ":1000" and ":437" are used as anchor points so the string above will
269 // be interpreted as
270 // target: _M_construct<char *>
271 // count: 1000
272 // target: string_view<std::allocator<char> >
273 // count: 437
274 while (n3 != StringRef::npos) {
275 n3 += Rest.substr(n3).find_first_not_of(' ');
276 Rest = Rest.substr(n3);
277 n3 = Rest.find_first_of(':');
278 if (n3 == StringRef::npos || n3 == 0)
279 return false;
280
282 uint64_t count, n4;
283 while (true) {
284 // Get the segment after the current colon.
285 StringRef AfterColon = Rest.substr(n3 + 1);
286 // Get the target symbol before the current colon.
287 Target = Rest.substr(0, n3);
288 // Check if the word after the current colon is an integer.
289 n4 = AfterColon.find_first_of(' ');
290 n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
291 StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
292 if (!WordAfterColon.getAsInteger(10, count))
293 break;
294
295 // Try to find the next colon.
296 uint64_t n5 = AfterColon.find_first_of(':');
297 if (n5 == StringRef::npos)
298 return false;
299 n3 += n5 + 1;
300 }
301
302 // An anchor point is found. Save the {target, count} pair
303 TargetCountMap[Target] = count;
304 if (n4 == Rest.size())
305 break;
306 // Change n3 to the next blank space after colon + integer pair.
307 n3 = n4;
308 }
309 } else {
310 LineTy = LineType::CallSiteProfile;
311 size_t n3 = Rest.find_last_of(':');
312 CalleeName = Rest.substr(0, n3);
313 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
314 return false;
315 }
316 return true;
317}
318
319/// Load samples from a text file.
320///
321/// See the documentation at the top of the file for an explanation of
322/// the expected format.
323///
324/// \returns true if the file was loaded successfully, false otherwise.
326 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
328
329 InlineCallStack InlineStack;
330 uint32_t TopLevelProbeProfileCount = 0;
331
332 // DepthMetadata tracks whether we have processed metadata for the current
333 // top-level or nested function profile.
334 uint32_t DepthMetadata = 0;
335
336 std::vector<SampleContext *> FlatSamples;
337
340 for (; !LineIt.is_at_eof(); ++LineIt) {
341 size_t pos = LineIt->find_first_not_of(' ');
342 if (pos == LineIt->npos || (*LineIt)[pos] == '#')
343 continue;
344 // Read the header of each function.
345 //
346 // Note that for function identifiers we are actually expecting
347 // mangled names, but we may not always get them. This happens when
348 // the compiler decides not to emit the function (e.g., it was inlined
349 // and removed). In this case, the binary will not have the linkage
350 // name for the function, so the profiler will emit the function's
351 // unmangled name, which may contain characters like ':' and '>' in its
352 // name (member functions, templates, etc).
353 //
354 // The only requirement we place on the identifier, then, is that it
355 // should not begin with a number.
356 if ((*LineIt)[0] != ' ') {
357 uint64_t NumSamples, NumHeadSamples;
358 StringRef FName;
359 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
360 reportError(LineIt.line_number(),
361 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
363 }
364 DepthMetadata = 0;
365 SampleContext FContext(FName, CSNameTable);
366 if (FContext.hasContext())
368 FunctionSamples &FProfile = Profiles.create(FContext);
369 mergeSampleProfErrors(Result, FProfile.addTotalSamples(NumSamples));
370 mergeSampleProfErrors(Result, FProfile.addHeadSamples(NumHeadSamples));
371 InlineStack.clear();
372 InlineStack.push_back(&FProfile);
373 } else {
374 uint64_t NumSamples;
375 StringRef FName;
376 DenseMap<StringRef, uint64_t> TargetCountMap;
377 uint32_t Depth, LineOffset, Discriminator;
378 LineType LineTy = LineType::BodyProfile;
379 uint64_t FunctionHash = 0;
381 bool IsFlat = false;
382 if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
383 Discriminator, FName, TargetCountMap, FunctionHash,
384 Attributes, IsFlat)) {
385 switch (LineTy) {
386 case LineType::Metadata:
387 reportError(LineIt.line_number(),
388 "Cannot parse metadata: " + *LineIt);
389 break;
390 default:
391 reportError(LineIt.line_number(),
392 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
393 *LineIt);
394 }
396 }
397 if (LineTy != LineType::Metadata && Depth == DepthMetadata) {
398 // Metadata must be put at the end of a function profile.
399 reportError(LineIt.line_number(),
400 "Found non-metadata after metadata: " + *LineIt);
402 }
403
404 // Here we handle FS discriminators.
405 Discriminator &= getDiscriminatorMask();
406
407 while (InlineStack.size() > Depth) {
408 InlineStack.pop_back();
409 }
410 switch (LineTy) {
411 case LineType::CallSiteProfile: {
412 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
413 LineLocation(LineOffset, Discriminator))[FunctionId(FName)];
414 FSamples.setFunction(FunctionId(FName));
415 mergeSampleProfErrors(Result, FSamples.addTotalSamples(NumSamples));
416 InlineStack.push_back(&FSamples);
417 DepthMetadata = 0;
418 break;
419 }
420 case LineType::BodyProfile: {
421 FunctionSamples &FProfile = *InlineStack.back();
422 for (const auto &name_count : TargetCountMap) {
424 LineOffset, Discriminator,
425 FunctionId(name_count.first),
426 name_count.second));
427 }
429 Result,
430 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples));
431 break;
432 }
433 case LineType::Metadata: {
434 FunctionSamples &FProfile = *InlineStack.back();
435 if (FunctionHash) {
436 FProfile.setFunctionHash(FunctionHash);
437 if (Depth == 1)
438 ++TopLevelProbeProfileCount;
439 }
442 ProfileIsPreInlined = true;
443 DepthMetadata = Depth;
444 if (IsFlat) {
445 if (Depth == 1)
446 FlatSamples.push_back(&FProfile.getContext());
447 else
449 Buffer->getBufferIdentifier(), LineIt.line_number(),
450 "!Flat may only be used at top level function.", DS_Warning));
451 }
452 break;
453 }
454 }
455 }
456 }
457
458 // Honor the option to skip flat functions. Since they are already added to
459 // the profile map, remove them all here.
460 if (SkipFlatProf)
461 for (SampleContext *FlatSample : FlatSamples)
462 Profiles.erase(*FlatSample);
463
464 assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
465 "Cannot have both context-sensitive and regular profile");
467 assert((TopLevelProbeProfileCount == 0 ||
468 TopLevelProbeProfileCount == Profiles.size()) &&
469 "Cannot have both probe-based profiles and regular profiles");
470 ProfileIsProbeBased = (TopLevelProbeProfileCount > 0);
474
475 if (Result == sampleprof_error::success)
477
478 return Result;
479}
480
482 bool result = false;
483
484 // Check that the first non-comment line is a valid function header.
485 line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
486 if (!LineIt.is_at_eof()) {
487 if ((*LineIt)[0] != ' ') {
488 uint64_t NumSamples, NumHeadSamples;
489 StringRef FName;
490 result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
491 }
492 }
493
494 return result;
495}
496
498 unsigned NumBytesRead = 0;
499 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
500
501 if (Val > std::numeric_limits<T>::max()) {
502 std::error_code EC = sampleprof_error::malformed;
503 reportError(0, EC.message());
504 return EC;
505 } else if (Data + NumBytesRead > End) {
506 std::error_code EC = sampleprof_error::truncated;
507 reportError(0, EC.message());
508 return EC;
509 }
510
511 Data += NumBytesRead;
512 return static_cast<T>(Val);
513}
514
516 StringRef Str(reinterpret_cast<const char *>(Data));
517 if (Data + Str.size() + 1 > End) {
518 std::error_code EC = sampleprof_error::truncated;
519 reportError(0, EC.message());
520 return EC;
521 }
522
523 Data += Str.size() + 1;
524 return Str;
525}
526
527template <typename T>
529 if (Data + sizeof(T) > End) {
530 std::error_code EC = sampleprof_error::truncated;
531 reportError(0, EC.message());
532 return EC;
533 }
534
535 using namespace support;
536 T Val = endian::readNext<T, llvm::endianness::little>(Data);
537 return Val;
538}
539
540template <typename T>
542 auto Idx = readNumber<size_t>();
543 if (std::error_code EC = Idx.getError())
544 return EC;
545 if (*Idx >= Table.size())
547 return *Idx;
548}
549
553 if (std::error_code EC = Idx.getError())
554 return EC;
555 if (RetIdx)
556 *RetIdx = *Idx;
557 return NameTable[*Idx];
558}
559
562 auto ContextIdx = readNumber<size_t>();
563 if (std::error_code EC = ContextIdx.getError())
564 return EC;
565 if (*ContextIdx >= CSNameTable.size())
567 if (RetIdx)
568 *RetIdx = *ContextIdx;
569 return CSNameTable[*ContextIdx];
570}
571
575 size_t Idx;
576 if (ProfileIsCS) {
577 auto FContext(readContextFromTable(&Idx));
578 if (std::error_code EC = FContext.getError())
579 return EC;
580 Context = SampleContext(*FContext);
581 } else {
582 auto FName(readStringFromTable(&Idx));
583 if (std::error_code EC = FName.getError())
584 return EC;
585 Context = SampleContext(*FName);
586 }
587 // Since MD5SampleContextStart may point to the profile's file data, need to
588 // make sure it is reading the same value on big endian CPU.
590 // Lazy computing of hash value, write back to the table to cache it. Only
591 // compute the context's hash value if it is being referenced for the first
592 // time.
593 if (Hash == 0) {
595 Hash = Context.getHashCode();
597 }
598 return std::make_pair(Context, Hash);
599}
600
601std::error_code
603 auto NumSamples = readNumber<uint64_t>();
604 if (std::error_code EC = NumSamples.getError())
605 return EC;
606 FProfile.addTotalSamples(*NumSamples);
607
608 // Read the samples in the body.
609 auto NumRecords = readNumber<uint32_t>();
610 if (std::error_code EC = NumRecords.getError())
611 return EC;
612
613 for (uint32_t I = 0; I < *NumRecords; ++I) {
614 auto LineOffset = readNumber<uint64_t>();
615 if (std::error_code EC = LineOffset.getError())
616 return EC;
617
618 if (!isOffsetLegal(*LineOffset)) {
620 }
621
622 auto Discriminator = readNumber<uint64_t>();
623 if (std::error_code EC = Discriminator.getError())
624 return EC;
625
626 auto NumSamples = readNumber<uint64_t>();
627 if (std::error_code EC = NumSamples.getError())
628 return EC;
629
630 auto NumCalls = readNumber<uint32_t>();
631 if (std::error_code EC = NumCalls.getError())
632 return EC;
633
634 // Here we handle FS discriminators:
635 uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
636
637 for (uint32_t J = 0; J < *NumCalls; ++J) {
638 auto CalledFunction(readStringFromTable());
639 if (std::error_code EC = CalledFunction.getError())
640 return EC;
641
642 auto CalledFunctionSamples = readNumber<uint64_t>();
643 if (std::error_code EC = CalledFunctionSamples.getError())
644 return EC;
645
646 FProfile.addCalledTargetSamples(*LineOffset, DiscriminatorVal,
647 *CalledFunction, *CalledFunctionSamples);
648 }
649
650 FProfile.addBodySamples(*LineOffset, DiscriminatorVal, *NumSamples);
651 }
652
653 // Read all the samples for inlined function calls.
654 auto NumCallsites = readNumber<uint32_t>();
655 if (std::error_code EC = NumCallsites.getError())
656 return EC;
657
658 for (uint32_t J = 0; J < *NumCallsites; ++J) {
659 auto LineOffset = readNumber<uint64_t>();
660 if (std::error_code EC = LineOffset.getError())
661 return EC;
662
663 auto Discriminator = readNumber<uint64_t>();
664 if (std::error_code EC = Discriminator.getError())
665 return EC;
666
667 auto FName(readStringFromTable());
668 if (std::error_code EC = FName.getError())
669 return EC;
670
671 // Here we handle FS discriminators:
672 uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
673
674 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
675 LineLocation(*LineOffset, DiscriminatorVal))[*FName];
676 CalleeProfile.setFunction(*FName);
677 if (std::error_code EC = readProfile(CalleeProfile))
678 return EC;
679 }
680
682}
683
684std::error_code
686 SampleProfileMap &Profiles) {
687 Data = Start;
688 auto NumHeadSamples = readNumber<uint64_t>();
689 if (std::error_code EC = NumHeadSamples.getError())
690 return EC;
691
692 auto FContextHash(readSampleContextFromTable());
693 if (std::error_code EC = FContextHash.getError())
694 return EC;
695
696 auto &[FContext, Hash] = *FContextHash;
697 // Use the cached hash value for insertion instead of recalculating it.
698 auto Res = Profiles.try_emplace(Hash, FContext, FunctionSamples());
699 FunctionSamples &FProfile = Res.first->second;
700 FProfile.setContext(FContext);
701 FProfile.addHeadSamples(*NumHeadSamples);
702
703 if (FContext.hasContext())
705
706 if (std::error_code EC = readProfile(FProfile))
707 return EC;
709}
710
711std::error_code
713 return readFuncProfile(Start, Profiles);
714}
715
719 while (Data < End) {
720 if (std::error_code EC = readFuncProfile(Data))
721 return EC;
722 }
723
725}
726
728 const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
729 Data = Start;
730 End = Start + Size;
731 switch (Entry.Type) {
732 case SecProfSummary:
733 if (std::error_code EC = readSummary())
734 return EC;
736 Summary->setPartialProfile(true);
743 break;
744 case SecNameTable: {
745 bool FixedLengthMD5 =
747 bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
748 // UseMD5 means if THIS section uses MD5, ProfileIsMD5 means if the entire
749 // profile uses MD5 for function name matching in IPO passes.
750 ProfileIsMD5 = ProfileIsMD5 || UseMD5;
753 if (std::error_code EC = readNameTableSec(UseMD5, FixedLengthMD5))
754 return EC;
755 break;
756 }
757 case SecCSNameTable: {
758 if (std::error_code EC = readCSNameTableSec())
759 return EC;
760 break;
761 }
762 case SecLBRProfile:
763 ProfileSecRange = std::make_pair(Data, End);
764 if (std::error_code EC = readFuncProfiles())
765 return EC;
766 break;
768 // If module is absent, we are using LLVM tools, and need to read all
769 // profiles, so skip reading the function offset table.
770 if (!M) {
771 Data = End;
772 } else {
775 "func offset table should always be sorted in CS profile");
776 if (std::error_code EC = readFuncOffsetTable())
777 return EC;
778 }
779 break;
780 case SecFuncMetadata: {
786 if (std::error_code EC = readFuncMetadata(ProfileHasAttribute))
787 return EC;
788 break;
789 }
791 if (std::error_code EC = readProfileSymbolList())
792 return EC;
793 break;
794 default:
795 if (std::error_code EC = readCustomSection(Entry))
796 return EC;
797 break;
798 }
800}
801
803 // If profile is CS, the function offset section is expected to consist of
804 // sequences of contexts in pre-order layout
805 // (e.g. [A, A:1 @ B, A:1 @ B:2.3 @ C] [D, D:1 @ E]), so that when a matched
806 // context in the module is found, the profiles of all its callees are
807 // recursively loaded. A list is needed since the order of profiles matters.
808 if (ProfileIsCS)
809 return true;
810
811 // If the profile is MD5, use the map container to lookup functions in
812 // the module. A remapper has no use on MD5 names.
813 if (useMD5())
814 return false;
815
816 // Profile is not MD5 and if a remapper is present, the remapped name of
817 // every function needed to be matched against the module, so use the list
818 // container since each entry is accessed.
819 if (Remapper)
820 return true;
821
822 // Otherwise use the map container for faster lookup.
823 // TODO: If the cardinality of the function offset section is much smaller
824 // than the number of functions in the module, using the list container can
825 // be always faster, but we need to figure out the constant factor to
826 // determine the cutoff.
827 return false;
828}
829
830std::error_code
832 SampleProfileMap &Profiles) {
833 if (FuncsToUse.empty())
835
836 Data = ProfileSecRange.first;
837 End = ProfileSecRange.second;
838 if (std::error_code EC = readFuncProfiles(FuncsToUse, Profiles))
839 return EC;
840 End = Data;
841 DenseSet<FunctionSamples *> ProfilesToReadMetadata;
842 for (auto FName : FuncsToUse) {
843 auto I = Profiles.find(FName);
844 if (I != Profiles.end())
845 ProfilesToReadMetadata.insert(&I->second);
846 }
847
848 if (std::error_code EC =
849 readFuncMetadata(ProfileHasAttribute, ProfilesToReadMetadata))
850 return EC;
852}
853
855 if (!M)
856 return false;
857 FuncsToUse.clear();
858 for (auto &F : *M)
860 return true;
861}
862
864 // If there are more than one function offset section, the profile associated
865 // with the previous section has to be done reading before next one is read.
866 FuncOffsetTable.clear();
867 FuncOffsetList.clear();
868
869 auto Size = readNumber<uint64_t>();
870 if (std::error_code EC = Size.getError())
871 return EC;
872
873 bool UseFuncOffsetList = useFuncOffsetList();
874 if (UseFuncOffsetList)
875 FuncOffsetList.reserve(*Size);
876 else
877 FuncOffsetTable.reserve(*Size);
878
879 for (uint64_t I = 0; I < *Size; ++I) {
880 auto FContextHash(readSampleContextFromTable());
881 if (std::error_code EC = FContextHash.getError())
882 return EC;
883
884 auto &[FContext, Hash] = *FContextHash;
885 auto Offset = readNumber<uint64_t>();
886 if (std::error_code EC = Offset.getError())
887 return EC;
888
889 if (UseFuncOffsetList)
890 FuncOffsetList.emplace_back(FContext, *Offset);
891 else
892 // Because Porfiles replace existing value with new value if collision
893 // happens, we also use the latest offset so that they are consistent.
894 FuncOffsetTable[Hash] = *Offset;
895 }
896
898}
899
901 const DenseSet<StringRef> &FuncsToUse, SampleProfileMap &Profiles) {
902 const uint8_t *Start = Data;
903
904 if (Remapper) {
905 for (auto Name : FuncsToUse) {
906 Remapper->insert(Name);
907 }
908 }
909
910 if (ProfileIsCS) {
912 DenseSet<uint64_t> FuncGuidsToUse;
913 if (useMD5()) {
914 for (auto Name : FuncsToUse)
916 }
917
918 // For each function in current module, load all context profiles for
919 // the function as well as their callee contexts which can help profile
920 // guided importing for ThinLTO. This can be achieved by walking
921 // through an ordered context container, where contexts are laid out
922 // as if they were walked in preorder of a context trie. While
923 // traversing the trie, a link to the highest common ancestor node is
924 // kept so that all of its decendants will be loaded.
925 const SampleContext *CommonContext = nullptr;
926 for (const auto &NameOffset : FuncOffsetList) {
927 const auto &FContext = NameOffset.first;
928 FunctionId FName = FContext.getFunction();
929 StringRef FNameString;
930 if (!useMD5())
931 FNameString = FName.stringRef();
932
933 // For function in the current module, keep its farthest ancestor
934 // context. This can be used to load itself and its child and
935 // sibling contexts.
936 if ((useMD5() && FuncGuidsToUse.count(FName.getHashCode())) ||
937 (!useMD5() && (FuncsToUse.count(FNameString) ||
938 (Remapper && Remapper->exist(FNameString))))) {
939 if (!CommonContext || !CommonContext->isPrefixOf(FContext))
940 CommonContext = &FContext;
941 }
942
943 if (CommonContext == &FContext ||
944 (CommonContext && CommonContext->isPrefixOf(FContext))) {
945 // Load profile for the current context which originated from
946 // the common ancestor.
947 const uint8_t *FuncProfileAddr = Start + NameOffset.second;
948 if (std::error_code EC = readFuncProfile(FuncProfileAddr))
949 return EC;
950 }
951 }
952 } else if (useMD5()) {
954 for (auto Name : FuncsToUse) {
955 auto GUID = MD5Hash(Name);
956 auto iter = FuncOffsetTable.find(GUID);
957 if (iter == FuncOffsetTable.end())
958 continue;
959 const uint8_t *FuncProfileAddr = Start + iter->second;
960 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
961 return EC;
962 }
963 } else if (Remapper) {
965 for (auto NameOffset : FuncOffsetList) {
966 SampleContext FContext(NameOffset.first);
967 auto FuncName = FContext.getFunction();
968 StringRef FuncNameStr = FuncName.stringRef();
969 if (!FuncsToUse.count(FuncNameStr) && !Remapper->exist(FuncNameStr))
970 continue;
971 const uint8_t *FuncProfileAddr = Start + NameOffset.second;
972 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
973 return EC;
974 }
975 } else {
977 for (auto Name : FuncsToUse) {
978
979 auto iter = FuncOffsetTable.find(MD5Hash(Name));
980 if (iter == FuncOffsetTable.end())
981 continue;
982 const uint8_t *FuncProfileAddr = Start + iter->second;
983 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
984 return EC;
985 }
986 }
987
989}
990
992 // Collect functions used by current module if the Reader has been
993 // given a module.
994 // collectFuncsFromModule uses FunctionSamples::getCanonicalFnName
995 // which will query FunctionSamples::HasUniqSuffix, so it has to be
996 // called after FunctionSamples::HasUniqSuffix is set, i.e. after
997 // NameTable section is read.
998 bool LoadFuncsToBeUsed = collectFuncsFromModule();
999
1000 // When LoadFuncsToBeUsed is false, we are using LLVM tool, need to read all
1001 // profiles.
1002 if (!LoadFuncsToBeUsed) {
1003 while (Data < End) {
1004 if (std::error_code EC = readFuncProfile(Data))
1005 return EC;
1006 }
1007 assert(Data == End && "More data is read than expected");
1008 } else {
1009 // Load function profiles on demand.
1010 if (std::error_code EC = readFuncProfiles(FuncsToUse, Profiles))
1011 return EC;
1012 Data = End;
1013 }
1014 assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
1015 "Cannot have both context-sensitive and regular profile");
1017 "Section flag should be consistent with actual profile");
1019}
1020
1022 if (!ProfSymList)
1023 ProfSymList = std::make_unique<ProfileSymbolList>();
1024
1025 if (std::error_code EC = ProfSymList->read(Data, End - Data))
1026 return EC;
1027
1028 Data = End;
1030}
1031
1032std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
1033 const uint8_t *SecStart, const uint64_t SecSize,
1034 const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
1035 Data = SecStart;
1036 End = SecStart + SecSize;
1037 auto DecompressSize = readNumber<uint64_t>();
1038 if (std::error_code EC = DecompressSize.getError())
1039 return EC;
1040 DecompressBufSize = *DecompressSize;
1041
1042 auto CompressSize = readNumber<uint64_t>();
1043 if (std::error_code EC = CompressSize.getError())
1044 return EC;
1045
1048
1049 uint8_t *Buffer = Allocator.Allocate<uint8_t>(DecompressBufSize);
1050 size_t UCSize = DecompressBufSize;
1052 Buffer, UCSize);
1053 if (E)
1055 DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
1057}
1058
1060 const uint8_t *BufStart =
1061 reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1062
1063 for (auto &Entry : SecHdrTable) {
1064 // Skip empty section.
1065 if (!Entry.Size)
1066 continue;
1067
1068 // Skip sections without inlined functions when SkipFlatProf is true.
1070 continue;
1071
1072 const uint8_t *SecStart = BufStart + Entry.Offset;
1073 uint64_t SecSize = Entry.Size;
1074
1075 // If the section is compressed, decompress it into a buffer
1076 // DecompressBuf before reading the actual data. The pointee of
1077 // 'Data' will be changed to buffer hold by DecompressBuf
1078 // temporarily when reading the actual data.
1079 bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
1080 if (isCompressed) {
1081 const uint8_t *DecompressBuf;
1082 uint64_t DecompressBufSize;
1083 if (std::error_code EC = decompressSection(
1084 SecStart, SecSize, DecompressBuf, DecompressBufSize))
1085 return EC;
1086 SecStart = DecompressBuf;
1087 SecSize = DecompressBufSize;
1088 }
1089
1090 if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
1091 return EC;
1092 if (Data != SecStart + SecSize)
1094
1095 // Change the pointee of 'Data' from DecompressBuf to original Buffer.
1096 if (isCompressed) {
1097 Data = BufStart + Entry.Offset;
1098 End = BufStart + Buffer->getBufferSize();
1099 }
1100 }
1101
1103}
1104
1105std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
1106 if (Magic == SPMagic())
1109}
1110
1111std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
1112 if (Magic == SPMagic(SPF_Ext_Binary))
1115}
1116
1118 auto Size = readNumber<size_t>();
1119 if (std::error_code EC = Size.getError())
1120 return EC;
1121
1122 // Normally if useMD5 is true, the name table should have MD5 values, not
1123 // strings, however in the case that ExtBinary profile has multiple name
1124 // tables mixing string and MD5, all of them have to be normalized to use MD5,
1125 // because optimization passes can only handle either type.
1126 bool UseMD5 = useMD5();
1127
1128 NameTable.clear();
1129 NameTable.reserve(*Size);
1130 if (!ProfileIsCS) {
1131 MD5SampleContextTable.clear();
1132 if (UseMD5)
1133 MD5SampleContextTable.reserve(*Size);
1134 else
1135 // If we are using strings, delay MD5 computation since only a portion of
1136 // names are used by top level functions. Use 0 to indicate MD5 value is
1137 // to be calculated as no known string has a MD5 value of 0.
1138 MD5SampleContextTable.resize(*Size);
1139 }
1140 for (size_t I = 0; I < *Size; ++I) {
1141 auto Name(readString());
1142 if (std::error_code EC = Name.getError())
1143 return EC;
1144 if (UseMD5) {
1145 FunctionId FID(*Name);
1146 if (!ProfileIsCS)
1147 MD5SampleContextTable.emplace_back(FID.getHashCode());
1148 NameTable.emplace_back(FID);
1149 } else
1150 NameTable.push_back(FunctionId(*Name));
1151 }
1152 if (!ProfileIsCS)
1155}
1156
1157std::error_code
1159 bool FixedLengthMD5) {
1160 if (FixedLengthMD5) {
1161 if (!IsMD5)
1162 errs() << "If FixedLengthMD5 is true, UseMD5 has to be true";
1163 auto Size = readNumber<size_t>();
1164 if (std::error_code EC = Size.getError())
1165 return EC;
1166
1167 assert(Data + (*Size) * sizeof(uint64_t) == End &&
1168 "Fixed length MD5 name table does not contain specified number of "
1169 "entries");
1170 if (Data + (*Size) * sizeof(uint64_t) > End)
1172
1173 NameTable.clear();
1174 NameTable.reserve(*Size);
1175 for (size_t I = 0; I < *Size; ++I) {
1176 using namespace support;
1177 uint64_t FID = endian::read<uint64_t, endianness::little, unaligned>(
1178 Data + I * sizeof(uint64_t));
1179 NameTable.emplace_back(FunctionId(FID));
1180 }
1181 if (!ProfileIsCS)
1182 MD5SampleContextStart = reinterpret_cast<const uint64_t *>(Data);
1183 Data = Data + (*Size) * sizeof(uint64_t);
1185 }
1186
1187 if (IsMD5) {
1188 assert(!FixedLengthMD5 && "FixedLengthMD5 should be unreachable here");
1189 auto Size = readNumber<size_t>();
1190 if (std::error_code EC = Size.getError())
1191 return EC;
1192
1193 NameTable.clear();
1194 NameTable.reserve(*Size);
1195 if (!ProfileIsCS)
1196 MD5SampleContextTable.resize(*Size);
1197 for (size_t I = 0; I < *Size; ++I) {
1198 auto FID = readNumber<uint64_t>();
1199 if (std::error_code EC = FID.getError())
1200 return EC;
1201 if (!ProfileIsCS)
1203 NameTable.emplace_back(FunctionId(*FID));
1204 }
1205 if (!ProfileIsCS)
1208 }
1209
1211}
1212
1213// Read in the CS name table section, which basically contains a list of context
1214// vectors. Each element of a context vector, aka a frame, refers to the
1215// underlying raw function names that are stored in the name table, as well as
1216// a callsite identifier that only makes sense for non-leaf frames.
1218 auto Size = readNumber<size_t>();
1219 if (std::error_code EC = Size.getError())
1220 return EC;
1221
1222 CSNameTable.clear();
1223 CSNameTable.reserve(*Size);
1224 if (ProfileIsCS) {
1225 // Delay MD5 computation of CS context until they are needed. Use 0 to
1226 // indicate MD5 value is to be calculated as no known string has a MD5
1227 // value of 0.
1228 MD5SampleContextTable.clear();
1229 MD5SampleContextTable.resize(*Size);
1231 }
1232 for (size_t I = 0; I < *Size; ++I) {
1233 CSNameTable.emplace_back(SampleContextFrameVector());
1234 auto ContextSize = readNumber<uint32_t>();
1235 if (std::error_code EC = ContextSize.getError())
1236 return EC;
1237 for (uint32_t J = 0; J < *ContextSize; ++J) {
1238 auto FName(readStringFromTable());
1239 if (std::error_code EC = FName.getError())
1240 return EC;
1241 auto LineOffset = readNumber<uint64_t>();
1242 if (std::error_code EC = LineOffset.getError())
1243 return EC;
1244
1245 if (!isOffsetLegal(*LineOffset))
1247
1248 auto Discriminator = readNumber<uint64_t>();
1249 if (std::error_code EC = Discriminator.getError())
1250 return EC;
1251
1252 CSNameTable.back().emplace_back(
1253 FName.get(), LineLocation(LineOffset.get(), Discriminator.get()));
1254 }
1255 }
1256
1258}
1259
1260std::error_code
1262 FunctionSamples *FProfile) {
1263 if (Data < End) {
1264 if (ProfileIsProbeBased) {
1265 auto Checksum = readNumber<uint64_t>();
1266 if (std::error_code EC = Checksum.getError())
1267 return EC;
1268 if (FProfile)
1269 FProfile->setFunctionHash(*Checksum);
1270 }
1271
1272 if (ProfileHasAttribute) {
1273 auto Attributes = readNumber<uint32_t>();
1274 if (std::error_code EC = Attributes.getError())
1275 return EC;
1276 if (FProfile)
1278 }
1279
1280 if (!ProfileIsCS) {
1281 // Read all the attributes for inlined function calls.
1282 auto NumCallsites = readNumber<uint32_t>();
1283 if (std::error_code EC = NumCallsites.getError())
1284 return EC;
1285
1286 for (uint32_t J = 0; J < *NumCallsites; ++J) {
1287 auto LineOffset = readNumber<uint64_t>();
1288 if (std::error_code EC = LineOffset.getError())
1289 return EC;
1290
1291 auto Discriminator = readNumber<uint64_t>();
1292 if (std::error_code EC = Discriminator.getError())
1293 return EC;
1294
1295 auto FContextHash(readSampleContextFromTable());
1296 if (std::error_code EC = FContextHash.getError())
1297 return EC;
1298
1299 auto &[FContext, Hash] = *FContextHash;
1300 FunctionSamples *CalleeProfile = nullptr;
1301 if (FProfile) {
1302 CalleeProfile = const_cast<FunctionSamples *>(
1304 *LineOffset,
1305 *Discriminator))[FContext.getFunction()]);
1306 }
1307 if (std::error_code EC =
1308 readFuncMetadata(ProfileHasAttribute, CalleeProfile))
1309 return EC;
1310 }
1311 }
1312 }
1313
1315}
1316
1318 bool ProfileHasAttribute, DenseSet<FunctionSamples *> &Profiles) {
1319 if (FuncMetadataIndex.empty())
1321
1322 for (auto *FProfile : Profiles) {
1323 auto R = FuncMetadataIndex.find(FProfile->getContext().getHashCode());
1324 if (R == FuncMetadataIndex.end())
1325 continue;
1326
1327 Data = R->second.first;
1328 End = R->second.second;
1329 if (std::error_code EC = readFuncMetadata(ProfileHasAttribute, FProfile))
1330 return EC;
1331 assert(Data == End && "More data is read than expected");
1332 }
1334}
1335
1336std::error_code
1338 while (Data < End) {
1339 auto FContextHash(readSampleContextFromTable());
1340 if (std::error_code EC = FContextHash.getError())
1341 return EC;
1342 auto &[FContext, Hash] = *FContextHash;
1343 FunctionSamples *FProfile = nullptr;
1344 auto It = Profiles.find(FContext);
1345 if (It != Profiles.end())
1346 FProfile = &It->second;
1347
1348 const uint8_t *Start = Data;
1349 if (std::error_code EC = readFuncMetadata(ProfileHasAttribute, FProfile))
1350 return EC;
1351
1352 FuncMetadataIndex[FContext.getHashCode()] = {Start, Data};
1353 }
1354
1355 assert(Data == End && "More data is read than expected");
1357}
1358
1359std::error_code
1361 SecHdrTableEntry Entry;
1362 auto Type = readUnencodedNumber<uint64_t>();
1363 if (std::error_code EC = Type.getError())
1364 return EC;
1365 Entry.Type = static_cast<SecType>(*Type);
1366
1367 auto Flags = readUnencodedNumber<uint64_t>();
1368 if (std::error_code EC = Flags.getError())
1369 return EC;
1370 Entry.Flags = *Flags;
1371
1372 auto Offset = readUnencodedNumber<uint64_t>();
1373 if (std::error_code EC = Offset.getError())
1374 return EC;
1375 Entry.Offset = *Offset;
1376
1377 auto Size = readUnencodedNumber<uint64_t>();
1378 if (std::error_code EC = Size.getError())
1379 return EC;
1380 Entry.Size = *Size;
1381
1382 Entry.LayoutIndex = Idx;
1383 SecHdrTable.push_back(std::move(Entry));
1385}
1386
1388 auto EntryNum = readUnencodedNumber<uint64_t>();
1389 if (std::error_code EC = EntryNum.getError())
1390 return EC;
1391
1392 for (uint64_t i = 0; i < (*EntryNum); i++)
1393 if (std::error_code EC = readSecHdrTableEntry(i))
1394 return EC;
1395
1397}
1398
1400 const uint8_t *BufStart =
1401 reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1402 Data = BufStart;
1403 End = BufStart + Buffer->getBufferSize();
1404
1405 if (std::error_code EC = readMagicIdent())
1406 return EC;
1407
1408 if (std::error_code EC = readSecHdrTable())
1409 return EC;
1410
1412}
1413
1415 uint64_t Size = 0;
1416 for (auto &Entry : SecHdrTable) {
1417 if (Entry.Type == Type)
1418 Size += Entry.Size;
1419 }
1420 return Size;
1421}
1422
1424 // Sections in SecHdrTable is not necessarily in the same order as
1425 // sections in the profile because section like FuncOffsetTable needs
1426 // to be written after section LBRProfile but needs to be read before
1427 // section LBRProfile, so we cannot simply use the last entry in
1428 // SecHdrTable to calculate the file size.
1429 uint64_t FileSize = 0;
1430 for (auto &Entry : SecHdrTable) {
1431 FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
1432 }
1433 return FileSize;
1434}
1435
1436static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
1437 std::string Flags;
1439 Flags.append("{compressed,");
1440 else
1441 Flags.append("{");
1442
1444 Flags.append("flat,");
1445
1446 switch (Entry.Type) {
1447 case SecNameTable:
1449 Flags.append("fixlenmd5,");
1451 Flags.append("md5,");
1453 Flags.append("uniq,");
1454 break;
1455 case SecProfSummary:
1457 Flags.append("partial,");
1459 Flags.append("context,");
1461 Flags.append("preInlined,");
1463 Flags.append("fs-discriminator,");
1464 break;
1465 case SecFuncOffsetTable:
1467 Flags.append("ordered,");
1468 break;
1469 case SecFuncMetadata:
1471 Flags.append("probe,");
1473 Flags.append("attr,");
1474 break;
1475 default:
1476 break;
1477 }
1478 char &last = Flags.back();
1479 if (last == ',')
1480 last = '}';
1481 else
1482 Flags.append("}");
1483 return Flags;
1484}
1485
1487 uint64_t TotalSecsSize = 0;
1488 for (auto &Entry : SecHdrTable) {
1489 OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1490 << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1491 << "\n";
1492 ;
1493 TotalSecsSize += Entry.Size;
1494 }
1495 uint64_t HeaderSize = SecHdrTable.front().Offset;
1496 assert(HeaderSize + TotalSecsSize == getFileSize() &&
1497 "Size of 'header + sections' doesn't match the total size of profile");
1498
1499 OS << "Header Size: " << HeaderSize << "\n";
1500 OS << "Total Sections Size: " << TotalSecsSize << "\n";
1501 OS << "File Size: " << getFileSize() << "\n";
1502 return true;
1503}
1504
1506 // Read and check the magic identifier.
1507 auto Magic = readNumber<uint64_t>();
1508 if (std::error_code EC = Magic.getError())
1509 return EC;
1510 else if (std::error_code EC = verifySPMagic(*Magic))
1511 return EC;
1512
1513 // Read the version number.
1514 auto Version = readNumber<uint64_t>();
1515 if (std::error_code EC = Version.getError())
1516 return EC;
1517 else if (*Version != SPVersion())
1519
1521}
1522
1524 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1525 End = Data + Buffer->getBufferSize();
1526
1527 if (std::error_code EC = readMagicIdent())
1528 return EC;
1529
1530 if (std::error_code EC = readSummary())
1531 return EC;
1532
1533 if (std::error_code EC = readNameTable())
1534 return EC;
1536}
1537
1538std::error_code SampleProfileReaderBinary::readSummaryEntry(
1539 std::vector<ProfileSummaryEntry> &Entries) {
1540 auto Cutoff = readNumber<uint64_t>();
1541 if (std::error_code EC = Cutoff.getError())
1542 return EC;
1543
1544 auto MinBlockCount = readNumber<uint64_t>();
1545 if (std::error_code EC = MinBlockCount.getError())
1546 return EC;
1547
1548 auto NumBlocks = readNumber<uint64_t>();
1549 if (std::error_code EC = NumBlocks.getError())
1550 return EC;
1551
1552 Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
1554}
1555
1557 auto TotalCount = readNumber<uint64_t>();
1558 if (std::error_code EC = TotalCount.getError())
1559 return EC;
1560
1561 auto MaxBlockCount = readNumber<uint64_t>();
1562 if (std::error_code EC = MaxBlockCount.getError())
1563 return EC;
1564
1565 auto MaxFunctionCount = readNumber<uint64_t>();
1566 if (std::error_code EC = MaxFunctionCount.getError())
1567 return EC;
1568
1569 auto NumBlocks = readNumber<uint64_t>();
1570 if (std::error_code EC = NumBlocks.getError())
1571 return EC;
1572
1573 auto NumFunctions = readNumber<uint64_t>();
1574 if (std::error_code EC = NumFunctions.getError())
1575 return EC;
1576
1577 auto NumSummaryEntries = readNumber<uint64_t>();
1578 if (std::error_code EC = NumSummaryEntries.getError())
1579 return EC;
1580
1581 std::vector<ProfileSummaryEntry> Entries;
1582 for (unsigned i = 0; i < *NumSummaryEntries; i++) {
1583 std::error_code EC = readSummaryEntry(Entries);
1584 if (EC != sampleprof_error::success)
1585 return EC;
1586 }
1587 Summary = std::make_unique<ProfileSummary>(
1588 ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
1589 *MaxFunctionCount, *NumBlocks, *NumFunctions);
1590
1592}
1593
1595 const uint8_t *Data =
1596 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1597 uint64_t Magic = decodeULEB128(Data);
1598 return Magic == SPMagic();
1599}
1600
1602 const uint8_t *Data =
1603 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1604 uint64_t Magic = decodeULEB128(Data);
1605 return Magic == SPMagic(SPF_Ext_Binary);
1606}
1607
1609 uint32_t dummy;
1610 if (!GcovBuffer.readInt(dummy))
1613}
1614
1616 if (sizeof(T) <= sizeof(uint32_t)) {
1617 uint32_t Val;
1618 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
1619 return static_cast<T>(Val);
1620 } else if (sizeof(T) <= sizeof(uint64_t)) {
1621 uint64_t Val;
1622 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
1623 return static_cast<T>(Val);
1624 }
1625
1626 std::error_code EC = sampleprof_error::malformed;
1627 reportError(0, EC.message());
1628 return EC;
1629}
1630
1632 StringRef Str;
1633 if (!GcovBuffer.readString(Str))
1635 return Str;
1636}
1637
1639 // Read the magic identifier.
1642
1643 // Read the version number. Note - the GCC reader does not validate this
1644 // version, but the profile creator generates v704.
1645 GCOV::GCOVVersion version;
1646 if (!GcovBuffer.readGCOVVersion(version))
1648
1649 if (version != GCOV::V407)
1651
1652 // Skip the empty integer.
1653 if (std::error_code EC = skipNextWord())
1654 return EC;
1655
1657}
1658
1660 uint32_t Tag;
1661 if (!GcovBuffer.readInt(Tag))
1663
1664 if (Tag != Expected)
1666
1667 if (std::error_code EC = skipNextWord())
1668 return EC;
1669
1671}
1672
1674 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1675 return EC;
1676
1677 uint32_t Size;
1678 if (!GcovBuffer.readInt(Size))
1680
1681 for (uint32_t I = 0; I < Size; ++I) {
1682 StringRef Str;
1683 if (!GcovBuffer.readString(Str))
1685 Names.push_back(std::string(Str));
1686 }
1687
1689}
1690
1692 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1693 return EC;
1694
1695 uint32_t NumFunctions;
1696 if (!GcovBuffer.readInt(NumFunctions))
1698
1699 InlineCallStack Stack;
1700 for (uint32_t I = 0; I < NumFunctions; ++I)
1701 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1702 return EC;
1703
1706}
1707
1709 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1710 uint64_t HeadCount = 0;
1711 if (InlineStack.size() == 0)
1712 if (!GcovBuffer.readInt64(HeadCount))
1714
1715 uint32_t NameIdx;
1716 if (!GcovBuffer.readInt(NameIdx))
1718
1719 StringRef Name(Names[NameIdx]);
1720
1721 uint32_t NumPosCounts;
1722 if (!GcovBuffer.readInt(NumPosCounts))
1724
1725 uint32_t NumCallsites;
1726 if (!GcovBuffer.readInt(NumCallsites))
1728
1729 FunctionSamples *FProfile = nullptr;
1730 if (InlineStack.size() == 0) {
1731 // If this is a top function that we have already processed, do not
1732 // update its profile again. This happens in the presence of
1733 // function aliases. Since these aliases share the same function
1734 // body, there will be identical replicated profiles for the
1735 // original function. In this case, we simply not bother updating
1736 // the profile of the original function.
1737 FProfile = &Profiles[FunctionId(Name)];
1738 FProfile->addHeadSamples(HeadCount);
1739 if (FProfile->getTotalSamples() > 0)
1740 Update = false;
1741 } else {
1742 // Otherwise, we are reading an inlined instance. The top of the
1743 // inline stack contains the profile of the caller. Insert this
1744 // callee in the caller's CallsiteMap.
1745 FunctionSamples *CallerProfile = InlineStack.front();
1746 uint32_t LineOffset = Offset >> 16;
1747 uint32_t Discriminator = Offset & 0xffff;
1748 FProfile = &CallerProfile->functionSamplesAt(
1749 LineLocation(LineOffset, Discriminator))[FunctionId(Name)];
1750 }
1751 FProfile->setFunction(FunctionId(Name));
1752
1753 for (uint32_t I = 0; I < NumPosCounts; ++I) {
1757
1758 uint32_t NumTargets;
1759 if (!GcovBuffer.readInt(NumTargets))
1761
1762 uint64_t Count;
1763 if (!GcovBuffer.readInt64(Count))
1765
1766 // The line location is encoded in the offset as:
1767 // high 16 bits: line offset to the start of the function.
1768 // low 16 bits: discriminator.
1769 uint32_t LineOffset = Offset >> 16;
1770 uint32_t Discriminator = Offset & 0xffff;
1771
1772 InlineCallStack NewStack;
1773 NewStack.push_back(FProfile);
1774 llvm::append_range(NewStack, InlineStack);
1775 if (Update) {
1776 // Walk up the inline stack, adding the samples on this line to
1777 // the total sample count of the callers in the chain.
1778 for (auto *CallerProfile : NewStack)
1779 CallerProfile->addTotalSamples(Count);
1780
1781 // Update the body samples for the current profile.
1782 FProfile->addBodySamples(LineOffset, Discriminator, Count);
1783 }
1784
1785 // Process the list of functions called at an indirect call site.
1786 // These are all the targets that a function pointer (or virtual
1787 // function) resolved at runtime.
1788 for (uint32_t J = 0; J < NumTargets; J++) {
1789 uint32_t HistVal;
1790 if (!GcovBuffer.readInt(HistVal))
1792
1793 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1795
1796 uint64_t TargetIdx;
1797 if (!GcovBuffer.readInt64(TargetIdx))
1799 StringRef TargetName(Names[TargetIdx]);
1800
1801 uint64_t TargetCount;
1802 if (!GcovBuffer.readInt64(TargetCount))
1804
1805 if (Update)
1806 FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1807 FunctionId(TargetName),
1808 TargetCount);
1809 }
1810 }
1811
1812 // Process all the inlined callers into the current function. These
1813 // are all the callsites that were inlined into this function.
1814 for (uint32_t I = 0; I < NumCallsites; I++) {
1815 // The offset is encoded as:
1816 // high 16 bits: line offset to the start of the function.
1817 // low 16 bits: discriminator.
1821 InlineCallStack NewStack;
1822 NewStack.push_back(FProfile);
1823 llvm::append_range(NewStack, InlineStack);
1824 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1825 return EC;
1826 }
1827
1829}
1830
1831/// Read a GCC AutoFDO profile.
1832///
1833/// This format is generated by the Linux Perf conversion tool at
1834/// https://github.com/google/autofdo.
1836 assert(!ProfileIsFSDisciminator && "Gcc profiles not support FSDisciminator");
1837 // Read the string table.
1838 if (std::error_code EC = readNameTable())
1839 return EC;
1840
1841 // Read the source profile.
1842 if (std::error_code EC = readFunctionProfiles())
1843 return EC;
1844
1846}
1847
1849 StringRef Magic(Buffer.getBufferStart());
1850 return Magic == "adcg*704";
1851}
1852
1854 // If the reader uses MD5 to represent string, we can't remap it because
1855 // we don't know what the original function names were.
1856 if (Reader.useMD5()) {
1858 Reader.getBuffer()->getBufferIdentifier(),
1859 "Profile data remapping cannot be applied to profile data "
1860 "using MD5 names (original mangled names are not available).",
1861 DS_Warning));
1862 return;
1863 }
1864
1865 // CSSPGO-TODO: Remapper is not yet supported.
1866 // We will need to remap the entire context string.
1867 assert(Remappings && "should be initialized while creating remapper");
1868 for (auto &Sample : Reader.getProfiles()) {
1869 DenseSet<FunctionId> NamesInSample;
1870 Sample.second.findAllNames(NamesInSample);
1871 for (auto &Name : NamesInSample) {
1872 StringRef NameStr = Name.stringRef();
1873 if (auto Key = Remappings->insert(NameStr))
1874 NameMap.insert({Key, NameStr});
1875 }
1876 }
1877
1878 RemappingApplied = true;
1879}
1880
1881std::optional<StringRef>
1883 if (auto Key = Remappings->lookup(Fname)) {
1884 StringRef Result = NameMap.lookup(Key);
1885 if (!Result.empty())
1886 return Result;
1887 }
1888 return std::nullopt;
1889}
1890
1891/// Prepare a memory buffer for the contents of \p Filename.
1892///
1893/// \returns an error code indicating the status of the buffer.
1896 auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()
1897 : FS.getBufferForFile(Filename);
1898 if (std::error_code EC = BufferOrErr.getError())
1899 return EC;
1900 auto Buffer = std::move(BufferOrErr.get());
1901
1902 return std::move(Buffer);
1903}
1904
1905/// Create a sample profile reader based on the format of the input file.
1906///
1907/// \param Filename The file to open.
1908///
1909/// \param C The LLVM context to use to emit diagnostics.
1910///
1911/// \param P The FSDiscriminatorPass.
1912///
1913/// \param RemapFilename The file used for profile remapping.
1914///
1915/// \returns an error code indicating the status of the created reader.
1919 StringRef RemapFilename) {
1920 auto BufferOrError = setupMemoryBuffer(Filename, FS);
1921 if (std::error_code EC = BufferOrError.getError())
1922 return EC;
1923 return create(BufferOrError.get(), C, FS, P, RemapFilename);
1924}
1925
1926/// Create a sample profile remapper from the given input, to remap the
1927/// function names in the given profile data.
1928///
1929/// \param Filename The file to open.
1930///
1931/// \param Reader The profile reader the remapper is going to be applied to.
1932///
1933/// \param C The LLVM context to use to emit diagnostics.
1934///
1935/// \returns an error code indicating the status of the created reader.
1938 vfs::FileSystem &FS,
1939 SampleProfileReader &Reader,
1940 LLVMContext &C) {
1941 auto BufferOrError = setupMemoryBuffer(Filename, FS);
1942 if (std::error_code EC = BufferOrError.getError())
1943 return EC;
1944 return create(BufferOrError.get(), Reader, C);
1945}
1946
1947/// Create a sample profile remapper from the given input, to remap the
1948/// function names in the given profile data.
1949///
1950/// \param B The memory buffer to create the reader from (assumes ownership).
1951///
1952/// \param C The LLVM context to use to emit diagnostics.
1953///
1954/// \param Reader The profile reader the remapper is going to be applied to.
1955///
1956/// \returns an error code indicating the status of the created reader.
1958SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
1959 SampleProfileReader &Reader,
1960 LLVMContext &C) {
1961 auto Remappings = std::make_unique<SymbolRemappingReader>();
1962 if (Error E = Remappings->read(*B)) {
1964 std::move(E), [&](const SymbolRemappingParseError &ParseError) {
1965 C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
1966 ParseError.getLineNum(),
1967 ParseError.getMessage()));
1968 });
1970 }
1971
1972 return std::make_unique<SampleProfileReaderItaniumRemapper>(
1973 std::move(B), std::move(Remappings), Reader);
1974}
1975
1976/// Create a sample profile reader based on the format of the input data.
1977///
1978/// \param B The memory buffer to create the reader from (assumes ownership).
1979///
1980/// \param C The LLVM context to use to emit diagnostics.
1981///
1982/// \param P The FSDiscriminatorPass.
1983///
1984/// \param RemapFilename The file used for profile remapping.
1985///
1986/// \returns an error code indicating the status of the created reader.
1988SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
1990 StringRef RemapFilename) {
1991 std::unique_ptr<SampleProfileReader> Reader;
1993 Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1995 Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1997 Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1999 Reader.reset(new SampleProfileReaderText(std::move(B), C));
2000 else
2002
2003 if (!RemapFilename.empty()) {
2005 RemapFilename, FS, *Reader, C);
2006 if (std::error_code EC = ReaderOrErr.getError()) {
2007 std::string Msg = "Could not create remapper: " + EC.message();
2008 C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
2009 return EC;
2010 }
2011 Reader->Remapper = std::move(ReaderOrErr.get());
2012 }
2013
2014 if (std::error_code EC = Reader->readHeader()) {
2015 return EC;
2016 }
2017
2018 Reader->setDiscriminatorMaskedBitFrom(P);
2019
2020 return std::move(Reader);
2021}
2022
2023// For text and GCC file formats, we compute the summary after reading the
2024// profile. Binary format has the profile summary in its header.
2028}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Kernel Attributes
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
std::string Name
uint64_t Size
Provides ErrorOr<T> smart pointer.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
static bool isDigit(const char C)
This file contains some templates that are useful if you are working with the STL at all.
static bool ParseHead(const StringRef &Input, StringRef &FName, uint64_t &NumSamples, uint64_t &NumHeadSamples)
Parse Input as function head.
static void dumpFunctionProfileJson(const FunctionSamples &S, json::OStream &JOS, bool TopLevel=false)
static bool isOffsetLegal(unsigned L)
Returns true if line offset L is legal (only has 16 bits).
static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth, uint64_t &NumSamples, uint32_t &LineOffset, uint32_t &Discriminator, StringRef &CalleeName, DenseMap< StringRef, uint64_t > &TargetCountMap, uint64_t &FunctionHash, uint32_t &Attributes, bool &IsFlat)
Parse Input as line sample.
static cl::opt< bool > ProfileIsFSDisciminator("profile-isfs", cl::Hidden, cl::init(false), cl::desc("Profile uses flow sensitive discriminators"))
static std::string getSecFlagsStr(const SecHdrTableEntry &Entry)
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
@ CallSiteProfile
raw_pwrite_stream & OS
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:149
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Diagnostic information for the sample profiler.
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
Tagged union holding either a T or a Error.
Definition: Error.h:485
bool readInt(uint32_t &Val)
Definition: GCOV.h:153
bool readInt64(uint64_t &Val)
Definition: GCOV.h:163
bool readGCOVVersion(GCOV::GCOVVersion &version)
readGCOVVersion - Read GCOV version.
Definition: GCOV.h:109
bool readString(StringRef &str)
Definition: GCOV.h:171
bool readGCDAFormat()
readGCDAFormat - Check GCDA signature is valid at the beginning of buffer.
Definition: GCOV.h:95
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition: Globals.cpp:77
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:52
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:77
static ErrorOr< std::unique_ptr< MemoryBuffer > > getSTDIN()
Read all of stdin into a file buffer, and return it.
Root of the metadata hierarchy.
Definition: Metadata.h:63
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Definition: ProfileCommon.h:71
LLVM_ABI std::unique_ptr< ProfileSummary > computeSummaryForProfiles(const sampleprof::SampleProfileMap &Profiles)
size_t size() const
Definition: SmallVector.h:79
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:480
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:581
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Definition: StringRef.h:409
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:384
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition: StringRef.h:353
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
Definition: StringRef.h:824
static constexpr size_t npos
Definition: StringRef.h:57
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Definition: StringRef.cpp:252
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:174
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition: JSON.h:996
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition: JSON.h:1026
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition: JSON.h:1051
LLVM_ABI void arrayBegin()
Definition: JSON.cpp:842
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
Definition: JSON.h:1055
LLVM_ABI void arrayEnd()
Definition: JSON.cpp:850
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:34
int64_t line_number() const
Return the current line number. May return any number at EOF.
Definition: LineIterator.h:69
bool is_at_eof() const
Return true if we've reached EOF or are an "end" iterator.
Definition: LineIterator.h:63
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
This class represents a function that is read from a sample profile.
Definition: FunctionId.h:36
StringRef stringRef() const
Convert to StringRef.
Definition: FunctionId.h:108
uint64_t getHashCode() const
Get hash code of this object.
Definition: FunctionId.h:123
std::string str() const
Convert to a string, usually for output purpose.
Definition: FunctionId.h:97
Representation of the samples collected for a function.
Definition: SampleProf.h:757
static LLVM_ABI bool ProfileIsPreInlined
Definition: SampleProf.h:1202
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:764
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
Definition: SampleProf.h:954
void setFunction(FunctionId NewFunctionID)
Set the name of the function.
Definition: SampleProf.h:1081
static LLVM_ABI bool ProfileIsCS
Definition: SampleProf.h:1200
FunctionId getFunction() const
Return the function name.
Definition: SampleProf.h:1086
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:783
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:797
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc)
Return the function samples at the given callsite location.
Definition: SampleProf.h:918
static LLVM_ABI bool ProfileIsProbeBased
Definition: SampleProf.h:1198
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
Definition: SampleProf.h:1102
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:791
void setFunctionHash(uint64_t Hash)
Definition: SampleProf.h:1091
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
Definition: SampleProf.h:1215
SampleContext & getContext() const
Definition: SampleProf.h:1204
static LLVM_ABI bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
Definition: SampleProf.h:1212
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition: SampleProf.h:946
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
Definition: SampleProf.h:988
void setContext(const SampleContext &FContext)
Definition: SampleProf.h:1206
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
Definition: SampleProf.h:985
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
Definition: HashKeyMap.h:65
void setAllAttributes(uint32_t A)
Definition: SampleProf.h:623
FunctionId getFunction() const
Definition: SampleProf.h:629
bool isPrefixOf(const SampleContext &That) const
Definition: SampleProf.h:708
This class provides operator overloads to the map container using MD5 as the key type,...
Definition: SampleProf.h:1325
iterator find(const SampleContext &Ctx)
Definition: SampleProf.h:1336
mapped_type & create(const SampleContext &Ctx)
Definition: SampleProf.h:1329
size_t erase(const SampleContext &Ctx)
Definition: SampleProf.h:1346
std::error_code readProfile(FunctionSamples &FProfile)
Read the contents of the given profile instance.
std::error_code readNameTable()
Read the whole name table.
const uint8_t * Data
Points to the current location in the buffer.
ErrorOr< StringRef > readString()
Read a string from the profile.
std::vector< FunctionId > NameTable
Function name table.
ErrorOr< T > readNumber()
Read a numeric value of type T from the profile.
ErrorOr< SampleContextFrames > readContextFromTable(size_t *RetIdx=nullptr)
Read a context indirectly via the CSNameTable.
ErrorOr< std::pair< SampleContext, uint64_t > > readSampleContextFromTable()
Read a context indirectly via the CSNameTable if the profile has context, otherwise same as readStrin...
std::error_code readHeader() override
Read and validate the file header.
const uint64_t * MD5SampleContextStart
The starting address of the table of MD5 values of sample contexts.
std::vector< SampleContextFrameVector > CSNameTable
CSNameTable is used to save full context vectors.
std::error_code readImpl() override
Read sample profiles from the associated file.
ErrorOr< FunctionId > readStringFromTable(size_t *RetIdx=nullptr)
Read a string indirectly via the name table. Optionally return the index.
std::vector< uint64_t > MD5SampleContextTable
Table to cache MD5 values of sample contexts corresponding to readSampleContextFromTable(),...
ErrorOr< size_t > readStringIndex(T &Table)
Read the string index and check whether it overflows the table.
const uint8_t * End
Points to the end of the buffer.
ErrorOr< T > readUnencodedNumber()
Read a numeric value of type T from the profile.
std::error_code readFuncProfile(const uint8_t *Start)
Read the next function profile instance.
std::error_code readSummary()
Read profile summary.
std::error_code readMagicIdent()
Read the contents of Magic number and Version number.
bool collectFuncsFromModule() override
Collect functions with definitions in Module M.
uint64_t getSectionSize(SecType Type)
Get the total size of all Type sections.
virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry)=0
std::vector< std::pair< SampleContext, uint64_t > > FuncOffsetList
The list version of FuncOffsetTable.
DenseSet< StringRef > FuncsToUse
The set containing the functions to use when compiling a module.
std::unique_ptr< ProfileSymbolList > ProfSymList
bool useFuncOffsetList() const
Determine which container readFuncOffsetTable() should populate, the list FuncOffsetList or the map F...
std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5)
std::error_code readImpl() override
Read sample profiles in extensible format from the associated file.
std::error_code readFuncMetadata(bool ProfileHasAttribute, DenseSet< FunctionSamples * > &Profiles)
virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry)
bool dumpSectionInfo(raw_ostream &OS=dbgs()) override
DenseMap< hash_code, uint64_t > FuncOffsetTable
The table mapping from a function context's MD5 to the offset of its FunctionSample towards file star...
std::error_code readHeader() override
Read and validate the file header.
uint64_t getFileSize()
Get the total size of header and all sections.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
GCOVBuffer GcovBuffer
GCOV buffer containing the profile.
std::vector< std::string > Names
Function names in this profile.
std::error_code readImpl() override
Read sample profiles from the associated file.
std::error_code readHeader() override
Read and validate the file header.
std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack, bool Update, uint32_t Offset)
static const uint32_t GCOVTagAFDOFileNames
GCOV tags used to separate sections in the profile file.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
std::error_code readSectionTag(uint32_t Expected)
Read the section tag and check that it's the same as Expected.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReaderItaniumRemapper > > create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader, LLVMContext &C)
Create a remapper from the given remapping file.
LLVM_ABI void applyRemapping(LLVMContext &Ctx)
Apply remappings to the profile read by Reader.
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
std::error_code readImpl() override
Read sample profiles from the associated file.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
Sample-based profile reader.
std::pair< const uint8_t *, const uint8_t * > ProfileSecRange
bool ProfileIsPreInlined
Whether function profile contains ShouldBeInlined contexts.
std::unordered_map< uint64_t, std::pair< const uint8_t *, const uint8_t * > > FuncMetadataIndex
SampleProfileMap & getProfiles()
Return all the profiles.
uint32_t CSProfileCount
Number of context-sensitive profiles.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
LLVM_ABI void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
bool useMD5() const
Return whether names in the profile are all MD5 numbers.
const Module * M
The current module being compiled if SampleProfileReader is used by compiler.
std::unique_ptr< MemoryBuffer > Buffer
Memory buffer holding the profile file.
std::unique_ptr< SampleProfileReaderItaniumRemapper > Remapper
bool ProfileHasAttribute
Whether the profile has attribute metadata.
bool SkipFlatProf
If SkipFlatProf is true, skip functions marked with !Flat in text mode or sections with SecFlagFlat f...
std::error_code read()
The interface to read sample profiles from the associated file.
bool ProfileIsCS
Whether function profiles are context-sensitive flat profiles.
bool ProfileIsMD5
Whether the profile uses MD5 for Sample Contexts and function names.
std::unique_ptr< ProfileSummary > Summary
Profile summary information.
LLVM_ABI void computeSummary()
Compute summary for this profile.
uint32_t getDiscriminatorMask() const
Get the bitmask the discriminators: For FS profiles, return the bit mask for this pass.
bool ProfileIsFS
Whether the function profiles use FS discriminators.
LLVM_ABI void dumpJson(raw_ostream &OS=dbgs())
Print all the profiles on stream OS in the JSON format.
SampleProfileMap Profiles
Map every function to its associated profile.
LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS, raw_ostream &OS=dbgs())
Print the profile for FunctionSamples on stream OS.
bool ProfileIsProbeBased
Whether samples are collected based on pseudo probes.
void reportError(int64_t LineNumber, const Twine &Msg) const
Report a parse error message.
LLVMContext & Ctx
LLVM context used to emit diagnostics.
Representation of a single sample record.
Definition: SampleProf.h:331
uint64_t getSamples() const
Definition: SampleProf.h:398
const SortedCallTargetSet getSortedCallTargets() const
Definition: SampleProf.h:400
The virtual file system interface.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
GCOVVersion
Definition: GCOV.h:43
@ V407
Definition: GCOV.h:43
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
Definition: SampleProf.cpp:231
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition: SampleProf.h:109
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:267
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition: SampleProf.h:748
uint64_t MD5Hash(const FunctionId &Obj)
Definition: FunctionId.h:167
std::map< LineLocation, SampleRecord > BodySampleMap
Definition: SampleProf.h:744
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
Definition: SampleProf.h:516
static std::string getSecName(SecType Type)
Definition: SampleProf.h:134
static uint64_t SPVersion()
Definition: SampleProf.h:116
uint64_t read64le(const void *P)
Definition: Endian.h:432
void write64le(void *P, uint64_t V)
Definition: Endian.h:475
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:990
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:132
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
Definition: SampleProf.h:72
sampleprof_error
Definition: SampleProf.h:49
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1973
@ DS_Warning
Represents the relative location of an instruction.
Definition: SampleProf.h:283