LLVM 23.0.0git
SampleProfileMatcher.cpp
Go to the documentation of this file.
1//===- SampleProfileMatcher.cpp - Sampling-based Stale Profile Matcher ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SampleProfileMatcher used for stale
10// profile matching.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
18#include "llvm/IR/MDBuilder.h"
21
22#include <unordered_set>
23
24using namespace llvm;
25using namespace sampleprof;
26
27#define DEBUG_TYPE "sample-profile-matcher"
28
29STATISTIC(NumDirectProfileMatch,
30 "Number of functions matched by demangled basename");
31
32namespace llvm {
33
35 "func-profile-similarity-threshold", cl::Hidden, cl::init(80),
36 cl::desc("Consider a profile matches a function if the similarity of their "
37 "callee sequences is above the specified percentile."));
38
40 "min-func-count-for-cg-matching", cl::Hidden, cl::init(5),
41 cl::desc("The minimum number of basic blocks required for a function to "
42 "run stale profile call graph matching."));
43
45 "min-call-count-for-cg-matching", cl::Hidden, cl::init(3),
46 cl::desc("The minimum number of call anchors required for a function to "
47 "run stale profile call graph matching."));
48
50 "load-func-profile-for-cg-matching", cl::Hidden, cl::init(true),
52 "Load top-level profiles that the sample reader initially skipped for "
53 "the call-graph matching (only meaningful for extended binary "
54 "format)"));
55
60
62 "salvage-unused-profile-max-functions", cl::Hidden, cl::init(UINT_MAX),
63 cl::desc("The maximum number of functions in a module, above which salvage "
64 "unused profile will be skipped."));
65
67 "salvage-stale-profile-max-callsites", cl::Hidden, cl::init(UINT_MAX),
68 cl::desc("The maximum number of callsites in a function, above which stale "
69 "profile matching will be skipped."));
70
71} // end namespace llvm
72
73void SampleProfileMatcher::findIRAnchors(const Function &F,
74 AnchorMap &IRAnchors) const {
75 // For inlined code, recover the original callsite and callee by finding the
76 // top-level inline frame. e.g. For frame stack "main:1 @ foo:2 @ bar:3", the
77 // top-level frame is "main:1", the callsite is "1" and the callee is "foo".
78 auto FindTopLevelInlinedCallsite = [](const DILocation *DIL) {
79 assert((DIL && DIL->getInlinedAt()) && "No inlined callsite");
80 const DILocation *PrevDIL = nullptr;
81 do {
82 PrevDIL = DIL;
83 DIL = DIL->getInlinedAt();
84 } while (DIL->getInlinedAt());
85
86 LineLocation Callsite = FunctionSamples::getCallSiteIdentifier(
88 StringRef CalleeName = PrevDIL->getSubprogramLinkageName();
89 return std::make_pair(Callsite, FunctionId(CalleeName));
90 };
91
92 auto GetCanonicalCalleeName = [](const CallBase *CB) {
93 StringRef CalleeName = UnknownIndirectCallee;
94 if (Function *Callee = CB->getCalledFunction())
95 CalleeName = FunctionSamples::getCanonicalFnName(Callee->getName());
96 return CalleeName;
97 };
98
99 // Extract profile matching anchors in the IR.
100 for (auto &BB : F) {
101 for (auto &I : BB) {
102 DILocation *DIL = I.getDebugLoc();
103 if (!DIL)
104 continue;
105
107 if (auto Probe = extractProbe(I)) {
108 // Flatten inlined IR for the matching.
109 if (DIL->getInlinedAt()) {
110 IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
111 } else {
112 // Use empty StringRef for basic block probe.
113 StringRef CalleeName;
114 if (const auto *CB = dyn_cast<CallBase>(&I)) {
115 // Skip the probe inst whose callee name is "llvm.pseudoprobe".
116 if (!isa<IntrinsicInst>(&I))
117 CalleeName = GetCanonicalCalleeName(CB);
118 }
119 LineLocation Loc = LineLocation(Probe->Id, 0);
120 IRAnchors.emplace(Loc, FunctionId(CalleeName));
121 }
122 }
123 } else {
124 // TODO: For line-number based profile(AutoFDO), currently only support
125 // find callsite anchors. In future, we need to parse all the non-call
126 // instructions to extract the line locations for profile matching.
128 continue;
129
130 if (DIL->getInlinedAt()) {
131 IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
132 } else {
133 LineLocation Callsite = FunctionSamples::getCallSiteIdentifier(
135 StringRef CalleeName = GetCanonicalCalleeName(dyn_cast<CallBase>(&I));
136 IRAnchors.emplace(Callsite, FunctionId(CalleeName));
137 }
138 }
139 }
140 }
141}
142
143void SampleProfileMatcher::findProfileAnchors(const FunctionSamples &FS,
144 AnchorMap &ProfileAnchors) const {
145 auto isInvalidLineOffset = [](uint32_t LineOffset) {
146 return LineOffset & 0x8000;
147 };
148
149 auto InsertAnchor = [](const LineLocation &Loc, const FunctionId &CalleeName,
150 AnchorMap &ProfileAnchors) {
151 auto Ret = ProfileAnchors.try_emplace(Loc, CalleeName);
152 if (!Ret.second) {
153 // For multiple callees, which indicates it's an indirect call, we use a
154 // dummy name(UnknownIndirectCallee) as the indrect callee name.
155 Ret.first->second = FunctionId(UnknownIndirectCallee);
156 }
157 };
158
159 for (const auto &I : FS.getBodySamples()) {
160 const LineLocation &Loc = I.first;
161 if (isInvalidLineOffset(Loc.LineOffset))
162 continue;
163 for (const auto &C : I.second.getCallTargets())
164 InsertAnchor(Loc, C.first, ProfileAnchors);
165 }
166
167 for (const auto &I : FS.getCallsiteSamples()) {
168 const LineLocation &Loc = I.first;
169 if (isInvalidLineOffset(Loc.LineOffset))
170 continue;
171 for (const auto &C : I.second)
172 InsertAnchor(Loc, C.first, ProfileAnchors);
173 }
174}
175
176bool SampleProfileMatcher::functionHasProfile(const FunctionId &IRFuncName,
177 Function *&FuncWithoutProfile) {
178 FuncWithoutProfile = nullptr;
179 auto R = FunctionsWithoutProfile.find(IRFuncName);
180 if (R != FunctionsWithoutProfile.end())
181 FuncWithoutProfile = R->second;
182 return !FuncWithoutProfile;
183}
184
185bool SampleProfileMatcher::isProfileUnused(const FunctionId &ProfileFuncName) {
186 return SymbolMap->find(ProfileFuncName) == SymbolMap->end();
187}
188
189bool SampleProfileMatcher::functionMatchesProfile(
190 const FunctionId &IRFuncName, const FunctionId &ProfileFuncName,
191 bool FindMatchedProfileOnly) {
192 if (IRFuncName == ProfileFuncName)
193 return true;
195 return false;
196
197 // If IR function doesn't have profile and the profile is unused, try
198 // matching them.
199 Function *IRFunc = nullptr;
200 if (functionHasProfile(IRFuncName, IRFunc) ||
201 !isProfileUnused(ProfileFuncName))
202 return false;
203
204 assert(FunctionId(IRFunc->getName()) != ProfileFuncName &&
205 "IR function should be different from profile function to match");
206 return functionMatchesProfile(*IRFunc, ProfileFuncName,
207 FindMatchedProfileOnly);
208}
209
211SampleProfileMatcher::longestCommonSequence(const AnchorList &AnchorList1,
212 const AnchorList &AnchorList2,
213 bool MatchUnusedFunction) {
214 LocToLocMap MatchedAnchors;
216 AnchorList1, AnchorList2,
217 [&](const FunctionId &A, const FunctionId &B) {
218 return functionMatchesProfile(
219 A, B,
220 !MatchUnusedFunction // Find matched function only
221 );
222 },
223 [&](LineLocation A, LineLocation B) {
224 MatchedAnchors.try_emplace(A, B);
225 });
226 return MatchedAnchors;
227}
228
229void SampleProfileMatcher::matchNonCallsiteLocs(
230 const LocToLocMap &MatchedAnchors, const AnchorMap &IRAnchors,
231 LocToLocMap &IRToProfileLocationMap) {
232 auto InsertMatching = [&](const LineLocation &From, const LineLocation &To) {
233 // Skip the unchanged location mapping to save memory.
234 if (From != To)
235 IRToProfileLocationMap.insert({From, To});
236 };
237
238 // Use function's beginning location as the initial anchor.
239 int32_t LocationDelta = 0;
240 SmallVector<LineLocation> LastMatchedNonAnchors;
241 for (const auto &IR : IRAnchors) {
242 const auto &Loc = IR.first;
243 bool IsMatchedAnchor = false;
244 // Match the anchor location in lexical order.
245 auto R = MatchedAnchors.find(Loc);
246 if (R != MatchedAnchors.end()) {
247 const auto &Candidate = R->second;
248 InsertMatching(Loc, Candidate);
249 LLVM_DEBUG(dbgs() << "Callsite with callee:" << IR.second.stringRef()
250 << " is matched from " << Loc << " to " << Candidate
251 << "\n");
252 LocationDelta = Candidate.LineOffset - Loc.LineOffset;
253
254 // Match backwards for non-anchor locations.
255 // The locations in LastMatchedNonAnchors have been matched forwards
256 // based on the previous anchor, spilt it evenly and overwrite the
257 // second half based on the current anchor.
258 for (size_t I = (LastMatchedNonAnchors.size() + 1) / 2;
259 I < LastMatchedNonAnchors.size(); I++) {
260 const auto &L = LastMatchedNonAnchors[I];
261 uint32_t CandidateLineOffset = L.LineOffset + LocationDelta;
262 LineLocation Candidate(CandidateLineOffset, L.Discriminator);
263 InsertMatching(L, Candidate);
264 LLVM_DEBUG(dbgs() << "Location is rematched backwards from " << L
265 << " to " << Candidate << "\n");
266 }
267
268 IsMatchedAnchor = true;
269 LastMatchedNonAnchors.clear();
270 }
271
272 // Match forwards for non-anchor locations.
273 if (!IsMatchedAnchor) {
274 uint32_t CandidateLineOffset = Loc.LineOffset + LocationDelta;
275 LineLocation Candidate(CandidateLineOffset, Loc.Discriminator);
276 InsertMatching(Loc, Candidate);
277 LLVM_DEBUG(dbgs() << "Location is matched from " << Loc << " to "
278 << Candidate << "\n");
279 LastMatchedNonAnchors.emplace_back(Loc);
280 }
281 }
282}
283
284// Filter the non-call locations from IRAnchors and ProfileAnchors and write
285// them into a list for random access later.
286void SampleProfileMatcher::getFilteredAnchorList(
287 const AnchorMap &IRAnchors, const AnchorMap &ProfileAnchors,
288 AnchorList &FilteredIRAnchorsList, AnchorList &FilteredProfileAnchorList) {
289 for (const auto &I : IRAnchors) {
290 if (I.second.stringRef().empty())
291 continue;
292 FilteredIRAnchorsList.emplace_back(I);
293 }
294
295 for (const auto &I : ProfileAnchors)
296 FilteredProfileAnchorList.emplace_back(I);
297}
298
299// Call target name anchor based profile fuzzy matching.
300// Input:
301// For IR locations, the anchor is the callee name of direct callsite; For
302// profile locations, it's the call target name for BodySamples or inlinee's
303// profile name for CallsiteSamples.
304// Matching heuristic:
305// First match all the anchors using the diff algorithm, then split the
306// non-anchor locations between the two anchors evenly, first half are matched
307// based on the start anchor, second half are matched based on the end anchor.
308// For example, given:
309// IR locations: [1, 2(foo), 3, 5, 6(bar), 7]
310// Profile locations: [1, 2, 3(foo), 4, 7, 8(bar), 9]
311// The matching gives:
312// [1, 2(foo), 3, 5, 6(bar), 7]
313// | | | | | |
314// [1, 2, 3(foo), 4, 7, 8(bar), 9]
315// The output mapping: [2->3, 3->4, 5->7, 6->8, 7->9].
316void SampleProfileMatcher::runStaleProfileMatching(
317 const Function &F, const AnchorMap &IRAnchors,
318 const AnchorMap &ProfileAnchors, LocToLocMap &IRToProfileLocationMap,
319 bool RunCFGMatching, bool RunCGMatching) {
320 if (!RunCFGMatching && !RunCGMatching)
321 return;
322 LLVM_DEBUG(dbgs() << "Run stale profile matching for " << F.getName()
323 << "\n");
324 assert(IRToProfileLocationMap.empty() &&
325 "Run stale profile matching only once per function");
326
327 AnchorList FilteredProfileAnchorList;
328 AnchorList FilteredIRAnchorsList;
329 getFilteredAnchorList(IRAnchors, ProfileAnchors, FilteredIRAnchorsList,
330 FilteredProfileAnchorList);
331
332 if (FilteredIRAnchorsList.empty() || FilteredProfileAnchorList.empty())
333 return;
334
335 if (FilteredIRAnchorsList.size() > SalvageStaleProfileMaxCallsites ||
336 FilteredProfileAnchorList.size() > SalvageStaleProfileMaxCallsites) {
337 LLVM_DEBUG(dbgs() << "Skip stale profile matching for " << F.getName()
338 << " because the number of callsites in the IR is "
339 << FilteredIRAnchorsList.size()
340 << " and in the profile is "
341 << FilteredProfileAnchorList.size() << "\n");
342 return;
343 }
344
345 // Match the callsite anchors by finding the longest common subsequence
346 // between IR and profile.
347 // Define a match between two anchors as follows:
348 // 1) The function names of anchors are the same.
349 // 2) The similarity between the anchor functions is above a threshold if
350 // RunCGMatching is set.
351 // For 2), we only consider the anchor functions from IR and profile don't
352 // appear on either side to reduce the matching scope. Note that we need to
353 // use IR anchor as base(A side) to align with the order of
354 // IRToProfileLocationMap.
355 LocToLocMap MatchedAnchors =
356 longestCommonSequence(FilteredIRAnchorsList, FilteredProfileAnchorList,
357 RunCGMatching /* Match unused functions */);
358
359 // CFG level matching:
360 // Apply the callsite matchings to infer matching for the basic
361 // block(non-callsite) locations and write the result to
362 // IRToProfileLocationMap.
363 if (RunCFGMatching)
364 matchNonCallsiteLocs(MatchedAnchors, IRAnchors, IRToProfileLocationMap);
365}
366
367void SampleProfileMatcher::runOnFunction(Function &F) {
368 // We need to use flattened function samples for matching.
369 // Unlike IR, which includes all callsites from the source code, the callsites
370 // in profile only show up when they are hit by samples, i,e. the profile
371 // callsites in one context may differ from those in another context. To get
372 // the maximum number of callsites, we merge the function profiles from all
373 // contexts, aka, the flattened profile to find profile anchors.
374 const auto *FSForMatching = getFlattenedSamplesFor(F);
375 if (SalvageUnusedProfile && !FSForMatching) {
376 // Apply the matching in place to find the new function's matched profile.
377 auto R = FuncToProfileNameMap.find(&F);
378 if (R != FuncToProfileNameMap.end()) {
379 FSForMatching = getFlattenedSamplesFor(R->second);
380 // Fallback for profiles loaded by functionMatchesProfileHelper but not
381 // yet in FlattenedProfiles. This should be rare now that
382 // functionMatchesProfileHelper flattens after loading.
383 if (!FSForMatching && LoadFuncProfileforCGMatching)
384 FSForMatching = Reader.getSamplesFor(R->second.stringRef());
385 }
386 }
387 if (!FSForMatching)
388 return;
389
390 // Anchors for IR. It's a map from IR location to callee name, callee name is
391 // empty for non-call instruction and use a dummy name(UnknownIndirectCallee)
392 // for unknown indrect callee name.
393 AnchorMap IRAnchors;
394 findIRAnchors(F, IRAnchors);
395 // Anchors for profile. It's a map from callsite location to a set of callee
396 // name.
397 AnchorMap ProfileAnchors;
398 findProfileAnchors(*FSForMatching, ProfileAnchors);
399
400 // Compute the callsite match states for profile staleness report.
402 recordCallsiteMatchStates(F, IRAnchors, ProfileAnchors, nullptr);
403
405 return;
406 // For probe-based profiles, run matching only when profile checksum is
407 // mismatched.
408 bool ChecksumMismatch = FunctionSamples::ProfileIsProbeBased &&
409 !ProbeManager->profileIsValid(F, *FSForMatching);
410 bool RunCFGMatching =
411 !FunctionSamples::ProfileIsProbeBased || ChecksumMismatch;
412 bool RunCGMatching = SalvageUnusedProfile;
413 // For imported functions, the checksum metadata(pseudo_probe_desc) are
414 // dropped, so we leverage function attribute(profile-checksum-mismatch) to
415 // transfer the info: add the attribute during pre-link phase and check it
416 // during post-link phase(see "profileIsValid").
417 if (ChecksumMismatch && LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink)
418 F.addFnAttr("profile-checksum-mismatch");
419
420 // The matching result will be saved to IRToProfileLocationMap, create a
421 // new map for each function.
422 auto &IRToProfileLocationMap = getIRToProfileLocationMap(F);
423 runStaleProfileMatching(F, IRAnchors, ProfileAnchors, IRToProfileLocationMap,
424 RunCFGMatching, RunCGMatching);
425 // Find and update callsite match states after matching.
426 if (RunCFGMatching && (ReportProfileStaleness || PersistProfileStaleness))
427 recordCallsiteMatchStates(F, IRAnchors, ProfileAnchors,
428 &IRToProfileLocationMap);
429}
430
431void SampleProfileMatcher::recordCallsiteMatchStates(
432 const Function &F, const AnchorMap &IRAnchors,
433 const AnchorMap &ProfileAnchors,
434 const LocToLocMap *IRToProfileLocationMap) {
435 bool IsPostMatch = IRToProfileLocationMap != nullptr;
436 auto &CallsiteMatchStates =
437 FuncCallsiteMatchStates[FunctionSamples::getCanonicalFnName(F.getName())];
438
439 auto MapIRLocToProfileLoc = [&](const LineLocation &IRLoc) {
440 // IRToProfileLocationMap is null in pre-match phrase.
441 if (!IRToProfileLocationMap)
442 return IRLoc;
443 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
444 if (ProfileLoc != IRToProfileLocationMap->end())
445 return ProfileLoc->second;
446 else
447 return IRLoc;
448 };
449
450 for (const auto &I : IRAnchors) {
451 // After fuzzy profile matching, use the matching result to remap the
452 // current IR callsite.
453 const auto &ProfileLoc = MapIRLocToProfileLoc(I.first);
454 const auto &IRCalleeId = I.second;
455 const auto &It = ProfileAnchors.find(ProfileLoc);
456 if (It == ProfileAnchors.end())
457 continue;
458 const auto &ProfCalleeId = It->second;
459 if (IRCalleeId == ProfCalleeId) {
460 auto It = CallsiteMatchStates.find(ProfileLoc);
461 if (It == CallsiteMatchStates.end())
462 CallsiteMatchStates.emplace(ProfileLoc, MatchState::InitialMatch);
463 else if (IsPostMatch) {
464 if (It->second == MatchState::InitialMatch)
465 It->second = MatchState::UnchangedMatch;
466 else if (It->second == MatchState::InitialMismatch)
467 It->second = MatchState::RecoveredMismatch;
468 }
469 }
470 }
471
472 // Check if there are any callsites in the profile that does not match to any
473 // IR callsites.
474 for (const auto &I : ProfileAnchors) {
475 const auto &Loc = I.first;
476 assert(!I.second.stringRef().empty() && "Callees should not be empty");
477 auto It = CallsiteMatchStates.find(Loc);
478 if (It == CallsiteMatchStates.end())
479 CallsiteMatchStates.emplace(Loc, MatchState::InitialMismatch);
480 else if (IsPostMatch) {
481 // Update the state if it's not matched(UnchangedMatch or
482 // RecoveredMismatch).
483 if (It->second == MatchState::InitialMismatch)
484 It->second = MatchState::UnchangedMismatch;
485 else if (It->second == MatchState::InitialMatch)
486 It->second = MatchState::RemovedMatch;
487 }
488 }
489}
490
491void SampleProfileMatcher::countMismatchedFuncSamples(const FunctionSamples &FS,
492 bool IsTopLevel) {
493 const auto *FuncDesc = ProbeManager->getDesc(FS.getGUID());
494 // Skip the function that is external or renamed.
495 if (!FuncDesc)
496 return;
497
498 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS)) {
499 if (IsTopLevel)
500 NumStaleProfileFunc++;
501 // Given currently all probe ids are after block probe ids, once the
502 // checksum is mismatched, it's likely all the callites are mismatched and
503 // dropped. We conservatively count all the samples as mismatched and stop
504 // counting the inlinees' profiles.
505 MismatchedFunctionSamples += FS.getTotalSamples();
506 return;
507 }
508
509 // Even the current-level function checksum is matched, it's possible that the
510 // nested inlinees' checksums are mismatched that affect the inlinee's sample
511 // loading, we need to go deeper to check the inlinees' function samples.
512 // Similarly, count all the samples as mismatched if the inlinee's checksum is
513 // mismatched using this recursive function.
514 for (const auto &I : FS.getCallsiteSamples())
515 for (const auto &CS : I.second)
516 countMismatchedFuncSamples(CS.second, false);
517}
518
519void SampleProfileMatcher::countMismatchedCallsiteSamples(
520 const FunctionSamples &FS) {
521 auto It = FuncCallsiteMatchStates.find(FS.getFuncName());
522 // Skip it if no mismatched callsite or this is an external function.
523 if (It == FuncCallsiteMatchStates.end() || It->second.empty())
524 return;
525 const auto &CallsiteMatchStates = It->second;
526
527 auto findMatchState = [&](const LineLocation &Loc) {
528 auto It = CallsiteMatchStates.find(Loc);
529 if (It == CallsiteMatchStates.end())
530 return MatchState::Unknown;
531 return It->second;
532 };
533
534 auto AttributeMismatchedSamples = [&](const enum MatchState &State,
535 uint64_t Samples) {
536 if (isMismatchState(State))
537 MismatchedCallsiteSamples += Samples;
538 else if (State == MatchState::RecoveredMismatch)
539 RecoveredCallsiteSamples += Samples;
540 };
541
542 // The non-inlined callsites are saved in the body samples of function
543 // profile, go through it to count the non-inlined callsite samples.
544 for (const auto &I : FS.getBodySamples())
545 AttributeMismatchedSamples(findMatchState(I.first), I.second.getSamples());
546
547 // Count the inlined callsite samples.
548 for (const auto &I : FS.getCallsiteSamples()) {
549 auto State = findMatchState(I.first);
550 uint64_t CallsiteSamples = 0;
551 for (const auto &CS : I.second)
552 CallsiteSamples += CS.second.getTotalSamples();
553 AttributeMismatchedSamples(State, CallsiteSamples);
554
555 if (isMismatchState(State))
556 continue;
557
558 // When the current level of inlined call site matches the profiled call
559 // site, we need to go deeper along the inline tree to count mismatches from
560 // lower level inlinees.
561 for (const auto &CS : I.second)
562 countMismatchedCallsiteSamples(CS.second);
563 }
564}
565
566void SampleProfileMatcher::countMismatchCallsites(const FunctionSamples &FS) {
567 auto It = FuncCallsiteMatchStates.find(FS.getFuncName());
568 // Skip it if no mismatched callsite or this is an external function.
569 if (It == FuncCallsiteMatchStates.end() || It->second.empty())
570 return;
571 const auto &MatchStates = It->second;
572 [[maybe_unused]] bool OnInitialState =
573 isInitialState(MatchStates.begin()->second);
574 for (const auto &I : MatchStates) {
575 TotalProfiledCallsites++;
576 assert(
577 (OnInitialState ? isInitialState(I.second) : isFinalState(I.second)) &&
578 "Profile matching state is inconsistent");
579
580 if (isMismatchState(I.second))
581 NumMismatchedCallsites++;
582 else if (I.second == MatchState::RecoveredMismatch)
583 NumRecoveredCallsites++;
584 }
585}
586
587void SampleProfileMatcher::countCallGraphRecoveredSamples(
588 const FunctionSamples &FS,
589 std::unordered_set<FunctionId> &CallGraphRecoveredProfiles) {
590 if (CallGraphRecoveredProfiles.count(FS.getFunction())) {
591 NumCallGraphRecoveredFuncSamples += FS.getTotalSamples();
592 return;
593 }
594
595 for (const auto &CM : FS.getCallsiteSamples()) {
596 for (const auto &CS : CM.second) {
597 countCallGraphRecoveredSamples(CS.second, CallGraphRecoveredProfiles);
598 }
599 }
600}
601
602void SampleProfileMatcher::computeAndReportProfileStaleness() {
604 return;
605
606 std::unordered_set<FunctionId> CallGraphRecoveredProfiles;
608 for (const auto &I : FuncToProfileNameMap) {
609 CallGraphRecoveredProfiles.insert(I.second);
610 if (GlobalValue::isAvailableExternallyLinkage(I.first->getLinkage()))
611 continue;
612 NumCallGraphRecoveredProfiledFunc++;
613 }
614 }
615
616 // Count profile mismatches for profile staleness report.
617 for (const auto &F : M) {
619 continue;
620 // As the stats will be merged by linker, skip reporting the metrics for
621 // imported functions to avoid repeated counting.
623 continue;
624 const auto *FS = Reader.getSamplesFor(F);
625 if (!FS)
626 continue;
627 TotalProfiledFunc++;
628 TotalFunctionSamples += FS->getTotalSamples();
629
630 if (SalvageUnusedProfile && !CallGraphRecoveredProfiles.empty())
631 countCallGraphRecoveredSamples(*FS, CallGraphRecoveredProfiles);
632
633 // Checksum mismatch is only used in pseudo-probe mode.
635 countMismatchedFuncSamples(*FS, true);
636
637 // Count mismatches and samples for calliste.
638 countMismatchCallsites(*FS);
639 countMismatchedCallsiteSamples(*FS);
640 }
641
644 errs() << "(" << NumStaleProfileFunc << "/" << TotalProfiledFunc
645 << ") of functions' profile are invalid and ("
646 << MismatchedFunctionSamples << "/" << TotalFunctionSamples
647 << ") of samples are discarded due to function hash mismatch.\n";
648 }
650 errs() << "(" << NumCallGraphRecoveredProfiledFunc << "/"
651 << TotalProfiledFunc << ") of functions' profile are matched and ("
652 << NumCallGraphRecoveredFuncSamples << "/" << TotalFunctionSamples
653 << ") of samples are reused by call graph matching.\n";
654 }
655
656 errs() << "(" << (NumMismatchedCallsites + NumRecoveredCallsites) << "/"
657 << TotalProfiledCallsites
658 << ") of callsites' profile are invalid and ("
659 << (MismatchedCallsiteSamples + RecoveredCallsiteSamples) << "/"
660 << TotalFunctionSamples
661 << ") of samples are discarded due to callsite location mismatch.\n";
662 errs() << "(" << NumRecoveredCallsites << "/"
663 << (NumRecoveredCallsites + NumMismatchedCallsites)
664 << ") of callsites and (" << RecoveredCallsiteSamples << "/"
665 << (RecoveredCallsiteSamples + MismatchedCallsiteSamples)
666 << ") of samples are recovered by stale profile matching.\n";
667 }
668
670 LLVMContext &Ctx = M.getContext();
671 MDBuilder MDB(Ctx);
672
675 ProfStatsVec.emplace_back("NumStaleProfileFunc", NumStaleProfileFunc);
676 ProfStatsVec.emplace_back("TotalProfiledFunc", TotalProfiledFunc);
677 ProfStatsVec.emplace_back("MismatchedFunctionSamples",
678 MismatchedFunctionSamples);
679 ProfStatsVec.emplace_back("TotalFunctionSamples", TotalFunctionSamples);
680 }
681
683 ProfStatsVec.emplace_back("NumCallGraphRecoveredProfiledFunc",
684 NumCallGraphRecoveredProfiledFunc);
685 ProfStatsVec.emplace_back("NumCallGraphRecoveredFuncSamples",
686 NumCallGraphRecoveredFuncSamples);
687 }
688
689 ProfStatsVec.emplace_back("NumMismatchedCallsites", NumMismatchedCallsites);
690 ProfStatsVec.emplace_back("NumRecoveredCallsites", NumRecoveredCallsites);
691 ProfStatsVec.emplace_back("TotalProfiledCallsites", TotalProfiledCallsites);
692 ProfStatsVec.emplace_back("MismatchedCallsiteSamples",
693 MismatchedCallsiteSamples);
694 ProfStatsVec.emplace_back("RecoveredCallsiteSamples",
695 RecoveredCallsiteSamples);
696
697 auto *MD = MDB.createLLVMStats(ProfStatsVec);
698 auto *NMD = M.getOrInsertNamedMetadata("llvm.stats");
699 NMD->addOperand(MD);
700 }
701}
702
703void SampleProfileMatcher::findFunctionsWithoutProfile() {
704 // TODO: Support MD5 profile.
706 return;
707 StringSet<> NamesInProfile;
708 if (auto NameTable = Reader.getNameTable()) {
709 for (auto Name : *NameTable)
710 NamesInProfile.insert(Name.stringRef());
711 }
712
713 for (auto &F : M) {
714 // Skip declarations, as even if the function can be matched, we have
715 // nothing to do with it.
716 if (F.isDeclaration())
717 continue;
718
719 StringRef CanonFName = FunctionSamples::getCanonicalFnName(F.getName());
720 const auto *FS = getFlattenedSamplesFor(F);
721 if (FS)
722 continue;
723
724 // For extended binary, functions fully inlined may not be loaded in the
725 // top-level profile, so check the NameTable which has the all symbol names
726 // in profile.
727 if (NamesInProfile.count(CanonFName))
728 continue;
729
730 // For extended binary, non-profiled function symbols are in the profile
731 // symbol list table.
732 if (PSL && PSL->contains(CanonFName))
733 continue;
734
735 LLVM_DEBUG(dbgs() << "Function " << CanonFName
736 << " is not in profile or profile symbol list.\n");
737 FunctionsWithoutProfile[FunctionId(CanonFName)] = &F;
738 }
739}
740
741// Demangle \p FName and return the base function name (stripping namespaces,
742// templates, and parameter types). Returns an empty string on failure.
743static std::string getDemangledBaseName(ItaniumPartialDemangler &Demangler,
744 StringRef FName) {
745 auto FunctionName = FName.str();
746 if (Demangler.partialDemangle(FunctionName.c_str()))
747 return std::string();
748 size_t BaseNameSize = 0;
749 // The demangler API follows the __cxa_demangle one, and thus needs a
750 // pointer that originates from malloc (or nullptr) and the caller is
751 // responsible for free()-ing the buffer.
752 char *BaseNamePtr = Demangler.getFunctionBaseName(nullptr, &BaseNameSize);
753 std::string Result = (BaseNamePtr && BaseNameSize)
754 ? std::string(BaseNamePtr, BaseNameSize)
755 : std::string();
756 free(BaseNamePtr);
757 // Trim trailing whitespace/null — getFunctionBaseName may include trailing
758 // characters in the reported size.
759 while (!Result.empty() && (Result.back() == ' ' || Result.back() == '\0'))
760 Result.pop_back();
761 return Result;
762}
763
764void SampleProfileMatcher::matchFunctionsWithoutProfileByBasename() {
765 if (FunctionsWithoutProfile.empty() || !LoadFuncProfileforCGMatching)
766 return;
767 auto *NameTable = Reader.getNameTable();
768 if (!NameTable)
769 return;
770
771 ItaniumPartialDemangler Demangler;
772
773 // Build a map from demangled basename to orphan function. Only keep
774 // basenames that map to exactly one orphan — ambiguous basenames like
775 // "get" or "operator()" would produce false positives.
776 StringMap<Function *> OrphansByBaseName;
777 StringSet<> AmbiguousBaseNames;
778 for (auto &[FuncId, Func] : FunctionsWithoutProfile) {
779 std::string BaseName = getDemangledBaseName(Demangler, Func->getName());
780 if (BaseName.empty() || AmbiguousBaseNames.count(BaseName))
781 continue;
782 auto [It, Inserted] = OrphansByBaseName.try_emplace(BaseName, Func);
783 if (!Inserted) {
784 // More than one orphan shares this basename — mark ambiguous.
785 OrphansByBaseName.erase(It);
786 AmbiguousBaseNames.insert(BaseName);
787 }
788 }
789 if (OrphansByBaseName.empty())
790 return;
791
792 // Scan the profile NameTable for candidates whose demangled basename matches
793 // a unique orphan. Use a quick substring check to avoid demangling every
794 // entry. Only keep 1:1 basename matches (exactly one profile candidate).
795 // Maps basename -> profile FunctionId; entries with multiple candidates are
796 // removed.
797 StringMap<FunctionId> CandidateByBaseName;
798 for (auto &ProfileFuncId : *NameTable) {
799 StringRef ProfName = ProfileFuncId.stringRef();
800 if (ProfName.empty())
801 continue;
802 for (auto &[BaseName, _] : OrphansByBaseName) {
803 if (AmbiguousBaseNames.count(BaseName) || !ProfName.contains(BaseName))
804 continue;
805 std::string ProfBaseName = getDemangledBaseName(Demangler, ProfName);
806 if (ProfBaseName != BaseName)
807 continue;
808 auto [It, Inserted] =
809 CandidateByBaseName.try_emplace(BaseName, ProfileFuncId);
810 if (!Inserted) {
811 // More than one profile entry shares this basename — mark ambiguous.
812 CandidateByBaseName.erase(It);
813 AmbiguousBaseNames.insert(BaseName);
814 }
815 break;
816 }
817 }
818 if (CandidateByBaseName.empty())
819 return;
820
821 // Load candidate profiles on demand, match, and flatten.
822 DenseSet<StringRef> ToLoad;
823 for (auto &[BaseName, ProfId] : CandidateByBaseName)
824 ToLoad.insert(ProfId.stringRef());
825 Reader.read(ToLoad);
826
827 unsigned MatchCount = 0;
828 SampleProfileMap NewlyLoadedProfiles;
829 for (auto &[BaseName, ProfId] : CandidateByBaseName) {
830 if (!isProfileUnused(ProfId))
831 continue;
832 Function *OrphanFunc = OrphansByBaseName.lookup(BaseName);
833 if (!OrphanFunc)
834 continue;
835
836 FuncToProfileNameMap[OrphanFunc] = ProfId;
837 if (const auto *FS = Reader.getSamplesFor(ProfId.stringRef()))
838 NewlyLoadedProfiles.create(FS->getFunction()).merge(*FS);
839 MatchCount++;
840 LLVM_DEBUG(dbgs() << "Direct basename match: " << OrphanFunc->getName()
841 << " (IR) -> " << ProfId << " (Profile)"
842 << " [basename: " << BaseName << "]\n");
843 }
844
845 // Flatten newly loaded profiles so inlined callees are available for
846 // subsequent LCS-based CG matching.
847 if (!NewlyLoadedProfiles.empty())
848 ProfileConverter::flattenProfile(NewlyLoadedProfiles, FlattenedProfiles,
850
851 NumDirectProfileMatch += MatchCount;
852 LLVM_DEBUG(dbgs() << "Direct basename matching found " << MatchCount
853 << " matches\n");
854}
855
856bool SampleProfileMatcher::functionMatchesProfileHelper(
857 const Function &IRFunc, const FunctionId &ProfFunc) {
858 // The value is in the range [0, 1]. The bigger the value is, the more similar
859 // two sequences are.
860 float Similarity = 0.0;
861
862 // Match the functions if they have the same base name(after demangling) and
863 // skip the similarity check.
864 ItaniumPartialDemangler Demangler;
865 auto IRBaseName = getDemangledBaseName(Demangler, IRFunc.getName());
866 auto ProfBaseName = getDemangledBaseName(Demangler, ProfFunc.stringRef());
867 if (!IRBaseName.empty() && IRBaseName == ProfBaseName) {
868 LLVM_DEBUG(dbgs() << "The functions " << IRFunc.getName() << "(IR) and "
869 << ProfFunc << "(Profile) share the same base name: "
870 << IRBaseName << ".\n");
871 return true;
872 }
873
874 const auto *FSForMatching = getFlattenedSamplesFor(ProfFunc);
875 // With extbinary profile format, initial profile loading only reads profile
876 // based on current function names in the module.
877 // However, if a function is renamed, sample loader skips to load its original
878 // profile(which has a different name), we will miss this case. To address
879 // this, we load the top-level profile candidate explicitly for the matching.
880 if (!FSForMatching && LoadFuncProfileforCGMatching) {
881 DenseSet<StringRef> TopLevelFunc({ProfFunc.stringRef()});
882 if (std::error_code EC = Reader.read(TopLevelFunc))
883 return false;
884 FSForMatching = Reader.getSamplesFor(ProfFunc.stringRef());
885 // Flatten the newly loaded profile so its inlined callees get their own
886 // entries in FlattenedProfiles, making them discoverable by subsequent
887 // CG matching steps.
888 if (FSForMatching) {
889 SampleProfileMap TempProfiles;
890 TempProfiles.create(FSForMatching->getFunction()).merge(*FSForMatching);
891 ProfileConverter::flattenProfile(TempProfiles, FlattenedProfiles,
893 FSForMatching = getFlattenedSamplesFor(ProfFunc);
894 }
895 LLVM_DEBUG({
896 if (FSForMatching)
897 dbgs() << "Read top-level function " << ProfFunc
898 << " for call-graph matching\n";
899 });
900 }
901 if (!FSForMatching)
902 return false;
903 // The check for similarity or checksum may not be reliable if the function is
904 // tiny, we use the number of basic block as a proxy for the function
905 // complexity and skip the matching if it's too small.
906 if (IRFunc.size() < MinFuncCountForCGMatching ||
907 FSForMatching->getBodySamples().size() < MinFuncCountForCGMatching)
908 return false;
909
910 // For probe-based function, we first trust the checksum info. If the checksum
911 // doesn't match, we continue checking for similarity.
913 const auto *FuncDesc = ProbeManager->getDesc(IRFunc);
914 if (FuncDesc &&
915 !ProbeManager->profileIsHashMismatched(*FuncDesc, *FSForMatching)) {
916 LLVM_DEBUG(dbgs() << "The checksums for " << IRFunc.getName()
917 << "(IR) and " << ProfFunc << "(Profile) match.\n");
918
919 return true;
920 }
921 }
922
923 AnchorMap IRAnchors;
924 findIRAnchors(IRFunc, IRAnchors);
925 AnchorMap ProfileAnchors;
926 findProfileAnchors(*FSForMatching, ProfileAnchors);
927
928 AnchorList FilteredIRAnchorsList;
929 AnchorList FilteredProfileAnchorList;
930 getFilteredAnchorList(IRAnchors, ProfileAnchors, FilteredIRAnchorsList,
931 FilteredProfileAnchorList);
932
933 // Similarly skip the matching if the num of anchors is not enough.
934 if (FilteredIRAnchorsList.size() < MinCallCountForCGMatching ||
935 FilteredProfileAnchorList.size() < MinCallCountForCGMatching)
936 return false;
937
938 // Use the diff algorithm to find the LCS between IR and profile.
939
940 // Don't recursively match the callee function to avoid infinite matching,
941 // callee functions will be handled later since it's processed in top-down
942 // order .
943 LocToLocMap MatchedAnchors =
944 longestCommonSequence(FilteredIRAnchorsList, FilteredProfileAnchorList,
945 false /* Match unused functions */);
946
947 Similarity = static_cast<float>(MatchedAnchors.size()) /
948 FilteredProfileAnchorList.size();
949
950 LLVM_DEBUG(dbgs() << "The similarity between " << IRFunc.getName()
951 << "(IR) and " << ProfFunc << "(profile) is "
952 << format("%.2f", Similarity) << "\n");
953 assert((Similarity >= 0 && Similarity <= 1.0) &&
954 "Similarity value should be in [0, 1]");
955 return Similarity * 100 > FuncProfileSimilarityThreshold;
956}
957
958// If FindMatchedProfileOnly is set to true, only use the processed function
959// results. This is used for skipping the repeated recursive matching.
960bool SampleProfileMatcher::functionMatchesProfile(Function &IRFunc,
961 const FunctionId &ProfFunc,
962 bool FindMatchedProfileOnly) {
963 auto R = FuncProfileMatchCache.find({&IRFunc, ProfFunc});
964 if (R != FuncProfileMatchCache.end())
965 return R->second;
966
967 if (FindMatchedProfileOnly)
968 return false;
969
970 bool Matched = functionMatchesProfileHelper(IRFunc, ProfFunc);
971 FuncProfileMatchCache[{&IRFunc, ProfFunc}] = Matched;
972 if (Matched) {
973 FuncToProfileNameMap[&IRFunc] = ProfFunc;
974 LLVM_DEBUG(dbgs() << "Function:" << IRFunc.getName()
975 << " matches profile:" << ProfFunc << "\n");
976 }
977
978 return Matched;
979}
980
981void SampleProfileMatcher::UpdateWithSalvagedProfiles() {
982 DenseSet<StringRef> ProfileSalvagedFuncs;
983 // Update FuncNameToProfNameMap and SymbolMap.
984 for (auto &I : FuncToProfileNameMap) {
985 assert(I.first && "New function is null");
986 FunctionId FuncName(I.first->getName());
987 ProfileSalvagedFuncs.insert(I.second.stringRef());
988 FuncNameToProfNameMap->emplace(FuncName, I.second);
989
990 // We need to remove the old entry to avoid duplicating the function
991 // processing.
992 SymbolMap->erase(FuncName);
993 SymbolMap->emplace(I.second, I.first);
994 }
995
996 // With extbinary profile format, initial profile loading only reads profile
997 // based on current function names in the module, so we need to load top-level
998 // profiles for functions with different profile name explicitly after
999 // function-profile name map is established with stale profile matching.
1000 Reader.read(ProfileSalvagedFuncs);
1001 Reader.setFuncNameToProfNameMap(*FuncNameToProfNameMap);
1002}
1003
1005 ProfileConverter::flattenProfile(Reader.getProfiles(), FlattenedProfiles,
1007 // Disable SalvageUnusedProfile if the module has an extremely large number of
1008 // functions to limit compile time.
1011
1013 findFunctionsWithoutProfile();
1014 matchFunctionsWithoutProfileByBasename();
1015 }
1016
1017 // Process the matching in top-down order so that the caller matching result
1018 // can be used to the callee matching.
1019 std::vector<Function *> TopDownFunctionList;
1020 TopDownFunctionList.reserve(M.size());
1021 buildTopDownFuncOrder(CG, TopDownFunctionList);
1022 for (auto *F : TopDownFunctionList) {
1024 continue;
1025 runOnFunction(*F);
1026 }
1027
1029 UpdateWithSalvagedProfiles();
1030
1032 distributeIRToProfileLocationMap();
1033
1034 computeAndReportProfileStaleness();
1035}
1036
1037void SampleProfileMatcher::distributeIRToProfileLocationMap(
1038 FunctionSamples &FS) {
1039 const auto ProfileMappings = FuncMappings.find(FS.getFuncName());
1040 if (ProfileMappings != FuncMappings.end()) {
1041 FS.setIRToProfileLocationMap(&(ProfileMappings->second));
1042 }
1043
1044 for (auto &Callees :
1045 const_cast<CallsiteSampleMap &>(FS.getCallsiteSamples())) {
1046 for (auto &FS : Callees.second) {
1047 distributeIRToProfileLocationMap(FS.second);
1048 }
1049 }
1050}
1051
1052// Use a central place to distribute the matching results. Outlined and inlined
1053// profile with the function name will be set to the same pointer.
1054void SampleProfileMatcher::distributeIRToProfileLocationMap() {
1055 for (auto &I : Reader.getProfiles()) {
1056 distributeIRToProfileLocationMap(I.second);
1057 }
1058}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define _
itanium_demangle::ManglingParser< DefaultAllocator > Demangler
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static std::string getDemangledBaseName(ItaniumPartialDemangler &Demangler, StringRef FName)
This file provides the interface for SampleProfileMatcher.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
size_t size() const
Definition Function.h:858
iterator end()
Definition Function.h:855
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
reference emplace_back(ArgTypes &&... Args)
bool empty() const
Definition StringMap.h:108
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:285
void erase(iterator I)
Definition StringMap.h:427
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:381
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
StringRef stringRef() const
Convert to StringRef.
Definition FunctionId.h:108
Representation of the samples collected for a function.
Definition SampleProf.h:783
static LLVM_ABI bool ProfileIsCS
static LLVM_ABI bool ProfileIsProbeBased
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
static LLVM_ABI bool UseMD5
Whether the profile uses MD5 to represent string.
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
mapped_type & create(const SampleContext &Ctx)
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition SampleProf.h:773
std::unordered_map< LineLocation, LineLocation, LineLocationHash > LocToLocMap
Definition SampleProf.h:775
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
cl::opt< bool > ReportProfileStaleness("report-profile-staleness", cl::Hidden, cl::init(false), cl::desc("Compute and report stale profile statistical metrics."))
cl::opt< bool > PersistProfileStaleness("persist-profile-staleness", cl::Hidden, cl::init(false), cl::desc("Compute stale profile statistical metrics and write it into the " "native object file(.llvm_stats section)."))
std::map< LineLocation, FunctionId > AnchorMap
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static cl::opt< bool > LoadFuncProfileforCGMatching("load-func-profile-for-cg-matching", cl::Hidden, cl::init(true), cl::desc("Load top-level profiles that the sample reader initially skipped for " "the call-graph matching (only meaningful for extended binary " "format)"))
static cl::opt< unsigned > SalvageUnusedProfileMaxFunctions("salvage-unused-profile-max-functions", cl::Hidden, cl::init(UINT_MAX), cl::desc("The maximum number of functions in a module, above which salvage " "unused profile will be skipped."))
static void buildTopDownFuncOrder(LazyCallGraph &CG, std::vector< Function * > &FunctionOrderList)
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:81
static cl::opt< unsigned > MinCallCountForCGMatching("min-call-count-for-cg-matching", cl::Hidden, cl::init(3), cl::desc("The minimum number of call anchors required for a function to " "run stale profile call graph matching."))
LLVM_ABI std::optional< PseudoProbe > extractProbe(const Instruction &Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
static cl::opt< unsigned > MinFuncCountForCGMatching("min-func-count-for-cg-matching", cl::Hidden, cl::init(5), cl::desc("The minimum number of basic blocks required for a function to " "run stale profile call graph matching."))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
cl::opt< bool > SalvageStaleProfile("salvage-stale-profile", cl::Hidden, cl::init(false), cl::desc("Salvage stale profile by fuzzy matching and use the remapped " "location for sample profile query."))
void longestCommonSequence(AnchorList AnchorList1, AnchorList AnchorList2, llvm::function_ref< bool(const Function &, const Function &)> FunctionMatchesProfile, llvm::function_ref< void(Loc, Loc)> InsertMatching)
std::vector< std::pair< LineLocation, FunctionId > > AnchorList
static bool skipProfileForFunction(const Function &F)
cl::opt< bool > SalvageUnusedProfile("salvage-unused-profile", cl::Hidden, cl::init(false), cl::desc("Salvage unused profile by matching with new " "functions on call graph."))
static cl::opt< unsigned > SalvageStaleProfileMaxCallsites("salvage-stale-profile-max-callsites", cl::Hidden, cl::init(UINT_MAX), cl::desc("The maximum number of callsites in a function, above which stale " "profile matching will be skipped."))
static cl::opt< unsigned > FuncProfileSimilarityThreshold("func-profile-similarity-threshold", cl::Hidden, cl::init(80), cl::desc("Consider a profile matches a function if the similarity of their " "callee sequences is above the specified percentile."))
"Partial" demangler.
Definition Demangle.h:85