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"
228bcb0991SDimitry Andric #include "llvm/Support/Error.h"
23*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
248bcb0991SDimitry Andric #include "llvm/Support/LEB128.h"
25*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
26*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
27*0b57cec5SDimitry Andric #include <string>
28*0b57cec5SDimitry Andric #include <system_error>
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric using namespace llvm;
31*0b57cec5SDimitry Andric using namespace sampleprof;
32*0b57cec5SDimitry Andric 
33fe6060f1SDimitry Andric static cl::opt<uint64_t> ProfileSymbolListCutOff(
34fe6060f1SDimitry Andric     "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), cl::ZeroOrMore,
35fe6060f1SDimitry Andric     cl::desc("Cutoff value about how many symbols in profile symbol list "
36fe6060f1SDimitry Andric              "will be used. This is very useful for performance debugging"));
37fe6060f1SDimitry Andric 
38*0b57cec5SDimitry Andric namespace llvm {
39*0b57cec5SDimitry Andric namespace sampleprof {
40*0b57cec5SDimitry Andric SampleProfileFormat FunctionSamples::Format;
41e8d8bef9SDimitry Andric bool FunctionSamples::ProfileIsProbeBased = false;
42e8d8bef9SDimitry Andric bool FunctionSamples::ProfileIsCS = false;
43fe6060f1SDimitry Andric bool FunctionSamples::UseMD5 = false;
44fe6060f1SDimitry Andric bool FunctionSamples::HasUniqSuffix = true;
45fe6060f1SDimitry Andric bool FunctionSamples::ProfileIsFS = false;
46*0b57cec5SDimitry Andric } // namespace sampleprof
47*0b57cec5SDimitry Andric } // namespace llvm
48*0b57cec5SDimitry Andric 
49*0b57cec5SDimitry Andric namespace {
50*0b57cec5SDimitry Andric 
51*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
52*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
53*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
54*0b57cec5SDimitry Andric class SampleProfErrorCategoryType : public std::error_category {
55*0b57cec5SDimitry Andric   const char *name() const noexcept override { return "llvm.sampleprof"; }
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric   std::string message(int IE) const override {
58*0b57cec5SDimitry Andric     sampleprof_error E = static_cast<sampleprof_error>(IE);
59*0b57cec5SDimitry Andric     switch (E) {
60*0b57cec5SDimitry Andric     case sampleprof_error::success:
61*0b57cec5SDimitry Andric       return "Success";
62*0b57cec5SDimitry Andric     case sampleprof_error::bad_magic:
63*0b57cec5SDimitry Andric       return "Invalid sample profile data (bad magic)";
64*0b57cec5SDimitry Andric     case sampleprof_error::unsupported_version:
65*0b57cec5SDimitry Andric       return "Unsupported sample profile format version";
66*0b57cec5SDimitry Andric     case sampleprof_error::too_large:
67*0b57cec5SDimitry Andric       return "Too much profile data";
68*0b57cec5SDimitry Andric     case sampleprof_error::truncated:
69*0b57cec5SDimitry Andric       return "Truncated profile data";
70*0b57cec5SDimitry Andric     case sampleprof_error::malformed:
71*0b57cec5SDimitry Andric       return "Malformed sample profile data";
72*0b57cec5SDimitry Andric     case sampleprof_error::unrecognized_format:
73*0b57cec5SDimitry Andric       return "Unrecognized sample profile encoding format";
74*0b57cec5SDimitry Andric     case sampleprof_error::unsupported_writing_format:
75*0b57cec5SDimitry Andric       return "Profile encoding format unsupported for writing operations";
76*0b57cec5SDimitry Andric     case sampleprof_error::truncated_name_table:
77*0b57cec5SDimitry Andric       return "Truncated function name table";
78*0b57cec5SDimitry Andric     case sampleprof_error::not_implemented:
79*0b57cec5SDimitry Andric       return "Unimplemented feature";
80*0b57cec5SDimitry Andric     case sampleprof_error::counter_overflow:
81*0b57cec5SDimitry Andric       return "Counter overflow";
82*0b57cec5SDimitry Andric     case sampleprof_error::ostream_seek_unsupported:
83*0b57cec5SDimitry Andric       return "Ostream does not support seek";
848bcb0991SDimitry Andric     case sampleprof_error::compress_failed:
858bcb0991SDimitry Andric       return "Compress failure";
868bcb0991SDimitry Andric     case sampleprof_error::uncompress_failed:
878bcb0991SDimitry Andric       return "Uncompress failure";
888bcb0991SDimitry Andric     case sampleprof_error::zlib_unavailable:
898bcb0991SDimitry Andric       return "Zlib is unavailable";
90e8d8bef9SDimitry Andric     case sampleprof_error::hash_mismatch:
91e8d8bef9SDimitry Andric       return "Function hash mismatch";
92*0b57cec5SDimitry Andric     }
93*0b57cec5SDimitry Andric     llvm_unreachable("A value of sampleprof_error has no message.");
94*0b57cec5SDimitry Andric   }
95*0b57cec5SDimitry Andric };
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric } // end anonymous namespace
98*0b57cec5SDimitry Andric 
99*0b57cec5SDimitry Andric static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory;
100*0b57cec5SDimitry Andric 
101*0b57cec5SDimitry Andric const std::error_category &llvm::sampleprof_category() {
102*0b57cec5SDimitry Andric   return *ErrorCategory;
103*0b57cec5SDimitry Andric }
104*0b57cec5SDimitry Andric 
105*0b57cec5SDimitry Andric void LineLocation::print(raw_ostream &OS) const {
106*0b57cec5SDimitry Andric   OS << LineOffset;
107*0b57cec5SDimitry Andric   if (Discriminator > 0)
108*0b57cec5SDimitry Andric     OS << "." << Discriminator;
109*0b57cec5SDimitry Andric }
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
112*0b57cec5SDimitry Andric                                           const LineLocation &Loc) {
113*0b57cec5SDimitry Andric   Loc.print(OS);
114*0b57cec5SDimitry Andric   return OS;
115*0b57cec5SDimitry Andric }
116*0b57cec5SDimitry Andric 
117fe6060f1SDimitry Andric /// Merge the samples in \p Other into this record.
118fe6060f1SDimitry Andric /// Optionally scale sample counts by \p Weight.
119fe6060f1SDimitry Andric sampleprof_error SampleRecord::merge(const SampleRecord &Other,
120fe6060f1SDimitry Andric                                      uint64_t Weight) {
121fe6060f1SDimitry Andric   sampleprof_error Result;
122fe6060f1SDimitry Andric   Result = addSamples(Other.getSamples(), Weight);
123fe6060f1SDimitry Andric   for (const auto &I : Other.getCallTargets()) {
124fe6060f1SDimitry Andric     MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
125fe6060f1SDimitry Andric   }
126fe6060f1SDimitry Andric   return Result;
127fe6060f1SDimitry Andric }
128fe6060f1SDimitry Andric 
129*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
130*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
131*0b57cec5SDimitry Andric #endif
132*0b57cec5SDimitry Andric 
133*0b57cec5SDimitry Andric /// Print the sample record to the stream \p OS indented by \p Indent.
134*0b57cec5SDimitry Andric void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
135*0b57cec5SDimitry Andric   OS << NumSamples;
136*0b57cec5SDimitry Andric   if (hasCalls()) {
137*0b57cec5SDimitry Andric     OS << ", calls:";
1388bcb0991SDimitry Andric     for (const auto &I : getSortedCallTargets())
1398bcb0991SDimitry Andric       OS << " " << I.first << ":" << I.second;
140*0b57cec5SDimitry Andric   }
141*0b57cec5SDimitry Andric   OS << "\n";
142*0b57cec5SDimitry Andric }
143*0b57cec5SDimitry Andric 
144*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
145*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
146*0b57cec5SDimitry Andric #endif
147*0b57cec5SDimitry Andric 
148*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
149*0b57cec5SDimitry Andric                                           const SampleRecord &Sample) {
150*0b57cec5SDimitry Andric   Sample.print(OS, 0);
151*0b57cec5SDimitry Andric   return OS;
152*0b57cec5SDimitry Andric }
153*0b57cec5SDimitry Andric 
154*0b57cec5SDimitry Andric /// Print the samples collected for a function on stream \p OS.
155*0b57cec5SDimitry Andric void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
156e8d8bef9SDimitry Andric   if (getFunctionHash())
157e8d8bef9SDimitry Andric     OS << "CFG checksum " << getFunctionHash() << "\n";
158e8d8bef9SDimitry Andric 
159*0b57cec5SDimitry Andric   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
160*0b57cec5SDimitry Andric      << " sampled lines\n";
161*0b57cec5SDimitry Andric 
162*0b57cec5SDimitry Andric   OS.indent(Indent);
163*0b57cec5SDimitry Andric   if (!BodySamples.empty()) {
164*0b57cec5SDimitry Andric     OS << "Samples collected in the function's body {\n";
165*0b57cec5SDimitry Andric     SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
166*0b57cec5SDimitry Andric     for (const auto &SI : SortedBodySamples.get()) {
167*0b57cec5SDimitry Andric       OS.indent(Indent + 2);
168*0b57cec5SDimitry Andric       OS << SI->first << ": " << SI->second;
169*0b57cec5SDimitry Andric     }
170*0b57cec5SDimitry Andric     OS.indent(Indent);
171*0b57cec5SDimitry Andric     OS << "}\n";
172*0b57cec5SDimitry Andric   } else {
173*0b57cec5SDimitry Andric     OS << "No samples collected in the function's body\n";
174*0b57cec5SDimitry Andric   }
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric   OS.indent(Indent);
177*0b57cec5SDimitry Andric   if (!CallsiteSamples.empty()) {
178*0b57cec5SDimitry Andric     OS << "Samples collected in inlined callsites {\n";
179*0b57cec5SDimitry Andric     SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
180*0b57cec5SDimitry Andric         CallsiteSamples);
181*0b57cec5SDimitry Andric     for (const auto &CS : SortedCallsiteSamples.get()) {
182*0b57cec5SDimitry Andric       for (const auto &FS : CS->second) {
183*0b57cec5SDimitry Andric         OS.indent(Indent + 2);
184*0b57cec5SDimitry Andric         OS << CS->first << ": inlined callee: " << FS.second.getName() << ": ";
185*0b57cec5SDimitry Andric         FS.second.print(OS, Indent + 4);
186*0b57cec5SDimitry Andric       }
187*0b57cec5SDimitry Andric     }
1888bcb0991SDimitry Andric     OS.indent(Indent);
189*0b57cec5SDimitry Andric     OS << "}\n";
190*0b57cec5SDimitry Andric   } else {
191*0b57cec5SDimitry Andric     OS << "No inlined callsites in this function\n";
192*0b57cec5SDimitry Andric   }
193*0b57cec5SDimitry Andric }
194*0b57cec5SDimitry Andric 
195*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
196*0b57cec5SDimitry Andric                                           const FunctionSamples &FS) {
197*0b57cec5SDimitry Andric   FS.print(OS);
198*0b57cec5SDimitry Andric   return OS;
199*0b57cec5SDimitry Andric }
200*0b57cec5SDimitry Andric 
201*0b57cec5SDimitry Andric unsigned FunctionSamples::getOffset(const DILocation *DIL) {
202*0b57cec5SDimitry Andric   return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
203*0b57cec5SDimitry Andric       0xffff;
204*0b57cec5SDimitry Andric }
205*0b57cec5SDimitry Andric 
206e8d8bef9SDimitry Andric LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL) {
207e8d8bef9SDimitry Andric   if (FunctionSamples::ProfileIsProbeBased)
208e8d8bef9SDimitry Andric     // In a pseudo-probe based profile, a callsite is simply represented by the
209e8d8bef9SDimitry Andric     // ID of the probe associated with the call instruction. The probe ID is
210e8d8bef9SDimitry Andric     // encoded in the Discriminator field of the call instruction's debug
211e8d8bef9SDimitry Andric     // metadata.
212e8d8bef9SDimitry Andric     return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
213e8d8bef9SDimitry Andric                             DIL->getDiscriminator()),
214e8d8bef9SDimitry Andric                         0);
215e8d8bef9SDimitry Andric   else
216e8d8bef9SDimitry Andric     return LineLocation(FunctionSamples::getOffset(DIL),
217e8d8bef9SDimitry Andric                         DIL->getBaseDiscriminator());
218e8d8bef9SDimitry Andric }
219e8d8bef9SDimitry Andric 
220e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamples(
221e8d8bef9SDimitry Andric     const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
222*0b57cec5SDimitry Andric   assert(DIL);
223*0b57cec5SDimitry Andric   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric   const DILocation *PrevDIL = DIL;
226*0b57cec5SDimitry Andric   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
227fe6060f1SDimitry Andric     unsigned Discriminator;
228fe6060f1SDimitry Andric     if (ProfileIsFS)
229fe6060f1SDimitry Andric       Discriminator = DIL->getDiscriminator();
230fe6060f1SDimitry Andric     else
231fe6060f1SDimitry Andric       Discriminator = DIL->getBaseDiscriminator();
232fe6060f1SDimitry Andric 
233fe6060f1SDimitry Andric     S.push_back(
234fe6060f1SDimitry Andric         std::make_pair(LineLocation(getOffset(DIL), Discriminator),
235*0b57cec5SDimitry Andric                        PrevDIL->getScope()->getSubprogram()->getLinkageName()));
236*0b57cec5SDimitry Andric     PrevDIL = DIL;
237*0b57cec5SDimitry Andric   }
238*0b57cec5SDimitry Andric   if (S.size() == 0)
239*0b57cec5SDimitry Andric     return this;
240*0b57cec5SDimitry Andric   const FunctionSamples *FS = this;
241*0b57cec5SDimitry Andric   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
242e8d8bef9SDimitry Andric     FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
243*0b57cec5SDimitry Andric   }
244*0b57cec5SDimitry Andric   return FS;
245*0b57cec5SDimitry Andric }
246*0b57cec5SDimitry Andric 
247e8d8bef9SDimitry Andric void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const {
248e8d8bef9SDimitry Andric   NameSet.insert(Name);
249e8d8bef9SDimitry Andric   for (const auto &BS : BodySamples)
250e8d8bef9SDimitry Andric     for (const auto &TS : BS.second.getCallTargets())
251e8d8bef9SDimitry Andric       NameSet.insert(TS.getKey());
252e8d8bef9SDimitry Andric 
253e8d8bef9SDimitry Andric   for (const auto &CS : CallsiteSamples) {
254e8d8bef9SDimitry Andric     for (const auto &NameFS : CS.second) {
255e8d8bef9SDimitry Andric       NameSet.insert(NameFS.first);
256e8d8bef9SDimitry Andric       NameFS.second.findAllNames(NameSet);
257e8d8bef9SDimitry Andric     }
258e8d8bef9SDimitry Andric   }
259e8d8bef9SDimitry Andric }
260e8d8bef9SDimitry Andric 
261e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
262e8d8bef9SDimitry Andric     const LineLocation &Loc, StringRef CalleeName,
263e8d8bef9SDimitry Andric     SampleProfileReaderItaniumRemapper *Remapper) const {
264fe6060f1SDimitry Andric   CalleeName = getCanonicalFnName(CalleeName);
265fe6060f1SDimitry Andric 
266e8d8bef9SDimitry Andric   std::string CalleeGUID;
267e8d8bef9SDimitry Andric   CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID);
268e8d8bef9SDimitry Andric 
269e8d8bef9SDimitry Andric   auto iter = CallsiteSamples.find(Loc);
270e8d8bef9SDimitry Andric   if (iter == CallsiteSamples.end())
271e8d8bef9SDimitry Andric     return nullptr;
272e8d8bef9SDimitry Andric   auto FS = iter->second.find(CalleeName);
273e8d8bef9SDimitry Andric   if (FS != iter->second.end())
274e8d8bef9SDimitry Andric     return &FS->second;
275e8d8bef9SDimitry Andric   if (Remapper) {
276e8d8bef9SDimitry Andric     if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
277e8d8bef9SDimitry Andric       auto FS = iter->second.find(*NameInProfile);
278e8d8bef9SDimitry Andric       if (FS != iter->second.end())
279e8d8bef9SDimitry Andric         return &FS->second;
280e8d8bef9SDimitry Andric     }
281e8d8bef9SDimitry Andric   }
282e8d8bef9SDimitry Andric   // If we cannot find exact match of the callee name, return the FS with
283e8d8bef9SDimitry Andric   // the max total count. Only do this when CalleeName is not provided,
284e8d8bef9SDimitry Andric   // i.e., only for indirect calls.
285e8d8bef9SDimitry Andric   if (!CalleeName.empty())
286e8d8bef9SDimitry Andric     return nullptr;
287e8d8bef9SDimitry Andric   uint64_t MaxTotalSamples = 0;
288e8d8bef9SDimitry Andric   const FunctionSamples *R = nullptr;
289e8d8bef9SDimitry Andric   for (const auto &NameFS : iter->second)
290e8d8bef9SDimitry Andric     if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
291e8d8bef9SDimitry Andric       MaxTotalSamples = NameFS.second.getTotalSamples();
292e8d8bef9SDimitry Andric       R = &NameFS.second;
293e8d8bef9SDimitry Andric     }
294e8d8bef9SDimitry Andric   return R;
295e8d8bef9SDimitry Andric }
296e8d8bef9SDimitry Andric 
297*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
298*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
299*0b57cec5SDimitry Andric #endif
3008bcb0991SDimitry Andric 
3018bcb0991SDimitry Andric std::error_code ProfileSymbolList::read(const uint8_t *Data,
3028bcb0991SDimitry Andric                                         uint64_t ListSize) {
3038bcb0991SDimitry Andric   const char *ListStart = reinterpret_cast<const char *>(Data);
3048bcb0991SDimitry Andric   uint64_t Size = 0;
305fe6060f1SDimitry Andric   uint64_t StrNum = 0;
306fe6060f1SDimitry Andric   while (Size < ListSize && StrNum < ProfileSymbolListCutOff) {
3078bcb0991SDimitry Andric     StringRef Str(ListStart + Size);
3088bcb0991SDimitry Andric     add(Str);
3098bcb0991SDimitry Andric     Size += Str.size() + 1;
310fe6060f1SDimitry Andric     StrNum++;
3118bcb0991SDimitry Andric   }
312fe6060f1SDimitry Andric   if (Size != ListSize && StrNum != ProfileSymbolListCutOff)
3138bcb0991SDimitry Andric     return sampleprof_error::malformed;
3148bcb0991SDimitry Andric   return sampleprof_error::success;
3158bcb0991SDimitry Andric }
3168bcb0991SDimitry Andric 
317fe6060f1SDimitry Andric void SampleContextTrimmer::trimAndMergeColdContextProfiles(
318fe6060f1SDimitry Andric     uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext,
319fe6060f1SDimitry Andric     uint32_t ColdContextFrameLength) {
320fe6060f1SDimitry Andric   if (!TrimColdContext && !MergeColdContext)
321fe6060f1SDimitry Andric     return;
322fe6060f1SDimitry Andric 
323fe6060f1SDimitry Andric   // Nothing to merge if sample threshold is zero
324fe6060f1SDimitry Andric   if (ColdCountThreshold == 0)
325fe6060f1SDimitry Andric     return;
326fe6060f1SDimitry Andric 
327fe6060f1SDimitry Andric   // Filter the cold profiles from ProfileMap and move them into a tmp
328fe6060f1SDimitry Andric   // container
329fe6060f1SDimitry Andric   std::vector<std::pair<StringRef, const FunctionSamples *>> ColdProfiles;
330fe6060f1SDimitry Andric   for (const auto &I : ProfileMap) {
331fe6060f1SDimitry Andric     const FunctionSamples &FunctionProfile = I.second;
332fe6060f1SDimitry Andric     if (FunctionProfile.getTotalSamples() >= ColdCountThreshold)
333fe6060f1SDimitry Andric       continue;
334fe6060f1SDimitry Andric     ColdProfiles.emplace_back(I.getKey(), &I.second);
335fe6060f1SDimitry Andric   }
336fe6060f1SDimitry Andric 
337fe6060f1SDimitry Andric   // Remove the cold profile from ProfileMap and merge them into
338fe6060f1SDimitry Andric   // MergedProfileMap by the last K frames of context
339fe6060f1SDimitry Andric   StringMap<FunctionSamples> MergedProfileMap;
340fe6060f1SDimitry Andric   for (const auto &I : ColdProfiles) {
341fe6060f1SDimitry Andric     if (MergeColdContext) {
342fe6060f1SDimitry Andric       auto Ret = MergedProfileMap.try_emplace(
343fe6060f1SDimitry Andric           I.second->getContext().getContextWithLastKFrames(
344fe6060f1SDimitry Andric               ColdContextFrameLength),
345fe6060f1SDimitry Andric           FunctionSamples());
346fe6060f1SDimitry Andric       FunctionSamples &MergedProfile = Ret.first->second;
347fe6060f1SDimitry Andric       MergedProfile.merge(*I.second);
348fe6060f1SDimitry Andric     }
349fe6060f1SDimitry Andric     ProfileMap.erase(I.first);
350fe6060f1SDimitry Andric   }
351fe6060f1SDimitry Andric 
352fe6060f1SDimitry Andric   // Move the merged profiles into ProfileMap;
353fe6060f1SDimitry Andric   for (const auto &I : MergedProfileMap) {
354fe6060f1SDimitry Andric     // Filter the cold merged profile
355fe6060f1SDimitry Andric     if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold &&
356fe6060f1SDimitry Andric         ProfileMap.find(I.getKey()) == ProfileMap.end())
357fe6060f1SDimitry Andric       continue;
358fe6060f1SDimitry Andric     // Merge the profile if the original profile exists, otherwise just insert
359fe6060f1SDimitry Andric     // as a new profile
360fe6060f1SDimitry Andric     auto Ret = ProfileMap.try_emplace(I.getKey(), FunctionSamples());
361fe6060f1SDimitry Andric     if (Ret.second) {
362fe6060f1SDimitry Andric       SampleContext FContext(Ret.first->first(), RawContext);
363fe6060f1SDimitry Andric       FunctionSamples &FProfile = Ret.first->second;
364fe6060f1SDimitry Andric       FProfile.setContext(FContext);
365fe6060f1SDimitry Andric       FProfile.setName(FContext.getNameWithoutContext());
366fe6060f1SDimitry Andric     }
367fe6060f1SDimitry Andric     FunctionSamples &OrigProfile = Ret.first->second;
368fe6060f1SDimitry Andric     OrigProfile.merge(I.second);
369fe6060f1SDimitry Andric   }
370fe6060f1SDimitry Andric }
371fe6060f1SDimitry Andric 
372fe6060f1SDimitry Andric void SampleContextTrimmer::canonicalizeContextProfiles() {
373fe6060f1SDimitry Andric   std::vector<StringRef> ProfilesToBeRemoved;
374fe6060f1SDimitry Andric   StringMap<FunctionSamples> ProfilesToBeAdded;
375fe6060f1SDimitry Andric   for (auto &I : ProfileMap) {
376fe6060f1SDimitry Andric     FunctionSamples &FProfile = I.second;
377fe6060f1SDimitry Andric     StringRef ContextStr = FProfile.getNameWithContext();
378fe6060f1SDimitry Andric     if (I.first() == ContextStr)
379fe6060f1SDimitry Andric       continue;
380fe6060f1SDimitry Andric 
381fe6060f1SDimitry Andric     // Use the context string from FunctionSamples to update the keys of
382fe6060f1SDimitry Andric     // ProfileMap. They can get out of sync after context profile promotion
383fe6060f1SDimitry Andric     // through pre-inliner.
384fe6060f1SDimitry Andric     // Duplicate the function profile for later insertion to avoid a conflict
385fe6060f1SDimitry Andric     // caused by a context both to be add and to be removed. This could happen
386fe6060f1SDimitry Andric     // when a context is promoted to another context which is also promoted to
387fe6060f1SDimitry Andric     // the third context. For example, given an original context A @ B @ C that
388fe6060f1SDimitry Andric     // is promoted to B @ C and the original context B @ C which is promoted to
389fe6060f1SDimitry Andric     // just C, adding B @ C to the profile map while removing same context (but
390fe6060f1SDimitry Andric     // with different profiles) from the map can cause a conflict if they are
391fe6060f1SDimitry Andric     // not handled in a right order. This can be solved by just caching the
392fe6060f1SDimitry Andric     // profiles to be added.
393fe6060f1SDimitry Andric     auto Ret = ProfilesToBeAdded.try_emplace(ContextStr, FProfile);
394fe6060f1SDimitry Andric     (void)Ret;
395fe6060f1SDimitry Andric     assert(Ret.second && "Context conflict during canonicalization");
396fe6060f1SDimitry Andric     ProfilesToBeRemoved.push_back(I.first());
397fe6060f1SDimitry Andric   }
398fe6060f1SDimitry Andric 
399fe6060f1SDimitry Andric   for (auto &I : ProfilesToBeRemoved) {
400fe6060f1SDimitry Andric     ProfileMap.erase(I);
401fe6060f1SDimitry Andric   }
402fe6060f1SDimitry Andric 
403fe6060f1SDimitry Andric   for (auto &I : ProfilesToBeAdded) {
404fe6060f1SDimitry Andric     ProfileMap.try_emplace(I.first(), I.second);
405fe6060f1SDimitry Andric   }
406fe6060f1SDimitry Andric }
407fe6060f1SDimitry Andric 
4088bcb0991SDimitry Andric std::error_code ProfileSymbolList::write(raw_ostream &OS) {
4098bcb0991SDimitry Andric   // Sort the symbols before output. If doing compression.
4108bcb0991SDimitry Andric   // It will make the compression much more effective.
411e8d8bef9SDimitry Andric   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
4128bcb0991SDimitry Andric   llvm::sort(SortedList);
4138bcb0991SDimitry Andric 
4148bcb0991SDimitry Andric   std::string OutputString;
4158bcb0991SDimitry Andric   for (auto &Sym : SortedList) {
4168bcb0991SDimitry Andric     OutputString.append(Sym.str());
4178bcb0991SDimitry Andric     OutputString.append(1, '\0');
4188bcb0991SDimitry Andric   }
4198bcb0991SDimitry Andric 
4208bcb0991SDimitry Andric   OS << OutputString;
4218bcb0991SDimitry Andric   return sampleprof_error::success;
4228bcb0991SDimitry Andric }
4238bcb0991SDimitry Andric 
4248bcb0991SDimitry Andric void ProfileSymbolList::dump(raw_ostream &OS) const {
4258bcb0991SDimitry Andric   OS << "======== Dump profile symbol list ========\n";
426e8d8bef9SDimitry Andric   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
4278bcb0991SDimitry Andric   llvm::sort(SortedList);
4288bcb0991SDimitry Andric 
4298bcb0991SDimitry Andric   for (auto &Sym : SortedList)
4308bcb0991SDimitry Andric     OS << Sym << "\n";
4318bcb0991SDimitry Andric }
432