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