1*0b57cec5SDimitry Andric //=-- SampleProf.cpp - Sample profiling format support --------------------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This file contains common definitions used in the reading and writing of 10*0b57cec5SDimitry Andric // sample profile data. 11*0b57cec5SDimitry Andric // 12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 13*0b57cec5SDimitry Andric 14*0b57cec5SDimitry Andric #include "llvm/ProfileData/SampleProf.h" 15*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h" 16*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 17e8d8bef9SDimitry Andric #include "llvm/IR/PseudoProbe.h" 18e8d8bef9SDimitry Andric #include "llvm/ProfileData/SampleProfReader.h" 19fe6060f1SDimitry Andric #include "llvm/Support/CommandLine.h" 20*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 21*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 22*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 23*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h" 24*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 25*0b57cec5SDimitry Andric #include <string> 26*0b57cec5SDimitry Andric #include <system_error> 27*0b57cec5SDimitry Andric 28*0b57cec5SDimitry Andric using namespace llvm; 29*0b57cec5SDimitry Andric using namespace sampleprof; 30*0b57cec5SDimitry Andric 31fe6060f1SDimitry Andric static cl::opt<uint64_t> ProfileSymbolListCutOff( 3281ad6265SDimitry Andric "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), 33fe6060f1SDimitry Andric cl::desc("Cutoff value about how many symbols in profile symbol list " 34fe6060f1SDimitry Andric "will be used. This is very useful for performance debugging")); 35fe6060f1SDimitry Andric 360eae32dcSDimitry Andric cl::opt<bool> GenerateMergedBaseProfiles( 3781ad6265SDimitry Andric "generate-merged-base-profiles", 380eae32dcSDimitry Andric cl::desc("When generating nested context-sensitive profiles, always " 390eae32dcSDimitry Andric "generate extra base profile for function with all its context " 400eae32dcSDimitry Andric "profiles merged into it.")); 410eae32dcSDimitry Andric 42*0b57cec5SDimitry Andric namespace llvm { 43*0b57cec5SDimitry Andric namespace sampleprof { 44e8d8bef9SDimitry Andric bool FunctionSamples::ProfileIsProbeBased = false; 4581ad6265SDimitry Andric bool FunctionSamples::ProfileIsCS = false; 4681ad6265SDimitry Andric bool FunctionSamples::ProfileIsPreInlined = false; 47fe6060f1SDimitry Andric bool FunctionSamples::UseMD5 = false; 48fe6060f1SDimitry Andric bool FunctionSamples::HasUniqSuffix = true; 49fe6060f1SDimitry Andric bool FunctionSamples::ProfileIsFS = false; 50*0b57cec5SDimitry Andric } // namespace sampleprof 51*0b57cec5SDimitry Andric } // namespace llvm 52*0b57cec5SDimitry Andric 53*0b57cec5SDimitry Andric namespace { 54*0b57cec5SDimitry Andric 55*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It 56*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to 57*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code. 58*0b57cec5SDimitry Andric class SampleProfErrorCategoryType : public std::error_category { 59*0b57cec5SDimitry Andric const char *name() const noexcept override { return "llvm.sampleprof"; } 60*0b57cec5SDimitry Andric 61*0b57cec5SDimitry Andric std::string message(int IE) const override { 62*0b57cec5SDimitry Andric sampleprof_error E = static_cast<sampleprof_error>(IE); 63*0b57cec5SDimitry Andric switch (E) { 64*0b57cec5SDimitry Andric case sampleprof_error::success: 65*0b57cec5SDimitry Andric return "Success"; 66*0b57cec5SDimitry Andric case sampleprof_error::bad_magic: 67*0b57cec5SDimitry Andric return "Invalid sample profile data (bad magic)"; 68*0b57cec5SDimitry Andric case sampleprof_error::unsupported_version: 69*0b57cec5SDimitry Andric return "Unsupported sample profile format version"; 70*0b57cec5SDimitry Andric case sampleprof_error::too_large: 71*0b57cec5SDimitry Andric return "Too much profile data"; 72*0b57cec5SDimitry Andric case sampleprof_error::truncated: 73*0b57cec5SDimitry Andric return "Truncated profile data"; 74*0b57cec5SDimitry Andric case sampleprof_error::malformed: 75*0b57cec5SDimitry Andric return "Malformed sample profile data"; 76*0b57cec5SDimitry Andric case sampleprof_error::unrecognized_format: 77*0b57cec5SDimitry Andric return "Unrecognized sample profile encoding format"; 78*0b57cec5SDimitry Andric case sampleprof_error::unsupported_writing_format: 79*0b57cec5SDimitry Andric return "Profile encoding format unsupported for writing operations"; 80*0b57cec5SDimitry Andric case sampleprof_error::truncated_name_table: 81*0b57cec5SDimitry Andric return "Truncated function name table"; 82*0b57cec5SDimitry Andric case sampleprof_error::not_implemented: 83*0b57cec5SDimitry Andric return "Unimplemented feature"; 84*0b57cec5SDimitry Andric case sampleprof_error::counter_overflow: 85*0b57cec5SDimitry Andric return "Counter overflow"; 86*0b57cec5SDimitry Andric case sampleprof_error::ostream_seek_unsupported: 87*0b57cec5SDimitry Andric return "Ostream does not support seek"; 888bcb0991SDimitry Andric case sampleprof_error::uncompress_failed: 898bcb0991SDimitry Andric return "Uncompress failure"; 908bcb0991SDimitry Andric case sampleprof_error::zlib_unavailable: 918bcb0991SDimitry Andric return "Zlib is unavailable"; 92e8d8bef9SDimitry Andric case sampleprof_error::hash_mismatch: 93e8d8bef9SDimitry Andric return "Function hash mismatch"; 94*0b57cec5SDimitry Andric } 95*0b57cec5SDimitry Andric llvm_unreachable("A value of sampleprof_error has no message."); 96*0b57cec5SDimitry Andric } 97*0b57cec5SDimitry Andric }; 98*0b57cec5SDimitry Andric 99*0b57cec5SDimitry Andric } // end anonymous namespace 100*0b57cec5SDimitry Andric 101*0b57cec5SDimitry Andric static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory; 102*0b57cec5SDimitry Andric 103*0b57cec5SDimitry Andric const std::error_category &llvm::sampleprof_category() { 104*0b57cec5SDimitry Andric return *ErrorCategory; 105*0b57cec5SDimitry Andric } 106*0b57cec5SDimitry Andric 107*0b57cec5SDimitry Andric void LineLocation::print(raw_ostream &OS) const { 108*0b57cec5SDimitry Andric OS << LineOffset; 109*0b57cec5SDimitry Andric if (Discriminator > 0) 110*0b57cec5SDimitry Andric OS << "." << Discriminator; 111*0b57cec5SDimitry Andric } 112*0b57cec5SDimitry Andric 113*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 114*0b57cec5SDimitry Andric const LineLocation &Loc) { 115*0b57cec5SDimitry Andric Loc.print(OS); 116*0b57cec5SDimitry Andric return OS; 117*0b57cec5SDimitry Andric } 118*0b57cec5SDimitry Andric 119fe6060f1SDimitry Andric /// Merge the samples in \p Other into this record. 120fe6060f1SDimitry Andric /// Optionally scale sample counts by \p Weight. 121fe6060f1SDimitry Andric sampleprof_error SampleRecord::merge(const SampleRecord &Other, 122fe6060f1SDimitry Andric uint64_t Weight) { 123fe6060f1SDimitry Andric sampleprof_error Result; 124fe6060f1SDimitry Andric Result = addSamples(Other.getSamples(), Weight); 125fe6060f1SDimitry Andric for (const auto &I : Other.getCallTargets()) { 126fe6060f1SDimitry Andric MergeResult(Result, addCalledTarget(I.first(), I.second, Weight)); 127fe6060f1SDimitry Andric } 128fe6060f1SDimitry Andric return Result; 129fe6060f1SDimitry Andric } 130fe6060f1SDimitry Andric 131*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 132*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); } 133*0b57cec5SDimitry Andric #endif 134*0b57cec5SDimitry Andric 135*0b57cec5SDimitry Andric /// Print the sample record to the stream \p OS indented by \p Indent. 136*0b57cec5SDimitry Andric void SampleRecord::print(raw_ostream &OS, unsigned Indent) const { 137*0b57cec5SDimitry Andric OS << NumSamples; 138*0b57cec5SDimitry Andric if (hasCalls()) { 139*0b57cec5SDimitry Andric OS << ", calls:"; 1408bcb0991SDimitry Andric for (const auto &I : getSortedCallTargets()) 1418bcb0991SDimitry Andric OS << " " << I.first << ":" << I.second; 142*0b57cec5SDimitry Andric } 143*0b57cec5SDimitry Andric OS << "\n"; 144*0b57cec5SDimitry Andric } 145*0b57cec5SDimitry Andric 146*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 147*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); } 148*0b57cec5SDimitry Andric #endif 149*0b57cec5SDimitry Andric 150*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 151*0b57cec5SDimitry Andric const SampleRecord &Sample) { 152*0b57cec5SDimitry Andric Sample.print(OS, 0); 153*0b57cec5SDimitry Andric return OS; 154*0b57cec5SDimitry Andric } 155*0b57cec5SDimitry Andric 156*0b57cec5SDimitry Andric /// Print the samples collected for a function on stream \p OS. 157*0b57cec5SDimitry Andric void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const { 158e8d8bef9SDimitry Andric if (getFunctionHash()) 159e8d8bef9SDimitry Andric OS << "CFG checksum " << getFunctionHash() << "\n"; 160e8d8bef9SDimitry Andric 161*0b57cec5SDimitry Andric OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size() 162*0b57cec5SDimitry Andric << " sampled lines\n"; 163*0b57cec5SDimitry Andric 164*0b57cec5SDimitry Andric OS.indent(Indent); 165*0b57cec5SDimitry Andric if (!BodySamples.empty()) { 166*0b57cec5SDimitry Andric OS << "Samples collected in the function's body {\n"; 167*0b57cec5SDimitry Andric SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples); 168*0b57cec5SDimitry Andric for (const auto &SI : SortedBodySamples.get()) { 169*0b57cec5SDimitry Andric OS.indent(Indent + 2); 170*0b57cec5SDimitry Andric OS << SI->first << ": " << SI->second; 171*0b57cec5SDimitry Andric } 172*0b57cec5SDimitry Andric OS.indent(Indent); 173*0b57cec5SDimitry Andric OS << "}\n"; 174*0b57cec5SDimitry Andric } else { 175*0b57cec5SDimitry Andric OS << "No samples collected in the function's body\n"; 176*0b57cec5SDimitry Andric } 177*0b57cec5SDimitry Andric 178*0b57cec5SDimitry Andric OS.indent(Indent); 179*0b57cec5SDimitry Andric if (!CallsiteSamples.empty()) { 180*0b57cec5SDimitry Andric OS << "Samples collected in inlined callsites {\n"; 181*0b57cec5SDimitry Andric SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples( 182*0b57cec5SDimitry Andric CallsiteSamples); 183*0b57cec5SDimitry Andric for (const auto &CS : SortedCallsiteSamples.get()) { 184*0b57cec5SDimitry Andric for (const auto &FS : CS->second) { 185*0b57cec5SDimitry Andric OS.indent(Indent + 2); 186*0b57cec5SDimitry Andric OS << CS->first << ": inlined callee: " << FS.second.getName() << ": "; 187*0b57cec5SDimitry Andric FS.second.print(OS, Indent + 4); 188*0b57cec5SDimitry Andric } 189*0b57cec5SDimitry Andric } 1908bcb0991SDimitry Andric OS.indent(Indent); 191*0b57cec5SDimitry Andric OS << "}\n"; 192*0b57cec5SDimitry Andric } else { 193*0b57cec5SDimitry Andric OS << "No inlined callsites in this function\n"; 194*0b57cec5SDimitry Andric } 195*0b57cec5SDimitry Andric } 196*0b57cec5SDimitry Andric 197*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 198*0b57cec5SDimitry Andric const FunctionSamples &FS) { 199*0b57cec5SDimitry Andric FS.print(OS); 200*0b57cec5SDimitry Andric return OS; 201*0b57cec5SDimitry Andric } 202*0b57cec5SDimitry Andric 203349cc55cSDimitry Andric void sampleprof::sortFuncProfiles( 204349cc55cSDimitry Andric const SampleProfileMap &ProfileMap, 205349cc55cSDimitry Andric std::vector<NameFunctionSamples> &SortedProfiles) { 206349cc55cSDimitry Andric for (const auto &I : ProfileMap) { 207349cc55cSDimitry Andric assert(I.first == I.second.getContext() && "Inconsistent profile map"); 208349cc55cSDimitry Andric SortedProfiles.push_back(std::make_pair(I.second.getContext(), &I.second)); 209349cc55cSDimitry Andric } 210349cc55cSDimitry Andric llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A, 211349cc55cSDimitry Andric const NameFunctionSamples &B) { 212349cc55cSDimitry Andric if (A.second->getTotalSamples() == B.second->getTotalSamples()) 213349cc55cSDimitry Andric return A.first < B.first; 214349cc55cSDimitry Andric return A.second->getTotalSamples() > B.second->getTotalSamples(); 215349cc55cSDimitry Andric }); 216349cc55cSDimitry Andric } 217349cc55cSDimitry Andric 218*0b57cec5SDimitry Andric unsigned FunctionSamples::getOffset(const DILocation *DIL) { 219*0b57cec5SDimitry Andric return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) & 220*0b57cec5SDimitry Andric 0xffff; 221*0b57cec5SDimitry Andric } 222*0b57cec5SDimitry Andric 2230eae32dcSDimitry Andric LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL, 2240eae32dcSDimitry Andric bool ProfileIsFS) { 2250eae32dcSDimitry Andric if (FunctionSamples::ProfileIsProbeBased) { 226e8d8bef9SDimitry Andric // In a pseudo-probe based profile, a callsite is simply represented by the 227e8d8bef9SDimitry Andric // ID of the probe associated with the call instruction. The probe ID is 228e8d8bef9SDimitry Andric // encoded in the Discriminator field of the call instruction's debug 229e8d8bef9SDimitry Andric // metadata. 230e8d8bef9SDimitry Andric return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex( 231e8d8bef9SDimitry Andric DIL->getDiscriminator()), 232e8d8bef9SDimitry Andric 0); 2330eae32dcSDimitry Andric } else { 2340eae32dcSDimitry Andric unsigned Discriminator = 2350eae32dcSDimitry Andric ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator(); 2360eae32dcSDimitry Andric return LineLocation(FunctionSamples::getOffset(DIL), Discriminator); 2370eae32dcSDimitry Andric } 2380eae32dcSDimitry Andric } 2390eae32dcSDimitry Andric 2400eae32dcSDimitry Andric uint64_t FunctionSamples::getCallSiteHash(StringRef CalleeName, 2410eae32dcSDimitry Andric const LineLocation &Callsite) { 2420eae32dcSDimitry Andric uint64_t NameHash = std::hash<std::string>{}(CalleeName.str()); 2430eae32dcSDimitry Andric uint64_t LocId = 2440eae32dcSDimitry Andric (((uint64_t)Callsite.LineOffset) << 32) | Callsite.Discriminator; 2450eae32dcSDimitry Andric return NameHash + (LocId << 5) + LocId; 246e8d8bef9SDimitry Andric } 247e8d8bef9SDimitry Andric 248e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamples( 249e8d8bef9SDimitry Andric const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const { 250*0b57cec5SDimitry Andric assert(DIL); 251*0b57cec5SDimitry Andric SmallVector<std::pair<LineLocation, StringRef>, 10> S; 252*0b57cec5SDimitry Andric 253*0b57cec5SDimitry Andric const DILocation *PrevDIL = DIL; 254*0b57cec5SDimitry Andric for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) { 255349cc55cSDimitry Andric // Use C++ linkage name if possible. 256349cc55cSDimitry Andric StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName(); 257349cc55cSDimitry Andric if (Name.empty()) 258349cc55cSDimitry Andric Name = PrevDIL->getScope()->getSubprogram()->getName(); 2590eae32dcSDimitry Andric S.emplace_back(FunctionSamples::getCallSiteIdentifier( 2600eae32dcSDimitry Andric DIL, FunctionSamples::ProfileIsFS), 2610eae32dcSDimitry Andric Name); 262*0b57cec5SDimitry Andric PrevDIL = DIL; 263*0b57cec5SDimitry Andric } 2640eae32dcSDimitry Andric 265*0b57cec5SDimitry Andric if (S.size() == 0) 266*0b57cec5SDimitry Andric return this; 267*0b57cec5SDimitry Andric const FunctionSamples *FS = this; 268*0b57cec5SDimitry Andric for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) { 269e8d8bef9SDimitry Andric FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper); 270*0b57cec5SDimitry Andric } 271*0b57cec5SDimitry Andric return FS; 272*0b57cec5SDimitry Andric } 273*0b57cec5SDimitry Andric 274e8d8bef9SDimitry Andric void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const { 275349cc55cSDimitry Andric NameSet.insert(getName()); 276e8d8bef9SDimitry Andric for (const auto &BS : BodySamples) 277e8d8bef9SDimitry Andric for (const auto &TS : BS.second.getCallTargets()) 278e8d8bef9SDimitry Andric NameSet.insert(TS.getKey()); 279e8d8bef9SDimitry Andric 280e8d8bef9SDimitry Andric for (const auto &CS : CallsiteSamples) { 281e8d8bef9SDimitry Andric for (const auto &NameFS : CS.second) { 282e8d8bef9SDimitry Andric NameSet.insert(NameFS.first); 283e8d8bef9SDimitry Andric NameFS.second.findAllNames(NameSet); 284e8d8bef9SDimitry Andric } 285e8d8bef9SDimitry Andric } 286e8d8bef9SDimitry Andric } 287e8d8bef9SDimitry Andric 288e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamplesAt( 289e8d8bef9SDimitry Andric const LineLocation &Loc, StringRef CalleeName, 290e8d8bef9SDimitry Andric SampleProfileReaderItaniumRemapper *Remapper) const { 291fe6060f1SDimitry Andric CalleeName = getCanonicalFnName(CalleeName); 292fe6060f1SDimitry Andric 293e8d8bef9SDimitry Andric std::string CalleeGUID; 294e8d8bef9SDimitry Andric CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID); 295e8d8bef9SDimitry Andric 296e8d8bef9SDimitry Andric auto iter = CallsiteSamples.find(Loc); 297e8d8bef9SDimitry Andric if (iter == CallsiteSamples.end()) 298e8d8bef9SDimitry Andric return nullptr; 299e8d8bef9SDimitry Andric auto FS = iter->second.find(CalleeName); 300e8d8bef9SDimitry Andric if (FS != iter->second.end()) 301e8d8bef9SDimitry Andric return &FS->second; 302e8d8bef9SDimitry Andric if (Remapper) { 303e8d8bef9SDimitry Andric if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) { 304e8d8bef9SDimitry Andric auto FS = iter->second.find(*NameInProfile); 305e8d8bef9SDimitry Andric if (FS != iter->second.end()) 306e8d8bef9SDimitry Andric return &FS->second; 307e8d8bef9SDimitry Andric } 308e8d8bef9SDimitry Andric } 309e8d8bef9SDimitry Andric // If we cannot find exact match of the callee name, return the FS with 310e8d8bef9SDimitry Andric // the max total count. Only do this when CalleeName is not provided, 311e8d8bef9SDimitry Andric // i.e., only for indirect calls. 312e8d8bef9SDimitry Andric if (!CalleeName.empty()) 313e8d8bef9SDimitry Andric return nullptr; 314e8d8bef9SDimitry Andric uint64_t MaxTotalSamples = 0; 315e8d8bef9SDimitry Andric const FunctionSamples *R = nullptr; 316e8d8bef9SDimitry Andric for (const auto &NameFS : iter->second) 317e8d8bef9SDimitry Andric if (NameFS.second.getTotalSamples() >= MaxTotalSamples) { 318e8d8bef9SDimitry Andric MaxTotalSamples = NameFS.second.getTotalSamples(); 319e8d8bef9SDimitry Andric R = &NameFS.second; 320e8d8bef9SDimitry Andric } 321e8d8bef9SDimitry Andric return R; 322e8d8bef9SDimitry Andric } 323e8d8bef9SDimitry Andric 324*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 325*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); } 326*0b57cec5SDimitry Andric #endif 3278bcb0991SDimitry Andric 3288bcb0991SDimitry Andric std::error_code ProfileSymbolList::read(const uint8_t *Data, 3298bcb0991SDimitry Andric uint64_t ListSize) { 3308bcb0991SDimitry Andric const char *ListStart = reinterpret_cast<const char *>(Data); 3318bcb0991SDimitry Andric uint64_t Size = 0; 332fe6060f1SDimitry Andric uint64_t StrNum = 0; 333fe6060f1SDimitry Andric while (Size < ListSize && StrNum < ProfileSymbolListCutOff) { 3348bcb0991SDimitry Andric StringRef Str(ListStart + Size); 3358bcb0991SDimitry Andric add(Str); 3368bcb0991SDimitry Andric Size += Str.size() + 1; 337fe6060f1SDimitry Andric StrNum++; 3388bcb0991SDimitry Andric } 339fe6060f1SDimitry Andric if (Size != ListSize && StrNum != ProfileSymbolListCutOff) 3408bcb0991SDimitry Andric return sampleprof_error::malformed; 3418bcb0991SDimitry Andric return sampleprof_error::success; 3428bcb0991SDimitry Andric } 3438bcb0991SDimitry Andric 344fe6060f1SDimitry Andric void SampleContextTrimmer::trimAndMergeColdContextProfiles( 345fe6060f1SDimitry Andric uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, 346349cc55cSDimitry Andric uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) { 347fe6060f1SDimitry Andric if (!TrimColdContext && !MergeColdContext) 348fe6060f1SDimitry Andric return; 349fe6060f1SDimitry Andric 350fe6060f1SDimitry Andric // Nothing to merge if sample threshold is zero 351fe6060f1SDimitry Andric if (ColdCountThreshold == 0) 352fe6060f1SDimitry Andric return; 353fe6060f1SDimitry Andric 354349cc55cSDimitry Andric // Trimming base profiles only is mainly to honor the preinliner decsion. When 355349cc55cSDimitry Andric // MergeColdContext is true preinliner decsion is not honored anyway so turn 356349cc55cSDimitry Andric // off TrimBaseProfileOnly. 357349cc55cSDimitry Andric if (MergeColdContext) 358349cc55cSDimitry Andric TrimBaseProfileOnly = false; 359349cc55cSDimitry Andric 360fe6060f1SDimitry Andric // Filter the cold profiles from ProfileMap and move them into a tmp 361fe6060f1SDimitry Andric // container 362349cc55cSDimitry Andric std::vector<std::pair<SampleContext, const FunctionSamples *>> ColdProfiles; 363fe6060f1SDimitry Andric for (const auto &I : ProfileMap) { 364349cc55cSDimitry Andric const SampleContext &Context = I.first; 365fe6060f1SDimitry Andric const FunctionSamples &FunctionProfile = I.second; 366349cc55cSDimitry Andric if (FunctionProfile.getTotalSamples() < ColdCountThreshold && 367349cc55cSDimitry Andric (!TrimBaseProfileOnly || Context.isBaseContext())) 368349cc55cSDimitry Andric ColdProfiles.emplace_back(Context, &I.second); 369fe6060f1SDimitry Andric } 370fe6060f1SDimitry Andric 371fe6060f1SDimitry Andric // Remove the cold profile from ProfileMap and merge them into 372fe6060f1SDimitry Andric // MergedProfileMap by the last K frames of context 373349cc55cSDimitry Andric SampleProfileMap MergedProfileMap; 374fe6060f1SDimitry Andric for (const auto &I : ColdProfiles) { 375fe6060f1SDimitry Andric if (MergeColdContext) { 376349cc55cSDimitry Andric auto MergedContext = I.second->getContext().getContextFrames(); 377349cc55cSDimitry Andric if (ColdContextFrameLength < MergedContext.size()) 378349cc55cSDimitry Andric MergedContext = MergedContext.take_back(ColdContextFrameLength); 379349cc55cSDimitry Andric auto Ret = MergedProfileMap.emplace(MergedContext, FunctionSamples()); 380fe6060f1SDimitry Andric FunctionSamples &MergedProfile = Ret.first->second; 381fe6060f1SDimitry Andric MergedProfile.merge(*I.second); 382fe6060f1SDimitry Andric } 383fe6060f1SDimitry Andric ProfileMap.erase(I.first); 384fe6060f1SDimitry Andric } 385fe6060f1SDimitry Andric 386fe6060f1SDimitry Andric // Move the merged profiles into ProfileMap; 387fe6060f1SDimitry Andric for (const auto &I : MergedProfileMap) { 388fe6060f1SDimitry Andric // Filter the cold merged profile 389fe6060f1SDimitry Andric if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold && 390349cc55cSDimitry Andric ProfileMap.find(I.first) == ProfileMap.end()) 391fe6060f1SDimitry Andric continue; 392fe6060f1SDimitry Andric // Merge the profile if the original profile exists, otherwise just insert 393fe6060f1SDimitry Andric // as a new profile 394349cc55cSDimitry Andric auto Ret = ProfileMap.emplace(I.first, FunctionSamples()); 395fe6060f1SDimitry Andric if (Ret.second) { 396349cc55cSDimitry Andric SampleContext FContext(Ret.first->first, RawContext); 397fe6060f1SDimitry Andric FunctionSamples &FProfile = Ret.first->second; 398fe6060f1SDimitry Andric FProfile.setContext(FContext); 399fe6060f1SDimitry Andric } 400fe6060f1SDimitry Andric FunctionSamples &OrigProfile = Ret.first->second; 401fe6060f1SDimitry Andric OrigProfile.merge(I.second); 402fe6060f1SDimitry Andric } 403fe6060f1SDimitry Andric } 404fe6060f1SDimitry Andric 405fe6060f1SDimitry Andric void SampleContextTrimmer::canonicalizeContextProfiles() { 406349cc55cSDimitry Andric std::vector<SampleContext> ProfilesToBeRemoved; 407349cc55cSDimitry Andric SampleProfileMap ProfilesToBeAdded; 408fe6060f1SDimitry Andric for (auto &I : ProfileMap) { 409fe6060f1SDimitry Andric FunctionSamples &FProfile = I.second; 410349cc55cSDimitry Andric SampleContext &Context = FProfile.getContext(); 411349cc55cSDimitry Andric if (I.first == Context) 412fe6060f1SDimitry Andric continue; 413fe6060f1SDimitry Andric 414fe6060f1SDimitry Andric // Use the context string from FunctionSamples to update the keys of 415fe6060f1SDimitry Andric // ProfileMap. They can get out of sync after context profile promotion 416fe6060f1SDimitry Andric // through pre-inliner. 417fe6060f1SDimitry Andric // Duplicate the function profile for later insertion to avoid a conflict 418fe6060f1SDimitry Andric // caused by a context both to be add and to be removed. This could happen 419fe6060f1SDimitry Andric // when a context is promoted to another context which is also promoted to 420fe6060f1SDimitry Andric // the third context. For example, given an original context A @ B @ C that 421fe6060f1SDimitry Andric // is promoted to B @ C and the original context B @ C which is promoted to 422fe6060f1SDimitry Andric // just C, adding B @ C to the profile map while removing same context (but 423fe6060f1SDimitry Andric // with different profiles) from the map can cause a conflict if they are 424fe6060f1SDimitry Andric // not handled in a right order. This can be solved by just caching the 425fe6060f1SDimitry Andric // profiles to be added. 426349cc55cSDimitry Andric auto Ret = ProfilesToBeAdded.emplace(Context, FProfile); 427fe6060f1SDimitry Andric (void)Ret; 428fe6060f1SDimitry Andric assert(Ret.second && "Context conflict during canonicalization"); 429349cc55cSDimitry Andric ProfilesToBeRemoved.push_back(I.first); 430fe6060f1SDimitry Andric } 431fe6060f1SDimitry Andric 432fe6060f1SDimitry Andric for (auto &I : ProfilesToBeRemoved) { 433fe6060f1SDimitry Andric ProfileMap.erase(I); 434fe6060f1SDimitry Andric } 435fe6060f1SDimitry Andric 436fe6060f1SDimitry Andric for (auto &I : ProfilesToBeAdded) { 437349cc55cSDimitry Andric ProfileMap.emplace(I.first, I.second); 438fe6060f1SDimitry Andric } 439fe6060f1SDimitry Andric } 440fe6060f1SDimitry Andric 4418bcb0991SDimitry Andric std::error_code ProfileSymbolList::write(raw_ostream &OS) { 4428bcb0991SDimitry Andric // Sort the symbols before output. If doing compression. 4438bcb0991SDimitry Andric // It will make the compression much more effective. 444e8d8bef9SDimitry Andric std::vector<StringRef> SortedList(Syms.begin(), Syms.end()); 4458bcb0991SDimitry Andric llvm::sort(SortedList); 4468bcb0991SDimitry Andric 4478bcb0991SDimitry Andric std::string OutputString; 4488bcb0991SDimitry Andric for (auto &Sym : SortedList) { 4498bcb0991SDimitry Andric OutputString.append(Sym.str()); 4508bcb0991SDimitry Andric OutputString.append(1, '\0'); 4518bcb0991SDimitry Andric } 4528bcb0991SDimitry Andric 4538bcb0991SDimitry Andric OS << OutputString; 4548bcb0991SDimitry Andric return sampleprof_error::success; 4558bcb0991SDimitry Andric } 4568bcb0991SDimitry Andric 4578bcb0991SDimitry Andric void ProfileSymbolList::dump(raw_ostream &OS) const { 4588bcb0991SDimitry Andric OS << "======== Dump profile symbol list ========\n"; 459e8d8bef9SDimitry Andric std::vector<StringRef> SortedList(Syms.begin(), Syms.end()); 4608bcb0991SDimitry Andric llvm::sort(SortedList); 4618bcb0991SDimitry Andric 4628bcb0991SDimitry Andric for (auto &Sym : SortedList) 4638bcb0991SDimitry Andric OS << Sym << "\n"; 4648bcb0991SDimitry Andric } 4650eae32dcSDimitry Andric 4660eae32dcSDimitry Andric CSProfileConverter::FrameNode * 4670eae32dcSDimitry Andric CSProfileConverter::FrameNode::getOrCreateChildFrame( 4680eae32dcSDimitry Andric const LineLocation &CallSite, StringRef CalleeName) { 4690eae32dcSDimitry Andric uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite); 4700eae32dcSDimitry Andric auto It = AllChildFrames.find(Hash); 4710eae32dcSDimitry Andric if (It != AllChildFrames.end()) { 4720eae32dcSDimitry Andric assert(It->second.FuncName == CalleeName && 4730eae32dcSDimitry Andric "Hash collision for child context node"); 4740eae32dcSDimitry Andric return &It->second; 4750eae32dcSDimitry Andric } 4760eae32dcSDimitry Andric 4770eae32dcSDimitry Andric AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite); 4780eae32dcSDimitry Andric return &AllChildFrames[Hash]; 4790eae32dcSDimitry Andric } 4800eae32dcSDimitry Andric 4810eae32dcSDimitry Andric CSProfileConverter::CSProfileConverter(SampleProfileMap &Profiles) 4820eae32dcSDimitry Andric : ProfileMap(Profiles) { 4830eae32dcSDimitry Andric for (auto &FuncSample : Profiles) { 4840eae32dcSDimitry Andric FunctionSamples *FSamples = &FuncSample.second; 4850eae32dcSDimitry Andric auto *NewNode = getOrCreateContextPath(FSamples->getContext()); 4860eae32dcSDimitry Andric assert(!NewNode->FuncSamples && "New node cannot have sample profile"); 4870eae32dcSDimitry Andric NewNode->FuncSamples = FSamples; 4880eae32dcSDimitry Andric } 4890eae32dcSDimitry Andric } 4900eae32dcSDimitry Andric 4910eae32dcSDimitry Andric CSProfileConverter::FrameNode * 4920eae32dcSDimitry Andric CSProfileConverter::getOrCreateContextPath(const SampleContext &Context) { 4930eae32dcSDimitry Andric auto Node = &RootFrame; 4940eae32dcSDimitry Andric LineLocation CallSiteLoc(0, 0); 4950eae32dcSDimitry Andric for (auto &Callsite : Context.getContextFrames()) { 4960eae32dcSDimitry Andric Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.FuncName); 4970eae32dcSDimitry Andric CallSiteLoc = Callsite.Location; 4980eae32dcSDimitry Andric } 4990eae32dcSDimitry Andric return Node; 5000eae32dcSDimitry Andric } 5010eae32dcSDimitry Andric 5020eae32dcSDimitry Andric void CSProfileConverter::convertProfiles(CSProfileConverter::FrameNode &Node) { 5030eae32dcSDimitry Andric // Process each child profile. Add each child profile to callsite profile map 5040eae32dcSDimitry Andric // of the current node `Node` if `Node` comes with a profile. Otherwise 5050eae32dcSDimitry Andric // promote the child profile to a standalone profile. 5060eae32dcSDimitry Andric auto *NodeProfile = Node.FuncSamples; 5070eae32dcSDimitry Andric for (auto &It : Node.AllChildFrames) { 5080eae32dcSDimitry Andric auto &ChildNode = It.second; 5090eae32dcSDimitry Andric convertProfiles(ChildNode); 5100eae32dcSDimitry Andric auto *ChildProfile = ChildNode.FuncSamples; 5110eae32dcSDimitry Andric if (!ChildProfile) 5120eae32dcSDimitry Andric continue; 5130eae32dcSDimitry Andric SampleContext OrigChildContext = ChildProfile->getContext(); 5140eae32dcSDimitry Andric // Reset the child context to be contextless. 5150eae32dcSDimitry Andric ChildProfile->getContext().setName(OrigChildContext.getName()); 5160eae32dcSDimitry Andric if (NodeProfile) { 5170eae32dcSDimitry Andric // Add child profile to the callsite profile map. 5180eae32dcSDimitry Andric auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc); 5190eae32dcSDimitry Andric SamplesMap.emplace(OrigChildContext.getName().str(), *ChildProfile); 5200eae32dcSDimitry Andric NodeProfile->addTotalSamples(ChildProfile->getTotalSamples()); 52181ad6265SDimitry Andric // Remove the corresponding body sample for the callsite and update the 52281ad6265SDimitry Andric // total weight. 52381ad6265SDimitry Andric auto Count = NodeProfile->removeCalledTargetAndBodySample( 52481ad6265SDimitry Andric ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator, 52581ad6265SDimitry Andric OrigChildContext.getName()); 52681ad6265SDimitry Andric NodeProfile->removeTotalSamples(Count); 5270eae32dcSDimitry Andric } 5280eae32dcSDimitry Andric 5290eae32dcSDimitry Andric // Separate child profile to be a standalone profile, if the current parent 5300eae32dcSDimitry Andric // profile doesn't exist. This is a duplicating operation when the child 5310eae32dcSDimitry Andric // profile is already incorporated into the parent which is still useful and 5320eae32dcSDimitry Andric // thus done optionally. It is seen that duplicating context profiles into 5330eae32dcSDimitry Andric // base profiles improves the code quality for thinlto build by allowing a 5340eae32dcSDimitry Andric // profile in the prelink phase for to-be-fully-inlined functions. 53581ad6265SDimitry Andric if (!NodeProfile) { 5360eae32dcSDimitry Andric ProfileMap[ChildProfile->getContext()].merge(*ChildProfile); 53781ad6265SDimitry Andric } else if (GenerateMergedBaseProfiles) { 53881ad6265SDimitry Andric ProfileMap[ChildProfile->getContext()].merge(*ChildProfile); 53981ad6265SDimitry Andric auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc); 54081ad6265SDimitry Andric SamplesMap[ChildProfile->getName().str()].getContext().setAttribute( 54181ad6265SDimitry Andric ContextDuplicatedIntoBase); 54281ad6265SDimitry Andric } 5430eae32dcSDimitry Andric 5440eae32dcSDimitry Andric // Remove the original child profile. 5450eae32dcSDimitry Andric ProfileMap.erase(OrigChildContext); 5460eae32dcSDimitry Andric } 5470eae32dcSDimitry Andric } 5480eae32dcSDimitry Andric 5490eae32dcSDimitry Andric void CSProfileConverter::convertProfiles() { convertProfiles(RootFrame); } 550