LLVM 23.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"
28#include "llvm/Support/LEB128.h"
29#include "llvm/Support/MD5.h"
31#include <cmath>
32#include <cstdint>
33#include <memory>
34#include <system_error>
35#include <utility>
36#include <vector>
37
38#define DEBUG_TYPE "llvm-profdata"
39
40using namespace llvm;
41using namespace sampleprof;
42
43// To begin with, make this option off by default.
45 "extbinary-write-vtable-type-prof", cl::init(false), cl::Hidden,
46 cl::desc("Write vtable type profile in ext-binary sample profile writer"));
47
49 "sample-profile-format-version", cl::init(DefaultVersion), cl::Hidden,
50 cl::desc("Format version to write for extensible binary profiles"));
51
52namespace llvm {
53namespace support {
54namespace endian {
55namespace {
56
57// Adapter class to llvm::support::endian::Writer for pwrite().
58struct SeekableWriter {
60 endianness Endian;
61 SeekableWriter(raw_pwrite_stream &OS, endianness Endian)
62 : OS(OS), Endian(Endian) {}
63
64 template <typename ValueType> void pwrite(ValueType Val, size_t Offset) {
65 std::string StringBuf;
66 raw_string_ostream SStream(StringBuf);
67 Writer(SStream, Endian).write(Val);
68 OS.pwrite(StringBuf.data(), StringBuf.size(), Offset);
69 }
70};
71
72} // namespace
73} // namespace endian
74} // namespace support
75} // namespace llvm
76
82
83void DefaultFunctionPruningStrategy::Erase(size_t CurrentOutputSize) {
84 double D = (double)OutputSizeLimit / CurrentOutputSize;
85 size_t NewSize = (size_t)round(ProfileMap.size() * D * D);
86 size_t NumToRemove = ProfileMap.size() - NewSize;
87 if (NumToRemove < 1)
88 NumToRemove = 1;
89
90 assert(NumToRemove <= SortedFunctions.size());
91 for (const NameFunctionSamples &E :
92 llvm::drop_begin(SortedFunctions, SortedFunctions.size() - NumToRemove))
93 ProfileMap.erase(E.first);
94 SortedFunctions.resize(SortedFunctions.size() - NumToRemove);
95}
96
98 SampleProfileMap &ProfileMap, size_t OutputSizeLimit,
99 FunctionPruningStrategy *Strategy) {
100 if (OutputSizeLimit == 0)
101 return write(ProfileMap);
102
103 size_t OriginalFunctionCount = ProfileMap.size();
104
105 std::unique_ptr<raw_ostream> OriginalOutputStream;
106 OutputStream.swap(OriginalOutputStream);
107
108 size_t IterationCount = 0;
109 size_t TotalSize;
110
111 SmallVector<char> StringBuffer;
112 do {
113 StringBuffer.clear();
114 OutputStream.reset(new raw_svector_ostream(StringBuffer));
115 if (std::error_code EC = write(ProfileMap))
116 return EC;
117
118 TotalSize = StringBuffer.size();
119 // On Windows every "\n" is actually written as "\r\n" to disk but not to
120 // memory buffer, this difference should be added when considering the total
121 // output size.
122#ifdef _WIN32
123 if (Format == SPF_Text)
124 TotalSize += LineCount;
125#endif
126 if (TotalSize <= OutputSizeLimit)
127 break;
128
129 Strategy->Erase(TotalSize);
130 IterationCount++;
131 } while (ProfileMap.size() != 0);
132
133 if (ProfileMap.size() == 0)
135
136 OutputStream.swap(OriginalOutputStream);
137 OutputStream->write(StringBuffer.data(), StringBuffer.size());
138 LLVM_DEBUG(dbgs() << "Profile originally has " << OriginalFunctionCount
139 << " functions, reduced to " << ProfileMap.size() << " in "
140 << IterationCount << " iterations\n");
141 // Silence warning on Release build.
142 (void)OriginalFunctionCount;
143 (void)IterationCount;
145}
146
147std::error_code
149 std::vector<NameFunctionSamples> V;
150 sortFuncProfiles(ProfileMap, V);
151 for (const auto &I : V) {
152 if (std::error_code EC = writeSample(*I.second))
153 return EC;
154 }
156}
157
158std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) {
159 if (std::error_code EC = writeHeader(ProfileMap))
160 return EC;
161
162 if (std::error_code EC = writeFuncProfiles(ProfileMap))
163 return EC;
164
166}
167
168/// Return the current position and prepare to use it as the start
169/// position of a section given the section type \p Type and its position
170/// \p LayoutIdx in SectionHdrLayout.
173 uint32_t LayoutIdx) {
174 uint64_t SectionStart = OutputStream->tell();
175 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
176 const auto &Entry = SectionHdrLayout[LayoutIdx];
177 assert(Entry.Type == Type && "Unexpected section type");
178 // Use LocalBuf as a temporary output for writting data.
180 LocalBufStream.swap(OutputStream);
181 return SectionStart;
182}
183
184std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
187 std::string &UncompressedStrings =
188 static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
189 if (UncompressedStrings.size() == 0)
191 auto &OS = *OutputStream;
192 SmallVector<uint8_t, 128> CompressedStrings;
194 CompressedStrings,
196 encodeULEB128(UncompressedStrings.size(), OS);
197 encodeULEB128(CompressedStrings.size(), OS);
198 OS << toStringRef(CompressedStrings);
199 UncompressedStrings.clear();
201}
202
203/// Add a new section into section header table given the section type
204/// \p Type, its position \p LayoutIdx in SectionHdrLayout and the
205/// location \p SectionStart where the section should be written to.
207 SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) {
208 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
209 const auto &Entry = SectionHdrLayout[LayoutIdx];
210 assert(Entry.Type == Type && "Unexpected section type");
212 LocalBufStream.swap(OutputStream);
213 if (std::error_code EC = compressAndOutput())
214 return EC;
215 }
216 SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
217 OutputStream->tell() - SectionStart, LayoutIdx});
219}
220
221std::error_code
223 // When calling write on a different profile map, existing states should be
224 // cleared.
225 NameTable.clear();
226 CSNameTable.clear();
227 SecHdrTable.clear();
228
229 if (std::error_code EC = writeHeader(ProfileMap))
230 return EC;
231
232 std::string LocalBuf;
233 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
234 if (std::error_code EC = writeSections(ProfileMap))
235 return EC;
236
237 if (std::error_code EC = writeSecHdrTable())
238 return EC;
239
241}
242
244 const SampleContext &Context) {
245 if (Context.hasContext())
246 return writeCSNameIdx(Context);
247 else
248 return SampleProfileWriterBinary::writeNameIdx(Context.getFunction());
249}
250
251std::error_code
253 const auto &Ret = CSNameTable.find(Context);
254 if (Ret == CSNameTable.end())
256 encodeULEB128(Ret->second, *OutputStream);
258}
259
260std::error_code
262 uint64_t Offset = OutputStream->tell();
263 auto &Context = S.getContext();
264 FuncOffsetTable[Context] = Offset - SecLBRProfileStart;
266 return writeBody(S);
267}
268
270 auto &OS = *OutputStream;
271
272 // Write out the table size.
273 encodeULEB128(FuncOffsetTable.size(), OS);
274
275 // Write out FuncOffsetTable.
276 auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) {
277 if (std::error_code EC = writeContextIdx(Context))
278 return EC;
280 return (std::error_code)sampleprof_error::success;
281 };
282
284 // Sort the contexts before writing them out. This is to help fast load all
285 // context profiles for a function as well as their callee contexts which
286 // can help profile-guided importing for ThinLTO.
287 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable(
288 FuncOffsetTable.begin(), FuncOffsetTable.end());
289 for (const auto &Entry : OrderedFuncOffsetTable) {
290 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
291 return EC;
292 }
294 } else {
295 for (const auto &Entry : FuncOffsetTable) {
296 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
297 return EC;
298 }
299 }
300
301 FuncOffsetTable.clear();
303}
304
306 const FunctionSamples &FunctionProfile) {
307 auto &OS = *OutputStream;
308 if (std::error_code EC = writeContextIdx(FunctionProfile.getContext()))
309 return EC;
310
312 encodeULEB128(FunctionProfile.getFunctionHash(), OS);
314 encodeULEB128(FunctionProfile.getContext().getAllAttributes(), OS);
315 }
316
318 // Recursively emit attributes for all callee samples.
319 uint64_t NumCallsites = 0;
320 for (const auto &J : FunctionProfile.getCallsiteSamples())
321 NumCallsites += J.second.size();
322 encodeULEB128(NumCallsites, OS);
323 for (const auto &J : FunctionProfile.getCallsiteSamples()) {
324 for (const auto &FS : J.second) {
325 LineLocation Loc = J.first;
326 encodeULEB128(Loc.LineOffset, OS);
327 encodeULEB128(Loc.Discriminator, OS);
328 if (std::error_code EC = writeFuncMetadata(FS.second))
329 return EC;
330 }
331 }
332 }
333
335}
336
338 const SampleProfileMap &Profiles) {
342 for (const auto &Entry : Profiles) {
343 if (std::error_code EC = writeFuncMetadata(Entry.second))
344 return EC;
345 }
347}
348
349template <class KeyT, class ValT>
354
355 llvm::sort(Entries,
356 [](const auto *L, const auto *R) { return L->first < R->first; });
357
358 for (const auto &[I, Entry] : llvm::enumerate(Entries))
359 Entry->second = I;
360
361 return Entries;
362}
363
365 if (!UseMD5)
367
368 auto &OS = *OutputStream;
369
370 // Write out the MD5 name table. We wrote unencoded MD5 so reader can
371 // retrieve the name using the name index without having to read the
372 // whole name table.
373 encodeULEB128(NameTable.size(), OS);
375 for (const auto *Entry : stabilizeTable(NameTable))
376 Writer.write(Entry->first.getHashCode());
378}
379
381 const SampleProfileMap &ProfileMap) {
382 for (const auto &I : ProfileMap) {
383 addContext(I.second.getContext());
384 addNames(I.second);
385 }
386
387 // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag
388 // so compiler won't strip the suffix during profile matching after
389 // seeing the flag in the profile.
390 // Original names are unavailable if using MD5, so this option has no use.
391 if (!UseMD5) {
392 for (const auto &I : NameTable) {
393 if (I.first.stringRef().contains(FunctionSamples::UniqSuffix)) {
395 break;
396 }
397 }
398 }
399
400 if (auto EC = writeNameTable())
401 return EC;
403}
404
406 auto &OS = *OutputStream;
407 encodeULEB128(CSNameTable.size(), OS);
409 for (const auto *Entry : stabilizeTable(CSNameTable)) {
410 auto Frames = Entry->first.getContextFrames();
411 encodeULEB128(Frames.size(), OS);
412 for (auto &Callsite : Frames) {
413 if (std::error_code EC = writeNameIdx(Callsite.Func))
414 return EC;
415 encodeULEB128(Callsite.Location.LineOffset, OS);
416 encodeULEB128(Callsite.Location.Discriminator, OS);
417 }
418 }
419
421}
422
423std::error_code
425 if (ProfSymList && ProfSymList->size() > 0)
426 if (std::error_code EC = ProfSymList->write(*OutputStream))
427 return EC;
428
430}
431
433 SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) {
434 // The setting of SecFlagCompress should happen before markSectionStart.
435 if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
439 if (Type == SecFuncMetadata &&
451
452 uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
453 switch (Type) {
454 case SecProfSummary:
455 computeSummary(ProfileMap);
456 if (auto EC = writeSummary())
457 return EC;
458 break;
459 case SecNameTable:
460 if (auto EC = writeNameTableSection(ProfileMap))
461 return EC;
462 break;
463 case SecCSNameTable:
464 if (auto EC = writeCSNameTableSection())
465 return EC;
466 break;
467 case SecLBRProfile:
469 if (std::error_code EC = writeFuncProfiles(ProfileMap))
470 return EC;
471 break;
473 if (auto EC = writeFuncOffsetTable())
474 return EC;
475 break;
476 case SecFuncMetadata:
477 if (std::error_code EC = writeFuncMetadata(ProfileMap))
478 return EC;
479 break;
481 if (auto EC = writeProfileSymbolListSection())
482 return EC;
483 break;
484 default:
485 if (auto EC = writeCustomSection(Type))
486 return EC;
487 break;
488 }
489 if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
490 return EC;
492}
493
499
500std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
501 const SampleProfileMap &ProfileMap) {
502 // The const indices passed to writeOneSection below are specifying the
503 // positions of the sections in SectionHdrLayout. Look at
504 // initSectionHdrLayout to find out where each section is located in
505 // SectionHdrLayout.
506 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
507 return EC;
508 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
509 return EC;
510 if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap))
511 return EC;
512 if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap))
513 return EC;
514 if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap))
515 return EC;
516 if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap))
517 return EC;
518 if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap))
519 return EC;
521}
522
523static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap,
524 SampleProfileMap &ContextProfileMap,
525 SampleProfileMap &NoContextProfileMap) {
526 for (const auto &I : ProfileMap) {
527 if (I.second.getCallsiteSamples().size())
528 ContextProfileMap.insert({I.first, I.second});
529 else
530 NoContextProfileMap.insert({I.first, I.second});
531 }
532}
533
534std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
535 const SampleProfileMap &ProfileMap) {
536 SampleProfileMap ContextProfileMap, NoContextProfileMap;
537 splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
538
539 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
540 return EC;
541 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
542 return EC;
543 if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
544 return EC;
545 if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
546 return EC;
547 // Mark the section to have no context. Note section flag needs to be set
548 // before writing the section.
550 if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
551 return EC;
552 // Mark the section to have no context. Note section flag needs to be set
553 // before writing the section.
555 if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
556 return EC;
557 if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
558 return EC;
559 if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
560 return EC;
561
563}
564
565std::error_code SampleProfileWriterExtBinary::writeSections(
566 const SampleProfileMap &ProfileMap) {
567 std::error_code EC;
569 EC = writeDefaultLayout(ProfileMap);
570 else if (SecLayout == CtxSplitLayout)
571 EC = writeCtxSplitLayout(ProfileMap);
572 else
573 llvm_unreachable("Unsupported layout");
574 return EC;
575}
576
577/// Write samples to a text file.
578///
579/// Note: it may be tempting to implement this in terms of
580/// FunctionSamples::print(). Please don't. The dump functionality is intended
581/// for debugging and has no specified form.
582///
583/// The format used here is more structured and deliberate because
584/// it needs to be parsed by the SampleProfileReaderText class.
586 auto &OS = *OutputStream;
588 OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples();
589 else
590 OS << S.getFunction() << ":" << S.getTotalSamples();
591
592 if (Indent == 0)
593 OS << ":" << S.getHeadSamples();
594 OS << "\n";
595 LineCount++;
596
598 for (const auto &I : SortedSamples.get()) {
599 LineLocation Loc = I->first;
600 const SampleRecord &Sample = I->second;
601 OS.indent(Indent + 1);
602 Loc.print(OS);
603 OS << ": " << Sample.getSamples();
604
605 for (const auto &J : Sample.getSortedCallTargets())
606 OS << " " << J.first << ":" << J.second;
607 OS << "\n";
608 LineCount++;
609
610 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
611 Map && !Map->empty()) {
612 OS.indent(Indent + 1);
613 Loc.print(OS);
614 OS << ": ";
615 OS << kVTableProfPrefix;
616 for (const auto [TypeName, Count] : *Map) {
617 OS << TypeName << ":" << Count << " ";
618 }
619 OS << "\n";
620 LineCount++;
621 }
622 }
623
626 Indent += 1;
627 for (const auto *Element : SortedCallsiteSamples.get()) {
628 // Element is a pointer to a pair of LineLocation and FunctionSamplesMap.
629 const auto &[Loc, FunctionSamplesMap] = *Element;
630 for (const FunctionSamples &CalleeSamples :
632 OS.indent(Indent);
633 Loc.print(OS);
634 OS << ": ";
635 if (std::error_code EC = writeSample(CalleeSamples))
636 return EC;
637 }
638
639 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
640 Map && !Map->empty()) {
641 OS.indent(Indent);
642 Loc.print(OS);
643 OS << ": ";
644 OS << kVTableProfPrefix;
645 for (const auto [TypeId, Count] : *Map) {
646 OS << TypeId << ":" << Count << " ";
647 }
648 OS << "\n";
649 LineCount++;
650 }
651 }
652
653 Indent -= 1;
654
656 OS.indent(Indent + 1);
657 OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
658 LineCount++;
659 }
660
661 if (S.getContext().getAllAttributes()) {
662 OS.indent(Indent + 1);
663 OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n";
664 LineCount++;
665 }
666
667 if (Indent == 0 && MarkFlatProfiles && S.getCallsiteSamples().size() == 0)
668 OS << " !Flat\n";
669
671}
672
673std::error_code
675 assert(!Context.hasContext() && "cs profile is not supported");
676 return writeNameIdx(Context.getFunction());
677}
678
680 auto &NTable = getNameTable();
681 const auto &Ret = NTable.find(FName);
682 if (Ret == NTable.end())
684 encodeULEB128(Ret->second, *OutputStream);
686}
687
689 auto &NTable = getNameTable();
690 NTable.insert(std::make_pair(FName, 0));
691}
692
694 addName(Context.getFunction());
695}
696
698 // Add all the names in indirect call targets.
699 for (const auto &I : S.getBodySamples()) {
700 const SampleRecord &Sample = I.second;
701 for (const auto &J : Sample.getCallTargets())
702 addName(J.first);
703 }
704
705 // Recursively add all the names for inlined callsites.
706 for (const auto &J : S.getCallsiteSamples())
707 for (const auto &FS : J.second) {
708 const FunctionSamples &CalleeSamples = FS.second;
709 addName(CalleeSamples.getFunction());
710 addNames(CalleeSamples);
711 }
712
713 if (!WriteVTableProf)
714 return;
715 // Add all the vtable names to NameTable.
716 for (const auto &VTableAccessCountMap :
718 // Add type name to NameTable.
719 for (const auto Type : llvm::make_first_range(VTableAccessCountMap)) {
720 addName(Type);
721 }
722 }
723}
724
726 const SampleContext &Context) {
727 if (Context.hasContext()) {
728 for (auto &Callsite : Context.getContextFrames())
730 CSNameTable.insert(std::make_pair(Context, 0));
731 } else {
732 SampleProfileWriterBinary::addName(Context.getFunction());
733 }
734}
735
737 auto &OS = *OutputStream;
738
739 // Write out the name table.
740 encodeULEB128(NameTable.size(), OS);
741 for (const auto *Entry : stabilizeTable(NameTable)) {
742 OS << Entry->first;
743 encodeULEB128(0, OS);
744 }
746}
747
748std::error_code
756
757std::error_code
759 // When calling write on a different profile map, existing names should be
760 // cleared.
761 NameTable.clear();
762
764
765 computeSummary(ProfileMap);
766 if (auto EC = writeSummary())
767 return EC;
768
769 // Generate the name table for all the functions referenced in the profile.
770 for (const auto &I : ProfileMap) {
771 addContext(I.second.getContext());
772 addNames(I.second);
773 }
774
777}
778
783
787
788void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
790
791 Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
792 SecHdrTableOffset = OutputStream->tell();
793 for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
794 Writer.write(static_cast<uint64_t>(-1));
795 Writer.write(static_cast<uint64_t>(-1));
796 Writer.write(static_cast<uint64_t>(-1));
797 Writer.write(static_cast<uint64_t>(-1));
798 }
799}
800
801std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
802 assert(SecHdrTable.size() == SectionHdrLayout.size() &&
803 "SecHdrTable entries doesn't match SectionHdrLayout");
804 SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
805 for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
806 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
807 }
808
809 // Write the section header table in the order specified in
810 // SectionHdrLayout. SectionHdrLayout specifies the sections
811 // order in which profile reader expect to read, so the section
812 // header table should be written in the order in SectionHdrLayout.
813 // Note that the section order in SecHdrTable may be different
814 // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
815 // needs to be computed after SecLBRProfile (the order in SecHdrTable),
816 // but it needs to be read before SecLBRProfile (the order in
817 // SectionHdrLayout). So we use IndexMap above to switch the order.
818 support::endian::SeekableWriter Writer(
819 static_cast<raw_pwrite_stream &>(*OutputStream),
821 for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
822 LayoutIdx++) {
823 assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
824 "Incorrect LayoutIdx in SecHdrTable");
825 auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
826 Writer.pwrite(static_cast<uint64_t>(Entry.Type),
827 SecHdrTableOffset + 4 * LayoutIdx * sizeof(uint64_t));
828 Writer.pwrite(static_cast<uint64_t>(Entry.Flags),
829 SecHdrTableOffset + (4 * LayoutIdx + 1) * sizeof(uint64_t));
830 Writer.pwrite(static_cast<uint64_t>(Entry.Offset),
831 SecHdrTableOffset + (4 * LayoutIdx + 2) * sizeof(uint64_t));
832 Writer.pwrite(static_cast<uint64_t>(Entry.Size),
833 SecHdrTableOffset + (4 * LayoutIdx + 3) * sizeof(uint64_t));
834 }
835
837}
838
839std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
840 const SampleProfileMap &ProfileMap) {
841 auto &OS = *OutputStream;
842 FileStart = OS.tell();
844
845 allocSecHdrTable();
847}
848
852 "writeCallsiteVTableProf should not be called if WriteVTableProf is "
853 "false");
854
855 encodeULEB128(CallsiteTypeMap.size(), OS);
856 for (const auto &[Loc, TypeMap] : CallsiteTypeMap) {
857 Loc.serialize(OS);
858 if (std::error_code EC = serializeTypeMap(TypeMap, getNameTable(), OS))
859 return EC;
860 }
861
863}
864
866 auto &OS = *OutputStream;
867 encodeULEB128(Summary->getTotalCount(), OS);
868 encodeULEB128(Summary->getMaxCount(), OS);
869 encodeULEB128(Summary->getMaxFunctionCount(), OS);
870 encodeULEB128(Summary->getNumCounts(), OS);
871 encodeULEB128(Summary->getNumFunctions(), OS);
872 ArrayRef<ProfileSummaryEntry> Entries = Summary->getDetailedSummary();
873 encodeULEB128(Entries.size(), OS);
874 for (auto Entry : Entries) {
875 encodeULEB128(Entry.Cutoff, OS);
876 encodeULEB128(Entry.MinCount, OS);
877 encodeULEB128(Entry.NumCounts, OS);
878 }
880}
882 auto &OS = *OutputStream;
883 if (std::error_code EC = writeContextIdx(S.getContext()))
884 return EC;
885
887
888 // Emit all the body samples.
889 encodeULEB128(S.getBodySamples().size(), OS);
890 for (const auto &I : S.getBodySamples()) {
891 LineLocation Loc = I.first;
892 const SampleRecord &Sample = I.second;
893 Loc.serialize(OS);
894 Sample.serialize(OS, getNameTable());
895 }
896
897 // Recursively emit all the callsite samples.
898 uint64_t NumCallsites = 0;
899 for (const auto &J : S.getCallsiteSamples())
900 NumCallsites += J.second.size();
901 encodeULEB128(NumCallsites, OS);
902 for (const auto &J : S.getCallsiteSamples())
903 for (const auto &FS : J.second) {
904 J.first.serialize(OS);
905 if (std::error_code EC = writeBody(FS.second))
906 return EC;
907 }
908
909 if (WriteVTableProf)
911
913}
914
915/// Write samples of a top-level function to a binary file.
916///
917/// \returns true if the samples were written successfully, false otherwise.
918std::error_code
923
924/// Create a sample profile file writer based on the specified format.
925///
926/// \param Filename The file to create.
927///
928/// \param Format Encoding format for the profile file.
929///
930/// \returns an error code indicating the status of the created writer.
933 std::error_code EC;
934 std::unique_ptr<raw_ostream> OS;
936 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
937 else
939 if (EC)
940 return EC;
941
942 return create(OS, Format);
943}
944
945/// Create a sample profile stream writer based on the specified format.
946///
947/// \param OS The output stream to store the profile data to.
948///
949/// \param Format Encoding format for the profile file.
950///
951/// \returns an error code indicating the status of the created writer.
953SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
955 std::error_code EC;
956 std::unique_ptr<SampleProfileWriter> Writer;
957
958 // Currently only Text and Extended Binary format are supported for CSSPGO.
962
963 if (Format == SPF_Binary)
964 Writer.reset(new SampleProfileWriterRawBinary(OS));
965 else if (Format == SPF_Ext_Binary)
966 Writer.reset(new SampleProfileWriterExtBinary(OS));
967 else if (Format == SPF_Text)
968 Writer.reset(new SampleProfileWriterText(OS));
969 else if (Format == SPF_GCC)
971 else
973
974 if (EC)
975 return EC;
976
977 Writer->Format = Format;
978 if (Format != SPF_Ext_Binary)
979 Writer->setFormatVersion(DefaultVersion);
981 Writer->setFormatVersion(RequestedVersion);
982 else
984 return std::move(Writer);
985}
986
989 Summary = Builder.computeSummaryForProfiles(ProfileMap);
990}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Provides ErrorOr<T> smart pointer.
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition KCFIHash.cpp:29
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
static cl::opt< uint64_t > RequestedVersion("sample-profile-format-version", cl::init(DefaultVersion), cl::Hidden, cl::desc("Format version to write for extensible binary profiles"))
static SmallVector< std::pair< KeyT, ValT > *, 0 > stabilizeTable(MapVector< KeyT, ValT > &Table)
static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap, SampleProfileMap &ContextProfileMap, SampleProfileMap &NoContextProfileMap)
static cl::opt< bool > ExtBinaryWriteVTableTypeProf("extbinary-write-vtable-type-prof", cl::init(false), cl::Hidden, cl::desc("Write vtable type profile in ext-binary sample profile writer"))
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
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:38
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
A raw_ostream that writes to an SmallVector or SmallString.
DefaultFunctionPruningStrategy(SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
void Erase(size_t CurrentOutputSize) override
In this default implementation, functions with fewest samples are dropped first.
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
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...
FunctionPruningStrategy(SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
ProfileMap A reference to the original profile map.
Representation of the samples collected for a function.
Definition SampleProf.h:802
static LLVM_ABI bool ProfileIsPreInlined
static constexpr const char * UniqSuffix
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
static LLVM_ABI bool ProfileIsCS
FunctionId getFunction() const
Return the function name.
const CallsiteTypeMap & getCallsiteTypeCounts() const
Returns vtable access samples for the C++ types collected in this function.
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const
Returns the TypeCountMap for inlined callsites at the given Loc.
Definition SampleProf.h:985
static LLVM_ABI bool ProfileIsProbeBased
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
SampleContext & getContext() const
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
std::string toString() const
Definition SampleProf.h:690
This class provides operator overloads to the map container using MD5 as the key type,...
virtual void addContext(const SampleContext &Context)
virtual std::error_code writeMagicIdent(SampleProfileFormat Format)
MapVector< FunctionId, uint32_t > NameTable
std::error_code writeCallsiteVTableProf(const CallsiteTypeMap &CallsiteTypeMap, raw_ostream &OS)
Write CallsiteTypeMap to the output stream OS.
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< FunctionId, uint32_t > & getNameTable()
std::error_code writeBody(const FunctionSamples &S)
std::error_code writeNameIdx(FunctionId FName)
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.
SampleProfileWriterExtBinary(std::unique_ptr< raw_ostream > &OS)
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.
uint64_t FormatVersion
Format version to write.
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:376
LLVM_ABI std::error_code serialize(raw_ostream &OS, const MapVector< FunctionId, uint32_t > &NameTable) const
Serialize the sample record to the output stream using ULEB128 encoding.
const CallTargetMap & getCallTargets() const
Definition SampleProf.h:444
SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:445
Sort a LocationT->SampleT map by LocationT.
const SamplesWithLocList & get() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI bool isAvailable()
constexpr int BestSizeCompression
Definition Compression.h:40
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition SampleProf.h:111
static bool formatVersionIsSupported(uint64_t Version)
Definition SampleProf.h:129
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:273
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:289
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:225
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:228
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:222
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:219
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:792
static constexpr uint64_t DefaultVersion
Definition SampleProf.h:123
std::map< FunctionId, uint64_t > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:356
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:94
LLVM_ABI std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
Definition SampleProf.h:794
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:804
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:573
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1409
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
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:79
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
endianness
Definition bit.h:71
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Represents the relative location of an instruction.
Definition SampleProf.h:305
Adapter to write values to a stream in a particular byte order.
void write(ArrayRef< value_type > Val)