35#include <system_error>
39#define DEBUG_TYPE "llvm-profdata"
47 cl::desc(
"Write vtable type profile in ext-binary sample profile writer"));
55struct SeekableWriter {
59 : OS(OS), Endian(Endian) {}
61 template <
typename ValueType>
63 std::string StringBuf;
64 raw_string_ostream SStream(StringBuf);
65 Writer(SStream, Endian).write(Val);
66 OS.pwrite(StringBuf.data(), StringBuf.size(),
Offset);
84 size_t NumToRemove =
ProfileMap.size() - NewSize;
88 assert(NumToRemove <= SortedFunctions.size());
92 SortedFunctions.resize(SortedFunctions.size() - NumToRemove);
98 if (OutputSizeLimit == 0)
99 return write(ProfileMap);
101 size_t OriginalFunctionCount = ProfileMap.size();
103 std::unique_ptr<raw_ostream> OriginalOutputStream;
106 size_t IterationCount = 0;
111 StringBuffer.
clear();
113 if (std::error_code EC =
write(ProfileMap))
116 TotalSize = StringBuffer.
size();
124 if (TotalSize <= OutputSizeLimit)
127 Strategy->
Erase(TotalSize);
129 }
while (ProfileMap.size() != 0);
131 if (ProfileMap.size() == 0)
136 LLVM_DEBUG(
dbgs() <<
"Profile originally has " << OriginalFunctionCount
137 <<
" functions, reduced to " << ProfileMap.size() <<
" in "
138 << IterationCount <<
" iterations\n");
140 (void)OriginalFunctionCount;
141 (void)IterationCount;
147 std::vector<NameFunctionSamples> V;
149 for (
const auto &
I : V) {
175 assert(Entry.Type ==
Type &&
"Unexpected section type");
182std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
185 std::string &UncompressedStrings =
187 if (UncompressedStrings.size() == 0)
197 UncompressedStrings.clear();
208 assert(Entry.Type ==
Type &&
"Unexpected section type");
211 if (std::error_code EC = compressAndOutput())
214 SecHdrTable.push_back({
Type, Entry.Flags, SectionStart - FileStart,
227 if (std::error_code EC = writeHeader(ProfileMap))
230 std::string LocalBuf;
231 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
235 if (std::error_code EC = writeSecHdrTable())
243 if (Context.hasContext())
251 const auto &Ret = CSNameTable.find(Context);
252 if (Ret == CSNameTable.end())
285 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable(
286 FuncOffsetTable.begin(), FuncOffsetTable.end());
287 for (
const auto &Entry : OrderedFuncOffsetTable) {
288 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
293 for (
const auto &Entry : FuncOffsetTable) {
294 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
299 FuncOffsetTable.clear();
319 NumCallsites += J.second.size();
322 for (
const auto &FS : J.second) {
340 for (
const auto &Entry : Profiles) {
352 std::set<FunctionId> V;
361 Writer.
write(
N.getHashCode());
367 for (
const auto &
I : ProfileMap) {
392 std::set<SampleContext> OrderedContexts;
393 for (
const auto &
I : CSNameTable)
394 OrderedContexts.insert(
I.first);
395 assert(OrderedContexts.size() == CSNameTable.size() &&
396 "Unmatched ordered and unordered contexts");
398 for (
auto &Context : OrderedContexts)
399 CSNameTable[Context] =
I++;
404 for (
auto Context : OrderedContexts) {
405 auto Frames = Context.getContextFrames();
407 for (
auto &Callsite : Frames) {
420 if (ProfSymList && ProfSymList->size() > 0)
421 if (std::error_code EC = ProfSymList->write(*
OutputStream))
490 std::unique_ptr<raw_ostream> &OS)
495std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
521 for (
const auto &
I : ProfileMap) {
522 if (
I.second.getCallsiteSamples().size())
523 ContextProfileMap.insert({
I.first,
I.second});
525 NoContextProfileMap.insert({
I.first,
I.second});
529std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
531 SampleProfileMap ContextProfileMap, NoContextProfileMap;
560std::error_code SampleProfileWriterExtBinary::writeSections(
564 EC = writeDefaultLayout(ProfileMap);
566 EC = writeCtxSplitLayout(ProfileMap);
593 for (
const auto &
I : SortedSamples.
get()) {
596 OS.indent(Indent + 1);
601 OS <<
" " << J.first <<
":" << J.second;
606 Map && !Map->empty()) {
607 OS.indent(Indent + 1);
611 for (
const auto [TypeName,
Count] : *Map) {
612 OS << TypeName <<
":" <<
Count <<
" ";
622 for (
const auto *Element : SortedCallsiteSamples.
get()) {
630 if (std::error_code EC =
writeSample(CalleeSamples))
635 Map && !Map->empty()) {
640 for (
const auto [TypeId,
Count] : *Map) {
641 OS << TypeId <<
":" <<
Count <<
" ";
651 OS.indent(Indent + 1);
657 OS.indent(Indent + 1);
670 assert(!Context.hasContext() &&
"cs profile is not supported");
676 const auto &Ret = NTable.find(FName);
677 if (Ret == NTable.end())
685 NTable.insert(std::make_pair(FName, 0));
689 addName(Context.getFunction());
702 for (
const auto &FS : J.second) {
711 for (
const auto &VTableAccessCountMap :
722 if (Context.hasContext()) {
723 for (
auto &Callsite : Context.getContextFrames())
725 CSNameTable.insert(std::make_pair(Context, 0));
743 std::set<FunctionId> V;
777 for (
const auto &
I : ProfileMap) {
795void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
801 Writer.write(
static_cast<uint64_t>(-1));
802 Writer.write(
static_cast<uint64_t>(-1));
803 Writer.write(
static_cast<uint64_t>(-1));
804 Writer.write(
static_cast<uint64_t>(-1));
808std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
810 "SecHdrTable entries doesn't match SectionHdrLayout");
812 for (
uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
813 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
825 support::endian::SeekableWriter Writer(
830 assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
831 "Incorrect LayoutIdx in SecHdrTable");
832 auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
833 Writer.pwrite(
static_cast<uint64_t
>(
Entry.Type),
834 SecHdrTableOffset + 4 * LayoutIdx *
sizeof(uint64_t));
835 Writer.pwrite(
static_cast<uint64_t
>(
Entry.Flags),
836 SecHdrTableOffset + (4 * LayoutIdx + 1) *
sizeof(uint64_t));
837 Writer.pwrite(
static_cast<uint64_t
>(
Entry.Offset),
838 SecHdrTableOffset + (4 * LayoutIdx + 2) *
sizeof(uint64_t));
839 Writer.pwrite(
static_cast<uint64_t
>(
Entry.Size),
840 SecHdrTableOffset + (4 * LayoutIdx + 3) *
sizeof(uint64_t));
846std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
849 FileStart = OS.tell();
859 "writeCallsiteVTableProf should not be called if WriteVTableProf is "
881 for (
auto Entry : Entries) {
907 NumCallsites += J.second.size();
910 for (
const auto &FS : J.second) {
911 J.first.serialize(OS);
912 if (std::error_code EC =
writeBody(FS.second))
941 std::unique_ptr<raw_ostream> OS;
963 std::unique_ptr<SampleProfileWriter> Writer;
985 return std::move(Writer);
990 Summary = Builder.computeSummaryForProfiles(ProfileMap);
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 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"))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
Represents either an error or a value T.
This class implements a map that also provides access to all stored values in a deterministic order.
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.
StringRef - Represent a constant reference to a string, i.e.
The instances of the Type class are immutable: once they are created, they are never changed.
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.
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.
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.
SampleProfileMap & ProfileMap
Representation of the samples collected for a function.
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.
uint64_t getFunctionHash() const
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.
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.
uint32_t getAllAttributes()
std::string toString() const
This class provides operator overloads to the map container using MD5 as the key type,...
void stablizeNameTable(MapVector< FunctionId, uint32_t > &NameTable, std::set< FunctionId > &V)
virtual void addContext(const SampleContext &Context)
virtual std::error_code writeNameTable()
virtual std::error_code writeMagicIdent(SampleProfileFormat Format)
std::error_code writeSummary()
MapVector< FunctionId, uint32_t > NameTable
void addNames(const FunctionSamples &S)
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)
void addName(FunctionId FName)
std::error_code writeNameTableSection(const SampleProfileMap &ProfileMap)
SmallVector< SecHdrTableEntry, 8 > SectionHdrLayout
std::error_code writeFuncMetadata(const SampleProfileMap &Profiles)
void setToCompressSection(SecType Type)
virtual std::error_code writeCustomSection(SecType Type)=0
virtual std::error_code writeOneSection(SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap)
std::error_code writeFuncOffsetTable()
std::error_code writeCSNameTableSection()
std::error_code writeCSNameIdx(const SampleContext &Context)
virtual std::error_code writeSections(const SampleProfileMap &ProfileMap)=0
std::error_code writeNameTable() override
void addSectionFlag(SecType Type, SecFlagType Flag)
std::error_code writeProfileSymbolListSection()
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...
void setToCompressAllSections() override
uint64_t SecLBRProfileStart
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.
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.
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
uint64_t getSamples() const
const SortedCallTargetSet getSortedCallTargets() const
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.
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
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
std::map< FunctionId, uint64_t > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
constexpr char kVTableProfPrefix[]
std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
static uint64_t SPVersion()
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
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.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct a string ref from an array ref of unsigned chars.
@ unsupported_writing_format
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
FunctionAddr VTableAddr Count
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Represents the relative location of an instruction.
Adapter to write values to a stream in a particular byte order.
void write(ArrayRef< value_type > Val)
static uint64_t round(uint64_t Acc, uint64_t Input)