LLVM 18.0.0git
SampleProfWriter.cpp
Go to the documentation of this file.
1//===- SampleProfWriter.cpp - Write 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 writes LLVM sample profiles. It
10// supports two file formats: text and binary. The textual representation
11// is useful for debugging and testing purposes. The binary representation
12// is more compact, resulting in smaller file sizes. However, they can
13// both be used interchangeably.
14//
15// See lib/ProfileData/SampleProfReader.cpp for documentation on each of the
16// supported formats.
17//
18//===----------------------------------------------------------------------===//
19
21#include "llvm/ADT/StringRef.h"
25#include "llvm/Support/Endian.h"
29#include "llvm/Support/LEB128.h"
30#include "llvm/Support/MD5.h"
32#include <algorithm>
33#include <cmath>
34#include <cstdint>
35#include <memory>
36#include <set>
37#include <system_error>
38#include <utility>
39#include <vector>
40
41#define DEBUG_TYPE "llvm-profdata"
42
43using namespace llvm;
44using namespace sampleprof;
45
46namespace llvm {
47namespace support {
48namespace endian {
49namespace {
50
51// Adapter class to llvm::support::endian::Writer for pwrite().
52struct SeekableWriter {
55 SeekableWriter(raw_pwrite_stream &OS, endianness Endian)
56 : OS(OS), Endian(Endian) {}
57
58 template <typename ValueType>
59 void pwrite(ValueType Val, size_t Offset) {
60 std::string StringBuf;
61 raw_string_ostream SStream(StringBuf);
62 Writer(SStream, Endian).write(Val);
63 OS.pwrite(StringBuf.data(), StringBuf.size(), Offset);
64 }
65};
66
67} // namespace
68} // namespace endian
69} // namespace support
70} // namespace llvm
71
73 SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
74 : FunctionPruningStrategy(ProfileMap, OutputSizeLimit) {
75 sortFuncProfiles(ProfileMap, SortedFunctions);
76}
77
78void DefaultFunctionPruningStrategy::Erase(size_t CurrentOutputSize) {
79 double D = (double)OutputSizeLimit / CurrentOutputSize;
80 size_t NewSize = (size_t)round(ProfileMap.size() * D * D);
81 size_t NumToRemove = ProfileMap.size() - NewSize;
82 if (NumToRemove < 1)
83 NumToRemove = 1;
84
85 assert(NumToRemove <= SortedFunctions.size());
86 for (const NameFunctionSamples &E :
87 llvm::drop_begin(SortedFunctions, SortedFunctions.size() - NumToRemove))
88 ProfileMap.erase(E.first);
89 SortedFunctions.resize(SortedFunctions.size() - NumToRemove);
90}
91
93 SampleProfileMap &ProfileMap, size_t OutputSizeLimit,
94 FunctionPruningStrategy *Strategy) {
95 if (OutputSizeLimit == 0)
96 return write(ProfileMap);
97
98 size_t OriginalFunctionCount = ProfileMap.size();
99
100 std::unique_ptr<raw_ostream> OriginalOutputStream;
101 OutputStream.swap(OriginalOutputStream);
102
103 size_t IterationCount = 0;
104 size_t TotalSize;
105
106 SmallVector<char> StringBuffer;
107 do {
108 StringBuffer.clear();
109 OutputStream.reset(new raw_svector_ostream(StringBuffer));
110 if (std::error_code EC = write(ProfileMap))
111 return EC;
112
113 TotalSize = StringBuffer.size();
114 // On Windows every "\n" is actually written as "\r\n" to disk but not to
115 // memory buffer, this difference should be added when considering the total
116 // output size.
117#ifdef _WIN32
118 if (Format == SPF_Text)
119 TotalSize += LineCount;
120#endif
121 if (TotalSize <= OutputSizeLimit)
122 break;
123
124 Strategy->Erase(TotalSize);
125 IterationCount++;
126 } while (ProfileMap.size() != 0);
127
128 if (ProfileMap.size() == 0)
130
131 OutputStream.swap(OriginalOutputStream);
132 OutputStream->write(StringBuffer.data(), StringBuffer.size());
133 LLVM_DEBUG(dbgs() << "Profile originally has " << OriginalFunctionCount
134 << " functions, reduced to " << ProfileMap.size() << " in "
135 << IterationCount << " iterations\n");
136 // Silence warning on Release build.
137 (void)OriginalFunctionCount;
138 (void)IterationCount;
140}
141
142std::error_code
144 std::vector<NameFunctionSamples> V;
145 sortFuncProfiles(ProfileMap, V);
146 for (const auto &I : V) {
147 if (std::error_code EC = writeSample(*I.second))
148 return EC;
149 }
151}
152
153std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) {
154 if (std::error_code EC = writeHeader(ProfileMap))
155 return EC;
156
157 if (std::error_code EC = writeFuncProfiles(ProfileMap))
158 return EC;
159
161}
162
163/// Return the current position and prepare to use it as the start
164/// position of a section given the section type \p Type and its position
165/// \p LayoutIdx in SectionHdrLayout.
168 uint32_t LayoutIdx) {
169 uint64_t SectionStart = OutputStream->tell();
170 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
171 const auto &Entry = SectionHdrLayout[LayoutIdx];
172 assert(Entry.Type == Type && "Unexpected section type");
173 // Use LocalBuf as a temporary output for writting data.
175 LocalBufStream.swap(OutputStream);
176 return SectionStart;
177}
178
179std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
182 std::string &UncompressedStrings =
183 static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
184 if (UncompressedStrings.size() == 0)
186 auto &OS = *OutputStream;
187 SmallVector<uint8_t, 128> CompressedStrings;
188 compression::zlib::compress(arrayRefFromStringRef(UncompressedStrings),
189 CompressedStrings,
191 encodeULEB128(UncompressedStrings.size(), OS);
192 encodeULEB128(CompressedStrings.size(), OS);
193 OS << toStringRef(CompressedStrings);
194 UncompressedStrings.clear();
196}
197
198/// Add a new section into section header table given the section type
199/// \p Type, its position \p LayoutIdx in SectionHdrLayout and the
200/// location \p SectionStart where the section should be written to.
202 SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) {
203 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
204 const auto &Entry = SectionHdrLayout[LayoutIdx];
205 assert(Entry.Type == Type && "Unexpected section type");
207 LocalBufStream.swap(OutputStream);
208 if (std::error_code EC = compressAndOutput())
209 return EC;
210 }
211 SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
212 OutputStream->tell() - SectionStart, LayoutIdx});
214}
215
216std::error_code
218 // When calling write on a different profile map, existing states should be
219 // cleared.
220 NameTable.clear();
221 CSNameTable.clear();
222 SecHdrTable.clear();
223
224 if (std::error_code EC = writeHeader(ProfileMap))
225 return EC;
226
227 std::string LocalBuf;
228 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
229 if (std::error_code EC = writeSections(ProfileMap))
230 return EC;
231
232 if (std::error_code EC = writeSecHdrTable())
233 return EC;
234
236}
237
239 const SampleContext &Context) {
240 if (Context.hasContext())
241 return writeCSNameIdx(Context);
242 else
244}
245
246std::error_code
248 const auto &Ret = CSNameTable.find(Context);
249 if (Ret == CSNameTable.end())
251 encodeULEB128(Ret->second, *OutputStream);
253}
254
255std::error_code
257 uint64_t Offset = OutputStream->tell();
258 auto &Context = S.getContext();
259 FuncOffsetTable[Context] = Offset - SecLBRProfileStart;
261 return writeBody(S);
262}
263
265 auto &OS = *OutputStream;
266
267 // Write out the table size.
268 encodeULEB128(FuncOffsetTable.size(), OS);
269
270 // Write out FuncOffsetTable.
271 auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) {
272 if (std::error_code EC = writeContextIdx(Context))
273 return EC;
275 return (std::error_code)sampleprof_error::success;
276 };
277
279 // Sort the contexts before writing them out. This is to help fast load all
280 // context profiles for a function as well as their callee contexts which
281 // can help profile-guided importing for ThinLTO.
282 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable(
283 FuncOffsetTable.begin(), FuncOffsetTable.end());
284 for (const auto &Entry : OrderedFuncOffsetTable) {
285 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
286 return EC;
287 }
289 } else {
290 for (const auto &Entry : FuncOffsetTable) {
291 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
292 return EC;
293 }
294 }
295
296 FuncOffsetTable.clear();
298}
299
301 const FunctionSamples &FunctionProfile) {
302 auto &OS = *OutputStream;
303 if (std::error_code EC = writeContextIdx(FunctionProfile.getContext()))
304 return EC;
305
307 encodeULEB128(FunctionProfile.getFunctionHash(), OS);
309 encodeULEB128(FunctionProfile.getContext().getAllAttributes(), OS);
310 }
311
313 // Recursively emit attributes for all callee samples.
314 uint64_t NumCallsites = 0;
315 for (const auto &J : FunctionProfile.getCallsiteSamples())
316 NumCallsites += J.second.size();
317 encodeULEB128(NumCallsites, OS);
318 for (const auto &J : FunctionProfile.getCallsiteSamples()) {
319 for (const auto &FS : J.second) {
320 LineLocation Loc = J.first;
323 if (std::error_code EC = writeFuncMetadata(FS.second))
324 return EC;
325 }
326 }
327 }
328
330}
331
333 const SampleProfileMap &Profiles) {
337 for (const auto &Entry : Profiles) {
338 if (std::error_code EC = writeFuncMetadata(Entry.second))
339 return EC;
340 }
342}
343
345 if (!UseMD5)
347
348 auto &OS = *OutputStream;
349 std::set<StringRef> V;
351
352 // Write out the MD5 name table. We wrote unencoded MD5 so reader can
353 // retrieve the name using the name index without having to read the
354 // whole name table.
355 encodeULEB128(NameTable.size(), OS);
357 for (auto N : V)
358 Writer.write(hashFuncName(N));
360}
361
363 const SampleProfileMap &ProfileMap) {
364 for (const auto &I : ProfileMap) {
365 addContext(I.second.getContext());
366 addNames(I.second);
367 }
368
369 // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag
370 // so compiler won't strip the suffix during profile matching after
371 // seeing the flag in the profile.
372 for (const auto &I : NameTable) {
373 if (I.first.contains(FunctionSamples::UniqSuffix)) {
375 break;
376 }
377 }
378
379 if (auto EC = writeNameTable())
380 return EC;
382}
383
385 // Sort the names to make CSNameTable deterministic.
386 std::set<SampleContext> OrderedContexts;
387 for (const auto &I : CSNameTable)
388 OrderedContexts.insert(I.first);
389 assert(OrderedContexts.size() == CSNameTable.size() &&
390 "Unmatched ordered and unordered contexts");
391 uint64_t I = 0;
392 for (auto &Context : OrderedContexts)
393 CSNameTable[Context] = I++;
394
395 auto &OS = *OutputStream;
396 encodeULEB128(OrderedContexts.size(), OS);
398 for (auto Context : OrderedContexts) {
399 auto Frames = Context.getContextFrames();
400 encodeULEB128(Frames.size(), OS);
401 for (auto &Callsite : Frames) {
402 if (std::error_code EC = writeNameIdx(Callsite.FuncName))
403 return EC;
404 encodeULEB128(Callsite.Location.LineOffset, OS);
405 encodeULEB128(Callsite.Location.Discriminator, OS);
406 }
407 }
408
410}
411
412std::error_code
414 if (ProfSymList && ProfSymList->size() > 0)
415 if (std::error_code EC = ProfSymList->write(*OutputStream))
416 return EC;
417
419}
420
422 SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) {
423 // The setting of SecFlagCompress should happen before markSectionStart.
424 if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
428 if (Type == SecFuncMetadata &&
437
438 uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
439 switch (Type) {
440 case SecProfSummary:
441 computeSummary(ProfileMap);
442 if (auto EC = writeSummary())
443 return EC;
444 break;
445 case SecNameTable:
446 if (auto EC = writeNameTableSection(ProfileMap))
447 return EC;
448 break;
449 case SecCSNameTable:
450 if (auto EC = writeCSNameTableSection())
451 return EC;
452 break;
453 case SecLBRProfile:
455 if (std::error_code EC = writeFuncProfiles(ProfileMap))
456 return EC;
457 break;
459 if (auto EC = writeFuncOffsetTable())
460 return EC;
461 break;
462 case SecFuncMetadata:
463 if (std::error_code EC = writeFuncMetadata(ProfileMap))
464 return EC;
465 break;
467 if (auto EC = writeProfileSymbolListSection())
468 return EC;
469 break;
470 default:
471 if (auto EC = writeCustomSection(Type))
472 return EC;
473 break;
474 }
475 if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
476 return EC;
478}
479
480std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
481 const SampleProfileMap &ProfileMap) {
482 // The const indices passed to writeOneSection below are specifying the
483 // positions of the sections in SectionHdrLayout. Look at
484 // initSectionHdrLayout to find out where each section is located in
485 // SectionHdrLayout.
486 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
487 return EC;
488 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
489 return EC;
490 if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap))
491 return EC;
492 if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap))
493 return EC;
494 if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap))
495 return EC;
496 if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap))
497 return EC;
498 if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap))
499 return EC;
501}
502
503static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap,
504 SampleProfileMap &ContextProfileMap,
505 SampleProfileMap &NoContextProfileMap) {
506 for (const auto &I : ProfileMap) {
507 if (I.second.getCallsiteSamples().size())
508 ContextProfileMap.insert({I.first, I.second});
509 else
510 NoContextProfileMap.insert({I.first, I.second});
511 }
512}
513
514std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
515 const SampleProfileMap &ProfileMap) {
516 SampleProfileMap ContextProfileMap, NoContextProfileMap;
517 splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
518
519 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
520 return EC;
521 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
522 return EC;
523 if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
524 return EC;
525 if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
526 return EC;
527 // Mark the section to have no context. Note section flag needs to be set
528 // before writing the section.
530 if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
531 return EC;
532 // Mark the section to have no context. Note section flag needs to be set
533 // before writing the section.
535 if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
536 return EC;
537 if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
538 return EC;
539 if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
540 return EC;
541
543}
544
545std::error_code SampleProfileWriterExtBinary::writeSections(
546 const SampleProfileMap &ProfileMap) {
547 std::error_code EC;
549 EC = writeDefaultLayout(ProfileMap);
550 else if (SecLayout == CtxSplitLayout)
551 EC = writeCtxSplitLayout(ProfileMap);
552 else
553 llvm_unreachable("Unsupported layout");
554 return EC;
555}
556
557/// Write samples to a text file.
558///
559/// Note: it may be tempting to implement this in terms of
560/// FunctionSamples::print(). Please don't. The dump functionality is intended
561/// for debugging and has no specified form.
562///
563/// The format used here is more structured and deliberate because
564/// it needs to be parsed by the SampleProfileReaderText class.
566 auto &OS = *OutputStream;
568 OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples();
569 else
570 OS << S.getName() << ":" << S.getTotalSamples();
571
572 if (Indent == 0)
573 OS << ":" << S.getHeadSamples();
574 OS << "\n";
575 LineCount++;
576
578 for (const auto &I : SortedSamples.get()) {
579 LineLocation Loc = I->first;
580 const SampleRecord &Sample = I->second;
581 OS.indent(Indent + 1);
582 if (Loc.Discriminator == 0)
583 OS << Loc.LineOffset << ": ";
584 else
585 OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
586
587 OS << Sample.getSamples();
588
589 for (const auto &J : Sample.getSortedCallTargets())
590 OS << " " << J.first << ":" << J.second;
591 OS << "\n";
592 LineCount++;
593 }
594
597 Indent += 1;
598 for (const auto &I : SortedCallsiteSamples.get())
599 for (const auto &FS : I->second) {
600 LineLocation Loc = I->first;
601 const FunctionSamples &CalleeSamples = FS.second;
602 OS.indent(Indent);
603 if (Loc.Discriminator == 0)
604 OS << Loc.LineOffset << ": ";
605 else
606 OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
607 if (std::error_code EC = writeSample(CalleeSamples))
608 return EC;
609 }
610 Indent -= 1;
611
613 OS.indent(Indent + 1);
614 OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
615 LineCount++;
616 }
617
618 if (S.getContext().getAllAttributes()) {
619 OS.indent(Indent + 1);
620 OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n";
621 LineCount++;
622 }
623
625}
626
627std::error_code
629 assert(!Context.hasContext() && "cs profile is not supported");
630 return writeNameIdx(Context.getName());
631}
632
634 auto &NTable = getNameTable();
635 const auto &Ret = NTable.find(FName);
636 if (Ret == NTable.end())
638 encodeULEB128(Ret->second, *OutputStream);
640}
641
643 auto &NTable = getNameTable();
644 NTable.insert(std::make_pair(FName, 0));
645}
646
648 addName(Context.getName());
649}
650
652 // Add all the names in indirect call targets.
653 for (const auto &I : S.getBodySamples()) {
654 const SampleRecord &Sample = I.second;
655 for (const auto &J : Sample.getCallTargets())
656 addName(J.first());
657 }
658
659 // Recursively add all the names for inlined callsites.
660 for (const auto &J : S.getCallsiteSamples())
661 for (const auto &FS : J.second) {
662 const FunctionSamples &CalleeSamples = FS.second;
663 addName(CalleeSamples.getName());
664 addNames(CalleeSamples);
665 }
666}
667
669 const SampleContext &Context) {
670 if (Context.hasContext()) {
671 for (auto &Callsite : Context.getContextFrames())
672 SampleProfileWriterBinary::addName(Callsite.FuncName);
673 CSNameTable.insert(std::make_pair(Context, 0));
674 } else {
676 }
677}
678
680 MapVector<StringRef, uint32_t> &NameTable, std::set<StringRef> &V) {
681 // Sort the names to make NameTable deterministic.
682 for (const auto &I : NameTable)
683 V.insert(I.first);
684 int i = 0;
685 for (const StringRef &N : V)
686 NameTable[N] = i++;
687}
688
690 auto &OS = *OutputStream;
691 std::set<StringRef> V;
693
694 // Write out the name table.
695 encodeULEB128(NameTable.size(), OS);
696 for (auto N : V) {
697 OS << N;
698 encodeULEB128(0, OS);
699 }
701}
702
703std::error_code
705 auto &OS = *OutputStream;
706 // Write file magic identifier.
710}
711
712std::error_code
714 // When calling write on a different profile map, existing names should be
715 // cleared.
716 NameTable.clear();
717
719
720 computeSummary(ProfileMap);
721 if (auto EC = writeSummary())
722 return EC;
723
724 // Generate the name table for all the functions referenced in the profile.
725 for (const auto &I : ProfileMap) {
726 addContext(I.second.getContext());
727 addNames(I.second);
728 }
729
732}
733
735 for (auto &Entry : SectionHdrLayout)
737}
738
741}
742
743void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
745
746 Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
747 SecHdrTableOffset = OutputStream->tell();
748 for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
749 Writer.write(static_cast<uint64_t>(-1));
750 Writer.write(static_cast<uint64_t>(-1));
751 Writer.write(static_cast<uint64_t>(-1));
752 Writer.write(static_cast<uint64_t>(-1));
753 }
754}
755
756std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
757 assert(SecHdrTable.size() == SectionHdrLayout.size() &&
758 "SecHdrTable entries doesn't match SectionHdrLayout");
759 SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
760 for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
761 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
762 }
763
764 // Write the section header table in the order specified in
765 // SectionHdrLayout. SectionHdrLayout specifies the sections
766 // order in which profile reader expect to read, so the section
767 // header table should be written in the order in SectionHdrLayout.
768 // Note that the section order in SecHdrTable may be different
769 // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
770 // needs to be computed after SecLBRProfile (the order in SecHdrTable),
771 // but it needs to be read before SecLBRProfile (the order in
772 // SectionHdrLayout). So we use IndexMap above to switch the order.
773 support::endian::SeekableWriter Writer(
775 for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
776 LayoutIdx++) {
777 assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
778 "Incorrect LayoutIdx in SecHdrTable");
779 auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
780 Writer.pwrite(static_cast<uint64_t>(Entry.Type),
781 SecHdrTableOffset + 4 * LayoutIdx * sizeof(uint64_t));
782 Writer.pwrite(static_cast<uint64_t>(Entry.Flags),
783 SecHdrTableOffset + (4 * LayoutIdx + 1) * sizeof(uint64_t));
784 Writer.pwrite(static_cast<uint64_t>(Entry.Offset),
785 SecHdrTableOffset + (4 * LayoutIdx + 2) * sizeof(uint64_t));
786 Writer.pwrite(static_cast<uint64_t>(Entry.Size),
787 SecHdrTableOffset + (4 * LayoutIdx + 3) * sizeof(uint64_t));
788 }
789
791}
792
793std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
794 const SampleProfileMap &ProfileMap) {
795 auto &OS = *OutputStream;
796 FileStart = OS.tell();
798
799 allocSecHdrTable();
801}
802
804 auto &OS = *OutputStream;
805 encodeULEB128(Summary->getTotalCount(), OS);
806 encodeULEB128(Summary->getMaxCount(), OS);
807 encodeULEB128(Summary->getMaxFunctionCount(), OS);
808 encodeULEB128(Summary->getNumCounts(), OS);
809 encodeULEB128(Summary->getNumFunctions(), OS);
810 const std::vector<ProfileSummaryEntry> &Entries =
811 Summary->getDetailedSummary();
812 encodeULEB128(Entries.size(), OS);
813 for (auto Entry : Entries) {
814 encodeULEB128(Entry.Cutoff, OS);
815 encodeULEB128(Entry.MinCount, OS);
816 encodeULEB128(Entry.NumCounts, OS);
817 }
819}
821 auto &OS = *OutputStream;
822 if (std::error_code EC = writeContextIdx(S.getContext()))
823 return EC;
824
826
827 // Emit all the body samples.
828 encodeULEB128(S.getBodySamples().size(), OS);
829 for (const auto &I : S.getBodySamples()) {
830 LineLocation Loc = I.first;
831 const SampleRecord &Sample = I.second;
834 encodeULEB128(Sample.getSamples(), OS);
835 encodeULEB128(Sample.getCallTargets().size(), OS);
836 for (const auto &J : Sample.getSortedCallTargets()) {
837 StringRef Callee = J.first;
838 uint64_t CalleeSamples = J.second;
839 if (std::error_code EC = writeNameIdx(Callee))
840 return EC;
841 encodeULEB128(CalleeSamples, OS);
842 }
843 }
844
845 // Recursively emit all the callsite samples.
846 uint64_t NumCallsites = 0;
847 for (const auto &J : S.getCallsiteSamples())
848 NumCallsites += J.second.size();
849 encodeULEB128(NumCallsites, OS);
850 for (const auto &J : S.getCallsiteSamples())
851 for (const auto &FS : J.second) {
852 LineLocation Loc = J.first;
853 const FunctionSamples &CalleeSamples = FS.second;
856 if (std::error_code EC = writeBody(CalleeSamples))
857 return EC;
858 }
859
861}
862
863/// Write samples of a top-level function to a binary file.
864///
865/// \returns true if the samples were written successfully, false otherwise.
866std::error_code
869 return writeBody(S);
870}
871
872/// Create a sample profile file writer based on the specified format.
873///
874/// \param Filename The file to create.
875///
876/// \param Format Encoding format for the profile file.
877///
878/// \returns an error code indicating the status of the created writer.
881 std::error_code EC;
882 std::unique_ptr<raw_ostream> OS;
884 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
885 else
886 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_TextWithCRLF));
887 if (EC)
888 return EC;
889
890 return create(OS, Format);
891}
892
893/// Create a sample profile stream writer based on the specified format.
894///
895/// \param OS The output stream to store the profile data to.
896///
897/// \param Format Encoding format for the profile file.
898///
899/// \returns an error code indicating the status of the created writer.
901SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
903 std::error_code EC;
904 std::unique_ptr<SampleProfileWriter> Writer;
905
906 // Currently only Text and Extended Binary format are supported for CSSPGO.
910
911 if (Format == SPF_Binary)
912 Writer.reset(new SampleProfileWriterRawBinary(OS));
913 else if (Format == SPF_Ext_Binary)
914 Writer.reset(new SampleProfileWriterExtBinary(OS));
915 else if (Format == SPF_Text)
916 Writer.reset(new SampleProfileWriterText(OS));
917 else if (Format == SPF_GCC)
919 else
921
922 if (EC)
923 return EC;
924
925 Writer->Format = Format;
926 return std::move(Writer);
927}
928
931 Summary = Builder.computeSummaryForProfiles(ProfileMap);
932}
assume Assume Builder
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Provides ErrorOr<T> smart pointer.
#define I(x, y, z)
Definition: MD5.cpp:58
LLVMContext & Context
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
endianness Endian
static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap, SampleProfileMap &ContextProfileMap, SampleProfileMap &NoContextProfileMap)
raw_pwrite_stream & OS
Represents either an error or a value T.
Definition: ErrorOr.h:56
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
static const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Definition: ProfileCommon.h:62
size_t size() const
Definition: SmallVector.h:91
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:289
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
unsigned size() const
Definition: StringMap.h:95
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:454
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:134
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:428
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
Definition: raw_ostream.h:436
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
DefaultFunctionPruningStrategy(SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
void Erase(size_t CurrentOutputSize) override
In this default implementation, functions with fewest samples are dropped first.
When writing a profile with size limit, user may want to use a different strategy to reduce function ...
virtual void Erase(size_t CurrentOutputSize)=0
SampleProfileWriter::writeWithSizeLimit() calls this after every write iteration if the output size s...
Representation of the samples collected for a function.
Definition: SampleProf.h:751
static constexpr const char * UniqSuffix
Definition: SampleProf.h:1097
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:945
static bool ProfileIsFS
If this profile uses flow sensitive discriminators.
Definition: SampleProf.h:1194
SampleContext & getContext() const
Definition: SampleProf.h:1183
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition: SampleProf.h:937
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
Definition: SampleProf.h:979
StringRef getName() const
Return the function name.
Definition: SampleProf.h:1071
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
Definition: SampleProf.h:976
std::error_code write(raw_ostream &OS)
Definition: SampleProf.cpp:398
std::string toString() const
Definition: SampleProf.h:637
This class provides operator overloads to the map container using MD5 as the key type,...
Definition: SampleProf.h:1382
size_t erase(const SampleContext &Ctx)
Definition: SampleProf.h:1408
void stablizeNameTable(MapVector< StringRef, uint32_t > &NameTable, std::set< StringRef > &V)
virtual void addContext(const SampleContext &Context)
virtual std::error_code writeMagicIdent(SampleProfileFormat Format)
std::error_code writeNameIdx(StringRef FName)
virtual std::error_code writeContextIdx(const SampleContext &Context)
std::error_code writeSample(const FunctionSamples &S) override
Write samples of a top-level function to a binary file.
std::error_code writeHeader(const SampleProfileMap &ProfileMap) override
Write a file header for the profile file.
virtual MapVector< StringRef, uint32_t > & getNameTable()
MapVector< StringRef, uint32_t > NameTable
std::error_code writeBody(const FunctionSamples &S)
std::error_code writeNameTableSection(const SampleProfileMap &ProfileMap)
SmallVector< SecHdrTableEntry, 8 > SectionHdrLayout
std::error_code writeFuncMetadata(const SampleProfileMap &Profiles)
virtual std::error_code writeCustomSection(SecType Type)=0
virtual std::error_code writeOneSection(SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap)
std::error_code writeCSNameIdx(const SampleContext &Context)
virtual std::error_code writeSections(const SampleProfileMap &ProfileMap)=0
void addSectionFlag(SecType Type, SecFlagType Flag)
uint64_t markSectionStart(SecType Type, uint32_t LayoutIdx)
Return the current position and prepare to use it as the start position of a section given the sectio...
void addContext(const SampleContext &Context) override
std::error_code addNewSection(SecType Sec, uint32_t LayoutIdx, uint64_t SectionStart)
Add a new section into section header table given the section type Type, its position LayoutIdx in Se...
std::error_code write(const SampleProfileMap &ProfileMap) override
Write all the sample profiles in the given map of samples.
std::error_code writeContextIdx(const SampleContext &Context) override
std::error_code writeSample(const FunctionSamples &S) override
Write samples of a top-level function to a binary file.
Sample-based profile writer (text format).
std::error_code writeSample(const FunctionSamples &S) override
Write samples to a text file.
std::unique_ptr< ProfileSummary > Summary
Profile summary.
virtual std::error_code writeSample(const FunctionSamples &S)=0
Write sample profiles in S.
SampleProfileFormat Format
Profile format.
std::error_code writeWithSizeLimitInternal(SampleProfileMap &ProfileMap, size_t OutputSizeLimit, FunctionPruningStrategy *Strategy)
void computeSummary(const SampleProfileMap &ProfileMap)
Compute summary for this profile.
virtual std::error_code writeFuncProfiles(const SampleProfileMap &ProfileMap)
std::unique_ptr< raw_ostream > OutputStream
Output stream where to emit the profile to.
size_t LineCount
For writeWithSizeLimit in text mode, each newline takes 1 additional byte on Windows when actually wr...
static ErrorOr< std::unique_ptr< SampleProfileWriter > > create(StringRef Filename, SampleProfileFormat Format)
Profile writer factory.
virtual std::error_code writeHeader(const SampleProfileMap &ProfileMap)=0
Write a file header for the profile file.
virtual std::error_code write(const SampleProfileMap &ProfileMap)
Write all the sample profiles in the given map of samples.
Representation of a single sample record.
Definition: SampleProf.h:339
const CallTargetMap & getCallTargets() const
Definition: SampleProf.h:407
uint64_t getSamples() const
Definition: SampleProf.h:406
const SortedCallTargetSet getSortedCallTargets() const
Definition: SampleProf.h:408
Sort a LocationT->SampleT map by LocationT.
Definition: SampleProf.h:1425
const SamplesWithLocList & get() const
Definition: SampleProf.h:1438
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
constexpr int BestSizeCompression
Definition: Compression.h:39
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
static uint64_t hashFuncName(StringRef F)
Definition: SampleProf.h:321
void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
Definition: SampleProf.cpp:201
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition: SampleProf.h:105
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
Definition: SampleProf.h:1416
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:257
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:273
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
static uint64_t SPVersion()
Definition: SampleProf.h:122
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:768
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:330
@ Offset
Definition: DWP.cpp:440
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
#define N
Represents the relative location of an instruction.
Definition: SampleProf.h:289
Adapter to write values to a stream in a particular byte order.
Definition: EndianStream.h:68
void write(ArrayRef< value_type > Val)
Definition: EndianStream.h:72
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition: xxhash.cpp:64