LLVM 24.0.0git
SampleProfile.cpp
Go to the documentation of this file.
1//===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
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 SampleProfileLoader transformation. This pass
10// reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11// http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12// profile information in the given profile.
13//
14// This pass generates branch weight annotations on the IR:
15//
16// - prof: Represents branch weights. This annotation is added to branches
17// to indicate the weights of each edge coming out of the branch.
18// The weight of each edge is the weight of the target block for
19// that edge. The weight of a block B is computed as the maximum
20// number of samples found in B.
21//
22//===----------------------------------------------------------------------===//
23
25#include "IPOOptions.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/MapVector.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/Twine.h"
46#include "llvm/IR/BasicBlock.h"
47#include "llvm/IR/DebugLoc.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/MDBuilder.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/PassManager.h"
60#include "llvm/IR/PseudoProbe.h"
67#include "llvm/Support/Debug.h"
71#include "llvm/Transforms/IPO.h"
82#include <algorithm>
83#include <cassert>
84#include <cstdint>
85#include <functional>
86#include <limits>
87#include <memory>
88#include <queue>
89#include <string>
90#include <system_error>
91#include <utility>
92#include <vector>
93
94using namespace llvm;
95using namespace sampleprof;
96using namespace llvm::sampleprofutil;
97#define DEBUG_TYPE "sample-profile"
98#define CSINLINE_DEBUG DEBUG_TYPE "-inline"
99
100STATISTIC(NumCSInlined,
101 "Number of functions inlined with context sensitive profile");
102STATISTIC(NumCSNotInlined,
103 "Number of functions not inlined with context sensitive profile");
104STATISTIC(NumMismatchedProfile,
105 "Number of functions with CFG mismatched profile");
106STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
107STATISTIC(NumDuplicatedInlinesite,
108 "Number of inlined callsites with a partial distribution factor");
109
110STATISTIC(NumCSInlinedHitMinLimit,
111 "Number of functions with FDO inline stopped due to min size limit");
112STATISTIC(NumCSInlinedHitMaxLimit,
113 "Number of functions with FDO inline stopped due to max size limit");
115 NumCSInlinedHitGrowthLimit,
116 "Number of functions with FDO inline stopped due to growth size limit");
117
118namespace llvm {
120}
121
122namespace {
123
124using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
125using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
126using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
127using BlockEdgeMap =
129
130class GUIDToFuncNameMapper {
131public:
132 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
133 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
134 : CurrentReader(Reader), CurrentModule(M),
135 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
136 if (!CurrentReader.useMD5())
137 return;
138
139 for (const auto &F : CurrentModule) {
140 StringRef OrigName = F.getName();
141 CurrentGUIDToFuncNameMap.insert(
142 {Function::getGUIDAssumingExternalLinkage(OrigName), OrigName});
143
144 // Local to global var promotion used by optimization like thinlto
145 // will rename the var and add suffix like ".llvm.xxx" to the
146 // original local name. In sample profile, the suffixes of function
147 // names are all stripped. Since it is possible that the mapper is
148 // built in post-thin-link phase and var promotion has been done,
149 // we need to add the substring of function name without the suffix
150 // into the GUIDToFuncNameMap.
152 if (CanonName != OrigName)
153 CurrentGUIDToFuncNameMap.insert(
154 {Function::getGUIDAssumingExternalLinkage(CanonName), CanonName});
155 }
156
157 // Update GUIDToFuncNameMap for each function including inlinees.
158 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
159 }
160
161 ~GUIDToFuncNameMapper() {
162 if (!CurrentReader.useMD5())
163 return;
164
165 CurrentGUIDToFuncNameMap.clear();
166
167 // Reset GUIDToFuncNameMap for of each function as they're no
168 // longer valid at this point.
169 SetGUIDToFuncNameMapForAll(nullptr);
170 }
171
172private:
173 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
174 std::queue<FunctionSamples *> FSToUpdate;
175 for (auto &IFS : CurrentReader.getProfiles()) {
176 FSToUpdate.push(&IFS.second);
177 }
178
179 while (!FSToUpdate.empty()) {
180 FunctionSamples *FS = FSToUpdate.front();
181 FSToUpdate.pop();
182 FS->GUIDToFuncNameMap = Map;
183 for (const auto &ICS : FS->getCallsiteSamples()) {
184 const FunctionSamplesMap &FSMap = ICS.second;
185 for (const auto &IFS : FSMap) {
186 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
187 FSToUpdate.push(&FS);
188 }
189 }
190 }
191 }
192
194 Module &CurrentModule;
195 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
196};
197
198// Inline candidate used by iterative callsite prioritized inliner
199struct InlineCandidate {
200 CallBase *CallInstr;
201 const FunctionSamples *CalleeSamples;
202 // Prorated callsite count, which will be used to guide inlining. For example,
203 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
204 // copies will get their own distribution factors and their prorated counts
205 // will be used to decide if they should be inlined independently.
206 uint64_t CallsiteCount;
207 // Call site distribution factor to prorate the profile samples for a
208 // duplicated callsite. Default value is 1.0.
209 float CallsiteDistribution;
210};
211
212// Inline candidate comparer using call site weight
213struct CandidateComparer {
214 bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
215 if (LHS.CallsiteCount != RHS.CallsiteCount)
216 return LHS.CallsiteCount < RHS.CallsiteCount;
217
218 const FunctionSamples *LCS = LHS.CalleeSamples;
219 const FunctionSamples *RCS = RHS.CalleeSamples;
220 // In inline replay mode, CalleeSamples may be null and the order doesn't
221 // matter.
222 if (!LCS || !RCS)
223 return LCS;
224
225 // Tie breaker using number of samples try to favor smaller functions first
226 if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
227 return LCS->getBodySamples().size() > RCS->getBodySamples().size();
228
229 // Tie breaker using GUID so we have stable/deterministic inlining order
230 return LCS->getGUID() < RCS->getGUID();
231 }
232};
233
234using CandidateQueue =
236 CandidateComparer>;
237
238/// Sample profile pass.
239///
240/// This pass reads profile data from the file specified by
241/// -sample-profile-file and annotates every affected function with the
242/// profile information found in that file.
243class SampleProfileLoader final : public SampleProfileLoaderBaseImpl<Function> {
244public:
245 SampleProfileLoader(
246 const IPOOptions &Opts, StringRef Name, StringRef RemapName,
247 ThinOrFullLTOPhase LTOPhase, IntrusiveRefCntPtr<vfs::FileSystem> FS,
248 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
249 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
250 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
251 LazyCallGraph &CG, bool DisableSampleProfileInlining,
252 bool UseFlattenedProfile)
253 : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName),
254 std::move(FS)),
255 Opts(Opts), ProfileMergeInlinee(Opts.sample_profile_merge_inlinee),
256 ProfileSizeInline(valueOr(Opts.sample_profile_inline_size, false)),
257 CallsitePrioritizedInline(
258 valueOr(Opts.sample_profile_prioritized_inline, false)),
259 AllowRecursiveInline(
260 valueOr(Opts.sample_profile_recursive_inline, false)),
261 UsePreInlinerDecision(
262 valueOr(Opts.sample_profile_use_preinliner, false)),
263 SalvageStaleProfile(valueOr(Opts.salvage_stale_profile, false)),
264 SalvageUnusedProfile(valueOr(Opts.salvage_unused_profile, false)),
265 GetAC(std::move(GetAssumptionCache)),
266 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
267 CG(CG), LTOPhase(LTOPhase),
268 AnnotatedPassName(Opts.annotate_sample_profile_inline_phase
269 ? llvm::AnnotateInlinePassName(InlineContext{
272 DisableSampleProfileInlining(DisableSampleProfileInlining),
273 UseFlattenedProfile(UseFlattenedProfile) {}
274
275 bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
276 bool runOnModule(Module &M, ModuleAnalysisManager &AM,
277 ProfileSummaryInfo *_PSI);
278
279protected:
280 const IPOOptions &Opts;
281 // Options the loader adjusts according to the profile.
282 bool ProfileMergeInlinee;
283 bool ProfileSizeInline;
284 bool CallsitePrioritizedInline;
285 bool AllowRecursiveInline;
286 bool UsePreInlinerDecision;
287 bool SalvageStaleProfile;
288 bool SalvageUnusedProfile;
289 SampleProfileInlineOptions InlineOpts;
290
292 bool emitAnnotations(Function &F);
293 ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
294 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
295 const FunctionSamples *
296 findFunctionSamples(const Instruction &I) const override;
297 std::vector<const FunctionSamples *>
298 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
299 void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
300 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
301 uint64_t Threshold);
302 // Attempt to promote indirect call and also inline the promoted call
303 bool tryPromoteAndInlineCandidate(
304 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
305 uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
306
307 bool inlineHotFunctions(Function &F,
308 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
309 std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
310 bool getExternalInlineAdvisorShouldInline(CallBase &CB);
311 InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
312 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
313 bool
314 tryInlineCandidate(InlineCandidate &Candidate,
315 SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
316 bool
317 inlineHotFunctionsWithPriority(Function &F,
318 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
319 // Inline cold/small functions in addition to hot ones
320 bool shouldInlineColdCallee(CallBase &CallInst);
321 void emitOptimizationRemarksForInlineCandidates(
322 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
323 bool Hot);
324 void promoteMergeNotInlinedContextSamples(
325 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
326 const Function &F);
327 std::vector<Function *> buildFunctionOrder(Module &M, LazyCallGraph &CG);
328 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(Module &M);
329 void generateMDProfMetadata(Function &F);
330 bool rejectHighStalenessProfile(Module &M, ProfileSummaryInfo *PSI,
331 const SampleProfileMap &Profiles);
332 void removePseudoProbeInstsDiscriminator(Module &M);
333
334 /// Map from function name to Function *. Used to find the function from
335 /// the function name. If the function name contains suffix, additional
336 /// entry is added to map from the stripped name to the function if there
337 /// is one-to-one mapping.
338 HashKeyMap<DenseMap, FunctionId, Function *> SymbolMap;
339
340 /// Map from function name to profile name generated by call-graph based
341 /// profile fuzzy matching(--salvage-unused-profile).
342 HashKeyMap<DenseMap, FunctionId, FunctionId> FuncNameToProfNameMap;
343
344 std::function<AssumptionCache &(Function &)> GetAC;
345 std::function<TargetTransformInfo &(Function &)> GetTTI;
346 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
347 LazyCallGraph &CG;
348
349 /// Profile tracker for different context.
350 std::unique_ptr<SampleContextTracker> ContextTracker;
351
352 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
353 ///
354 /// We need to know the LTO phase because for example in ThinLTOPrelink
355 /// phase, in annotation, we should not promote indirect calls. Instead,
356 /// we will mark GUIDs that needs to be annotated to the function.
357 const ThinOrFullLTOPhase LTOPhase;
358 const std::string AnnotatedPassName;
359
360 /// Profle Symbol list tells whether a function name appears in the binary
361 /// used to generate the current profile.
362 std::shared_ptr<ProfileSymbolList> PSL;
363
364 // Information recorded when we declined to inline a call site
365 // because we have determined it is too cold is accumulated for
366 // each callee function. Initially this is just the entry count.
367 struct NotInlinedProfileInfo {
368 uint64_t entryCount;
369 };
370 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
371
372 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
373 // all the function symbols defined or declared in current module.
374 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
375
376 // For symbol in profile symbol list, whether to regard their profiles
377 // to be accurate. It is mainly decided by existance of profile symbol
378 // list and -profile-accurate-for-symsinlist flag, but it can be
379 // overriden by -profile-sample-accurate or profile-sample-accurate
380 // attribute.
381 bool ProfAccForSymsInList;
382
383 bool DisableSampleProfileInlining;
384
385 bool UseFlattenedProfile;
386
387 // External inline advisor used to replay inline decision from remarks.
388 std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
389
390 // A helper to implement the sample profile matching algorithm.
391 std::unique_ptr<SampleProfileMatcher> MatchingManager;
392
393private:
394 const char *getAnnotatedRemarkPassName() const {
395 return AnnotatedPassName.c_str();
396 }
397};
398} // end anonymous namespace
399
400namespace llvm {
401template <>
402inline bool SampleProfileInference<Function>::isExit(const BasicBlock *BB) {
403 return succ_empty(BB);
404}
405
406template <>
407inline void SampleProfileInference<Function>::findUnlikelyJumps(
408 const std::vector<const BasicBlockT *> &BasicBlocks,
409 BlockEdgeMap &Successors, FlowFunction &Func) {
410 for (auto &Jump : Func.Jumps) {
411 const auto *BB = BasicBlocks[Jump.Source];
412 const auto *Succ = BasicBlocks[Jump.Target];
413 const Instruction *TI = BB->getTerminator();
414 // Check if a block ends with InvokeInst and mark non-taken branch unlikely.
415 // In that case block Succ should be a landing pad
416 const auto &Succs = Successors[BB];
417 if (Succs.size() == 2 && Succs.back() == Succ) {
418 if (isa<InvokeInst>(TI)) {
419 Jump.IsUnlikely = true;
420 }
421 }
422 const Instruction *SuccTI = Succ->getTerminator();
423 // Check if the target block contains UnreachableInst and mark it unlikely
424 if (SuccTI->getNumSuccessors() == 0) {
425 if (isa<UnreachableInst>(SuccTI)) {
426 Jump.IsUnlikely = true;
427 }
428 }
429 }
430}
431
432template <>
434 Function &F) {
435 DT.reset(new DominatorTree);
436 DT->recalculate(F);
437
438 PDT.reset(new PostDominatorTree(F));
439
440 LI.reset(new LoopInfo);
441 LI->analyze(*DT);
442}
443} // namespace llvm
444
445ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
447 return getProbeWeight(Inst);
448
449 const DebugLoc &DLoc = Inst.getDebugLoc();
450 if (!DLoc)
451 return std::error_code();
452
453 // Ignore all intrinsics, phinodes and branch instructions.
454 // Branch and phinodes instruction usually contains debug info from sources
455 // outside of the residing basic block, thus we ignore them during annotation.
457 return std::error_code();
458
459 // For non-CS profile, if a direct call/invoke instruction is inlined in
460 // profile (findCalleeFunctionSamples returns non-empty result), but not
461 // inlined here, it means that the inlined callsite has no sample, thus the
462 // call instruction should have 0 count.
463 // For CS profile, the callsite count of previously inlined callees is
464 // populated with the entry count of the callees.
466 if (const auto *CB = dyn_cast<CallBase>(&Inst))
467 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
468 return 0;
469
470 return getInstWeightImpl(Inst);
471}
472
473/// Get the FunctionSamples for a call instruction.
474///
475/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
476/// instance in which that call instruction is calling to. It contains
477/// all samples that resides in the inlined instance. We first find the
478/// inlined instance in which the call instruction is from, then we
479/// traverse its children to find the callsite with the matching
480/// location.
481///
482/// \param Inst Call/Invoke instruction to query.
483///
484/// \returns The FunctionSamples pointer to the inlined instance.
485const FunctionSamples *
486SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
487 const DILocation *DIL = Inst.getDebugLoc();
488 if (!DIL) {
489 return nullptr;
490 }
491
492 StringRef CalleeName;
493 if (Function *Callee = Inst.getCalledFunction())
494 CalleeName = Callee->getName();
495
497 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
498
499 const FunctionSamples *FS = findFunctionSamples(Inst);
500 if (FS == nullptr)
501 return nullptr;
502
503 return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
504 CalleeName, Reader->getRemapper(),
505 &FuncNameToProfNameMap);
506}
507
508/// Returns a vector of FunctionSamples that are the indirect call targets
509/// of \p Inst. The vector is sorted by the total number of samples. Stores
510/// the total call count of the indirect call in \p Sum.
511std::vector<const FunctionSamples *>
512SampleProfileLoader::findIndirectCallFunctionSamples(
513 const Instruction &Inst, uint64_t &Sum) const {
514 const DILocation *DIL = Inst.getDebugLoc();
515 std::vector<const FunctionSamples *> R;
516
517 if (!DIL) {
518 return R;
519 }
520
521 auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
522 assert(L && R && "Expect non-null FunctionSamples");
523 if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
524 return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
525 return L->getGUID() < R->getGUID();
526 };
527
529 auto CalleeSamples =
530 ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
531 if (CalleeSamples.empty())
532 return R;
533
534 // For CSSPGO, we only use target context profile's entry count
535 // as that already includes both inlined callee and non-inlined ones..
536 Sum = 0;
537 for (const auto *const FS : CalleeSamples) {
538 Sum += FS->getHeadSamplesEstimate();
539 R.push_back(FS);
540 }
541 llvm::sort(R, FSCompare);
542 return R;
543 }
544
545 const FunctionSamples *FS = findFunctionSamples(Inst);
546 if (FS == nullptr)
547 return R;
548
550 Sum = 0;
551 if (auto T = FS->findCallTargetMapAt(CallSite))
552 for (const auto &T_C : *T)
553 Sum += T_C.second;
554 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
555 if (M->empty())
556 return R;
557 for (const auto &NameFS : *M) {
558 Sum += NameFS.second.getHeadSamplesEstimate();
559 R.push_back(&NameFS.second);
560 }
561 llvm::sort(R, FSCompare);
562 }
563 return R;
564}
565
566const FunctionSamples *
567SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
569 std::optional<PseudoProbe> Probe = extractProbe(Inst);
570 if (!Probe)
571 return nullptr;
572 }
573
574 const DILocation *DIL = Inst.getDebugLoc();
575 if (!DIL)
576 return Samples;
577
578 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
579 if (it.second) {
581 it.first->second = ContextTracker->getContextSamplesFor(DIL);
582 else
583 it.first->second = Samples->findFunctionSamples(
584 DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
585 }
586 return it.first->second;
587}
588
589/// Check whether the indirect call promotion history of \p Inst allows
590/// the promotion for \p Candidate.
591/// If the profile count for the promotion candidate \p Candidate is
592/// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
593/// for \p Inst. If we already have at least MaxNumPromotions
594/// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
595/// cannot promote for \p Inst anymore.
596static bool doesHistoryAllowICP(const IPOOptions &Opts, const Instruction &Inst,
597 StringRef Candidate) {
598 uint64_t TotalCount = 0;
599 auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
600 Opts.sample_profile_icp_max_prom,
601 TotalCount, true);
602 // No valid value profile so no promoted targets have been recorded
603 // before. Ok to do ICP.
604 if (ValueData.empty())
605 return true;
606
607 unsigned NumPromoted = 0;
608 for (const auto &V : ValueData) {
609 if (V.Count != NOMORE_ICP_MAGICNUM)
610 continue;
611
612 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
613 // metadata, it means the candidate has been promoted for this
614 // indirect call.
615 if (V.Value == Function::getGUIDAssumingExternalLinkage(Candidate))
616 return false;
617 NumPromoted++;
618 // If already have MaxNumPromotions promotion, don't do it anymore.
619 if (NumPromoted == Opts.sample_profile_icp_max_prom)
620 return false;
621 }
622 return true;
623}
624
625/// Update indirect call target profile metadata for \p Inst.
626/// Usually \p Sum is the sum of counts of all the targets for \p Inst.
627/// If it is 0, it means updateIDTMetaData is used to mark a
628/// certain target to be promoted already. If it is not zero,
629/// we expect to use it to update the total count in the value profile.
630static void
631updateIDTMetaData(const IPOOptions &Opts, Instruction &Inst,
632 const SmallVectorImpl<InstrProfValueData> &CallTargets,
633 uint64_t Sum) {
634 // Bail out early if MaxNumPromotions is zero.
635 // This prevents allocating an array of zero length below.
636 //
637 // Note `updateIDTMetaData` is called in two places so check
638 // `MaxNumPromotions` inside it.
639 if (Opts.sample_profile_icp_max_prom == 0)
640 return;
641 // OldSum is the existing total count in the value profile data.
642 uint64_t OldSum = 0;
643 auto ValueData =
644 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
645 Opts.sample_profile_icp_max_prom, OldSum, true);
646
647 DenseMap<uint64_t, uint64_t> ValueCountMap;
648 if (Sum == 0) {
649 assert((CallTargets.size() == 1 &&
650 CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
651 "If sum is 0, assume only one element in CallTargets "
652 "with count being NOMORE_ICP_MAGICNUM");
653 // Initialize ValueCountMap with existing value profile data.
654 for (const auto &V : ValueData)
655 ValueCountMap[V.Value] = V.Count;
656 auto Pair =
657 ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
658 // If the target already exists in value profile, decrease the total
659 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
660 if (!Pair.second) {
661 OldSum -= Pair.first->second;
662 Pair.first->second = NOMORE_ICP_MAGICNUM;
663 }
664 Sum = OldSum;
665 } else {
666 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
667 // counts in the value profile.
668 for (const auto &V : ValueData) {
669 if (V.Count == NOMORE_ICP_MAGICNUM)
670 ValueCountMap[V.Value] = V.Count;
671 }
672
673 for (const auto &Data : CallTargets) {
674 auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
675 if (Pair.second)
676 continue;
677 // The target represented by Data.Value has already been promoted.
678 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
679 // Sum by Data.Count.
680 assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
681 Sum -= Data.Count;
682 }
683 }
684
686 for (const auto &ValueCount : ValueCountMap) {
687 NewCallTargets.emplace_back(
688 InstrProfValueData{ValueCount.first, ValueCount.second});
689 }
690
691 llvm::sort(NewCallTargets,
692 [](const InstrProfValueData &L, const InstrProfValueData &R) {
693 return std::tie(L.Count, L.Value) > std::tie(R.Count, R.Value);
694 });
695
696 uint32_t MaxMDCount =
697 std::min(NewCallTargets.size(),
698 static_cast<size_t>(Opts.sample_profile_icp_max_prom));
699 annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
700 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
701}
702
703/// Attempt to promote indirect call and also inline the promoted call.
704///
705/// \param F Caller function.
706/// \param Candidate ICP and inline candidate.
707/// \param SumOrigin Original sum of target counts for indirect call before
708/// promoting given candidate.
709/// \param Sum Prorated sum of remaining target counts for indirect call
710/// after promoting given candidate.
711/// \param InlinedCallSite Output vector for new call sites exposed after
712/// inlining.
713bool SampleProfileLoader::tryPromoteAndInlineCandidate(
714 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
715 SmallVector<CallBase *, 8> *InlinedCallSite) {
716 // Bail out early if sample-loader inliner is disabled.
717 if (DisableSampleProfileInlining)
718 return false;
719
720 // Bail out early if MaxNumPromotions is zero.
721 // This prevents allocating an array of zero length in callees below.
722 if (Opts.sample_profile_icp_max_prom == 0)
723 return false;
724 auto CalleeFunctionName = Candidate.CalleeSamples->getFunction();
725 auto R = SymbolMap.find(CalleeFunctionName);
726 if (R == SymbolMap.end() || !R->second)
727 return false;
728
729 auto &CI = *Candidate.CallInstr;
730 if (!doesHistoryAllowICP(Opts, CI, R->second->getName()))
731 return false;
732
733 const char *Reason = "Callee function not available";
734 // R->getValue() != &F is to prevent promoting a recursive call.
735 // If it is a recursive call, we do not inline it as it could bloat
736 // the code exponentially. There is way to better handle this, e.g.
737 // clone the caller first, and inline the cloned caller if it is
738 // recursive. As llvm does not inline recursive calls, we will
739 // simply ignore it instead of handling it explicitly.
740 if (!R->second->isDeclaration() && R->second->getSubprogram() &&
741 R->second->hasFnAttribute("use-sample-profile") &&
742 R->second != &F && isLegalToPromote(CI, R->second, &Reason)) {
743 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
744 // in the value profile metadata so the target won't be promoted again.
745 SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
746 Function::getGUIDAssumingExternalLinkage(R->second->getName()),
748 updateIDTMetaData(Opts, CI, SortedCallTargets, 0);
749
750 auto *DI = &pgo::promoteIndirectCall(
751 CI, R->second, Candidate.CallsiteCount, Sum, false, ORE);
752 if (DI) {
753 Sum -= Candidate.CallsiteCount;
754 // Do not prorate the indirect callsite distribution since the original
755 // distribution will be used to scale down non-promoted profile target
756 // counts later. By doing this we lose track of the real callsite count
757 // for the leftover indirect callsite as a trade off for accurate call
758 // target counts.
759 // TODO: Ideally we would have two separate factors, one for call site
760 // counts and one is used to prorate call target counts.
761 // Do not update the promoted direct callsite distribution at this
762 // point since the original distribution combined with the callee profile
763 // will be used to prorate callsites from the callee if inlined. Once not
764 // inlined, the direct callsite distribution should be prorated so that
765 // the it will reflect the real callsite counts.
766 Candidate.CallInstr = DI;
767 if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
768 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
769 if (!Inlined) {
770 // Prorate the direct callsite distribution so that it reflects real
771 // callsite counts.
773 *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
774 }
775 return Inlined;
776 }
777 }
778 } else {
779 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
781 Candidate.CallInstr->getName())<< " because "
782 << Reason << "\n");
783 }
784 return false;
785}
786
787bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
788 if (!ProfileSizeInline)
789 return false;
790
791 if (CallInst.getCalledFunction() == nullptr)
792 return false;
793
794 InlineCost Cost =
795 getInlineCost(CallInst, getInlineParams(CallInst.getContext()),
796 GetTTI(*CallInst.getCaller()), GetAC, GetTLI);
797
798 if (Cost.isNever())
799 return false;
800
801 if (Cost.isAlways())
802 return true;
803
804 return Cost.getCost() <= InlineOpts.ColdCallSiteThreshold;
805}
806
807void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
808 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
809 bool Hot) {
810 for (auto *I : Candidates) {
811 Function *CalledFunction = I->getCalledFunction();
812 if (CalledFunction) {
813 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
814 "InlineAttempt", I->getDebugLoc(),
815 I->getParent())
816 << "previous inlining reattempted for "
817 << (Hot ? "hotness: '" : "size: '")
818 << ore::NV("Callee", CalledFunction) << "' into '"
819 << ore::NV("Caller", &F) << "'");
820 }
821 }
822}
823
824void SampleProfileLoader::findExternalInlineCandidate(
825 CallBase *CB, const FunctionSamples *Samples,
826 DenseSet<GlobalValue::GUID> &InlinedGUIDs, uint64_t Threshold) {
827 // Normally only functions defined outside this module need import hints.
828 // The targets of a deferred indirect call are an exception: another module
829 // that imports the caller must import them too, and no direct call to them
830 // may survive to create a summary edge.
831 bool IncludeLocalTargets = Opts.sample_profile_preserve_deferred_inlines &&
832 CB && CB->isIndirectCall();
833
834 // If ExternalInlineAdvisor(ReplayInlineAdvisor) wants to inline an external
835 // function make sure it's imported
836 if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
837 // Samples may not exist for replayed function, if so
838 // just add the direct GUID and move on
839 if (!Samples) {
840 InlinedGUIDs.insert(Function::getGUIDAssumingExternalLinkage(
841 CB->getCalledFunction()->getName()));
842 return;
843 }
844 // Otherwise, drop the threshold to import everything that we can
845 Threshold = 0;
846 }
847
848 // In some rare cases, call instruction could be changed after being pushed
849 // into inline candidate queue, this is because earlier inlining may expose
850 // constant propagation which can change indirect call to direct call. When
851 // this happens, we may fail to find matching function samples for the
852 // candidate later, even if a match was found when the candidate was enqueued.
853 if (!Samples)
854 return;
855
856 // For AutoFDO profile, retrieve candidate profiles by walking over
857 // the nested inlinee profiles.
859 // Set threshold to zero to honor pre-inliner decision.
860 if (UsePreInlinerDecision)
861 Threshold = 0;
862 Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold,
863 IncludeLocalTargets);
864 return;
865 }
866
867 ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
868 std::queue<ContextTrieNode *> CalleeList;
869 CalleeList.push(Caller);
870 while (!CalleeList.empty()) {
871 ContextTrieNode *Node = CalleeList.front();
872 CalleeList.pop();
873 FunctionSamples *CalleeSample = Node->getFunctionSamples();
874 // For CSSPGO profile, retrieve candidate profile by walking over the
875 // trie built for context profile. Note that also take call targets
876 // even if callee doesn't have a corresponding context profile.
877 if (!CalleeSample)
878 continue;
879
880 // If pre-inliner decision is used, honor that for importing as well.
881 bool PreInline =
882 UsePreInlinerDecision &&
884 if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
885 continue;
886
887 // A pre-inlined context can have no samples. Unlike an external one, a
888 // local definition is then not worth importing into other modules.
890 InlinedGUIDs, SymbolMap, CalleeSample->getFunction(),
891 IncludeLocalTargets && CalleeSample->getTotalSamples());
892
893 // Import hot CallTargets, which may not be available in IR because full
894 // profile annotation cannot be done until backend compilation in ThinLTO.
895 for (const auto &BS : CalleeSample->getBodySamples())
896 for (const auto &TS : BS.second.getCallTargets())
897 if (TS.second > Threshold)
898 FunctionSamples::addImportGUID(InlinedGUIDs, SymbolMap, TS.first,
899 IncludeLocalTargets);
900
901 // Import hot child context profile associted with callees. Note that this
902 // may have some overlap with the call target loop above, but doing this
903 // based child context profile again effectively allow us to use the max of
904 // entry count and call target count to determine importing.
905 for (auto &Child : Node->getAllChildContext()) {
906 ContextTrieNode *CalleeNode = &Child.second;
907 CalleeList.push(CalleeNode);
908 }
909 }
910}
911
912/// Iteratively inline hot callsites of a function.
913///
914/// Iteratively traverse all callsites of the function \p F, so as to
915/// find out callsites with corresponding inline instances.
916///
917/// For such callsites,
918/// - If it is hot enough, inline the callsites and adds callsites of the callee
919/// into the caller. If the call is an indirect call, first promote
920/// it to direct call. Each indirect call is limited with a single target.
921///
922/// - If a callsite is not inlined, merge the its profile to the outline
923/// version (if --sample-profile-merge-inlinee is true), or scale the
924/// counters of standalone function based on the profile of inlined
925/// instances (if --sample-profile-merge-inlinee is false).
926///
927/// Later passes may consume the updated profiles.
928///
929/// \param F function to perform iterative inlining.
930/// \param InlinedGUIDs a set to be updated to include all GUIDs that are
931/// inlined in the profiled binary.
932///
933/// \returns True if there is any inline happened.
934bool SampleProfileLoader::inlineHotFunctions(
935 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
936 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
937 // Profile symbol list is ignored when profile-sample-accurate is on.
938 assert((!ProfAccForSymsInList ||
939 (!Opts.profile_sample_accurate &&
940 !F.hasFnAttribute("profile-sample-accurate"))) &&
941 "ProfAccForSymsInList should be false when profile-sample-accurate "
942 "is enabled");
943
944 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
945 bool Changed = false;
946 bool LocalChanged = true;
947 while (LocalChanged) {
948 LocalChanged = false;
950 for (auto &BB : F) {
951 bool Hot = false;
952 SmallVector<CallBase *, 10> AllCandidates;
953 SmallVector<CallBase *, 10> ColdCandidates;
954 for (auto &I : BB) {
955 const FunctionSamples *FS = nullptr;
956 if (auto *CB = dyn_cast<CallBase>(&I)) {
957 if (!isa<IntrinsicInst>(I)) {
958 if ((FS = findCalleeFunctionSamples(*CB))) {
959 assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
960 "GUIDToFuncNameMap has to be populated");
961 AllCandidates.push_back(CB);
962 if (FS->getHeadSamplesEstimate() > 0 ||
964 LocalNotInlinedCallSites.insert({CB, FS});
965 if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
966 Hot = true;
967 else if (shouldInlineColdCallee(*CB))
968 ColdCandidates.push_back(CB);
969 } else if (getExternalInlineAdvisorShouldInline(*CB)) {
970 AllCandidates.push_back(CB);
971 }
972 }
973 }
974 }
975 if (Hot || ExternalInlineAdvisor) {
976 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
977 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
978 } else {
979 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
980 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
981 }
982 }
983 for (CallBase *I : CIS) {
984 Function *CalledFunction = I->getCalledFunction();
985 InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
986 0 /* dummy count */,
987 1.0 /* dummy distribution factor */};
988 // Do not inline recursive calls.
989 if (CalledFunction == &F)
990 continue;
991 if (I->isIndirectCall()) {
992 uint64_t Sum;
993 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
994 uint64_t SumOrigin = Sum;
995 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
996 findExternalInlineCandidate(I, FS, InlinedGUIDs,
997 PSI->getOrCompHotCountThreshold());
998 continue;
999 }
1000 if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1001 continue;
1002
1003 Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
1004 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1005 LocalNotInlinedCallSites.erase(I);
1006 LocalChanged = true;
1007 }
1008 }
1009 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1010 !CalledFunction->isDeclaration()) {
1011 if (tryInlineCandidate(Candidate)) {
1012 LocalNotInlinedCallSites.erase(I);
1013 LocalChanged = true;
1014 }
1015 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1016 findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1017 InlinedGUIDs,
1018 PSI->getOrCompHotCountThreshold());
1019 }
1020 }
1021 Changed |= LocalChanged;
1022 }
1023
1024 // For CS profile, profile for not inlined context will be merged when
1025 // base profile is being retrieved.
1027 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1028 return Changed;
1029}
1030
1031bool SampleProfileLoader::tryInlineCandidate(
1032 InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1033 // Do not attempt to inline a candidate if
1034 // --disable-sample-loader-inlining is true.
1035 if (DisableSampleProfileInlining)
1036 return false;
1037
1038 CallBase &CB = *Candidate.CallInstr;
1039 Function *CalledFunction = CB.getCalledFunction();
1040 assert(CalledFunction && "Expect a callee with definition");
1041 DebugLoc DLoc = CB.getDebugLoc();
1042 BasicBlock *BB = CB.getParent();
1043
1044 InlineCost Cost = shouldInlineCandidate(Candidate);
1045 if (Cost.isNever()) {
1046 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1047 "InlineFail", DLoc, BB)
1048 << "incompatible inlining");
1049 return false;
1050 }
1051
1052 if (!Cost)
1053 return false;
1054
1055 InlineFunctionInfo IFI(GetAC);
1056 IFI.UpdateProfile = false;
1057 InlineResult IR = InlineFunction(CB, IFI,
1058 /*MergeAttributes=*/true);
1059 if (!IR.isSuccess())
1060 return false;
1061
1062 // The call to InlineFunction erases I, so we can't pass it here.
1063 emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
1064 Cost, true, getAnnotatedRemarkPassName());
1065
1066 // Now populate the list of newly exposed call sites.
1067 if (InlinedCallSites) {
1068 InlinedCallSites->clear();
1069 llvm::append_range(*InlinedCallSites, IFI.InlinedCallSites);
1070 }
1071
1073 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1074 ++NumCSInlined;
1075
1076 // Prorate inlined probes for a duplicated inlining callsite which probably
1077 // has a distribution less than 100%. Samples for an inlinee should be
1078 // distributed among the copies of the original callsite based on each
1079 // callsite's distribution factor for counts accuracy. Note that an inlined
1080 // probe may come with its own distribution factor if it has been duplicated
1081 // in the inlinee body. The two factor are multiplied to reflect the
1082 // aggregation of duplication.
1083 if (Candidate.CallsiteDistribution < 1) {
1084 for (auto &I : IFI.InlinedCallSites) {
1085 if (std::optional<PseudoProbe> Probe = extractProbe(*I))
1086 setProbeDistributionFactor(*I, Probe->Factor *
1087 Candidate.CallsiteDistribution);
1088 }
1089 NumDuplicatedInlinesite++;
1090 }
1091
1092 return true;
1093}
1094
1095bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1096 CallBase *CB) {
1097 assert(CB && "Expect non-null call instruction");
1098
1099 if (isa<IntrinsicInst>(CB))
1100 return false;
1101
1102 // Find the callee's profile. For indirect call, find hottest target profile.
1103 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1104 // If ExternalInlineAdvisor wants to inline this site, do so even
1105 // if Samples are not present.
1106 if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1107 return false;
1108
1109 float Factor = 1.0;
1110 if (std::optional<PseudoProbe> Probe = extractProbe(*CB))
1111 Factor = Probe->Factor;
1112
1113 uint64_t CallsiteCount =
1114 CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
1115 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1116 return true;
1117}
1118
1119std::optional<InlineCost>
1120SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1121 std::unique_ptr<InlineAdvice> Advice = nullptr;
1122 if (ExternalInlineAdvisor) {
1123 Advice = ExternalInlineAdvisor->getAdvice(CB);
1124 if (Advice) {
1125 if (!Advice->isInliningRecommended()) {
1126 Advice->recordUnattemptedInlining();
1127 return InlineCost::getNever("not previously inlined");
1128 }
1129 Advice->recordInlining();
1130 return InlineCost::getAlways("previously inlined");
1131 }
1132 }
1133
1134 return {};
1135}
1136
1137bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1138 std::optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1139 return Cost ? !!*Cost : false;
1140}
1141
1142InlineCost
1143SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1144 if (std::optional<InlineCost> ReplayCost =
1145 getExternalInlineAdvisorCost(*Candidate.CallInstr))
1146 return *ReplayCost;
1147 // Adjust threshold based on call site hotness, only do this for callsite
1148 // prioritized inliner because otherwise cost-benefit check is done earlier.
1149 int SampleThreshold = InlineOpts.ColdCallSiteThreshold;
1150 if (CallsitePrioritizedInline) {
1151 if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1152 SampleThreshold = InlineOpts.HotCallSiteThreshold;
1153 else if (!ProfileSizeInline)
1154 return InlineCost::getNever("cold callsite");
1155 }
1156
1157 Function *Caller = Candidate.CallInstr->getCaller();
1158 Function *Callee = Candidate.CallInstr->getCalledFunction();
1159 assert(Callee && "Expect a definition for inline candidate of direct call");
1160
1161 InlineParams Params = getInlineParams(Caller->getContext());
1162 // We will ignore the threshold from inline cost, so always get full cost.
1163 Params.ComputeFullInlineCost = true;
1164 Params.AllowRecursiveCall = AllowRecursiveInline;
1165 // Checks if there is anything in the reachable portion of the callee at
1166 // this callsite that makes this inlining potentially illegal. Need to
1167 // set ComputeFullInlineCost, otherwise getInlineCost may return early
1168 // when cost exceeds threshold without checking all IRs in the callee.
1169 // The acutal cost does not matter because we only checks isNever() to
1170 // see if it is legal to inline the callsite.
1171 InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1172 GetTTI(*Caller), GetAC, GetTLI);
1173
1174 // Honor always inline and never inline from call analyzer
1175 if (Cost.isNever() || Cost.isAlways())
1176 return Cost;
1177
1178 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1179 // decisions based on hotness as well as accurate function byte sizes for
1180 // given context using function/inlinee sizes from previous build. It
1181 // stores the decision in profile, and also adjust/merge context profile
1182 // aiming at better context-sensitive post-inline profile quality, assuming
1183 // all inline decision estimates are going to be honored by compiler. Here
1184 // we replay that inline decision under `sample-profile-use-preinliner`.
1185 // Note that we don't need to handle negative decision from preinliner as
1186 // context profile for not inlined calls are merged by preinliner already.
1187 if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1188 // Once two node are merged due to promotion, we're losing some context
1189 // so the original context-sensitive preinliner decision should be ignored
1190 // for SyntheticContext.
1191 SampleContext &Context = Candidate.CalleeSamples->getContext();
1192 if (!Context.hasState(SyntheticContext) &&
1193 Context.hasAttribute(ContextShouldBeInlined))
1194 return InlineCost::getAlways("preinliner");
1195 }
1196
1197 // For old FDO inliner, we inline the call site if it is below hot threshold,
1198 // even if the function is hot based on sample profile data. This is to
1199 // prevent huge functions from being inlined.
1200 if (!CallsitePrioritizedInline) {
1201 return InlineCost::get(Cost.getCost(), InlineOpts.HotCallSiteThreshold);
1202 }
1203
1204 // Otherwise only use the cost from call analyzer, but overwite threshold with
1205 // Sample PGO threshold.
1206 return InlineCost::get(Cost.getCost(), SampleThreshold);
1207}
1208
1209bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1210 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1211 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1212 // Profile symbol list is ignored when profile-sample-accurate is on.
1213 assert((!ProfAccForSymsInList ||
1214 (!Opts.profile_sample_accurate &&
1215 !F.hasFnAttribute("profile-sample-accurate"))) &&
1216 "ProfAccForSymsInList should be false when profile-sample-accurate "
1217 "is enabled");
1218
1219 // Populating worklist with initial call sites from root inliner, along
1220 // with call site weights.
1221 CandidateQueue CQueue;
1222 InlineCandidate NewCandidate;
1223 for (auto &BB : F) {
1224 for (CallBase &CB : make_isa_range<CallBase>(BB)) {
1225 if (getInlineCandidate(&NewCandidate, &CB))
1226 CQueue.push(NewCandidate);
1227 }
1228 }
1229
1230 // Cap the size growth from profile guided inlining. This is needed even
1231 // though cost of each inline candidate already accounts for callee size,
1232 // because with top-down inlining, we can grow inliner size significantly
1233 // with large number of smaller inlinees each pass the cost check.
1234 assert(InlineOpts.LimitMax >= InlineOpts.LimitMin &&
1235 "Max inline size limit should not be smaller than min inline size "
1236 "limit.");
1237 unsigned SizeLimit = F.getInstructionCount() * InlineOpts.GrowthLimit;
1238 SizeLimit = std::min(SizeLimit, InlineOpts.LimitMax);
1239 SizeLimit = std::max(SizeLimit, InlineOpts.LimitMin);
1240 if (ExternalInlineAdvisor)
1241 SizeLimit = std::numeric_limits<unsigned>::max();
1242
1243 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1244
1245 // Perform iterative BFS call site prioritized inlining
1246 bool Changed = false;
1247 while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1248 InlineCandidate Candidate = CQueue.top();
1249 CQueue.pop();
1250 CallBase *I = Candidate.CallInstr;
1251 Function *CalledFunction = I->getCalledFunction();
1252
1253 if (CalledFunction == &F)
1254 continue;
1255 if (I->isIndirectCall()) {
1256 uint64_t Sum = 0;
1257 auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1258 uint64_t SumOrigin = Sum;
1259 Sum *= Candidate.CallsiteDistribution;
1260 unsigned ICPCount = 0;
1261 for (const auto *FS : CalleeSamples) {
1262 // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1263 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1264 findExternalInlineCandidate(I, FS, InlinedGUIDs,
1265 PSI->getOrCompHotCountThreshold());
1266 continue;
1267 }
1268 uint64_t EntryCountDistributed =
1269 FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1270 // In addition to regular inline cost check, we also need to make sure
1271 // ICP isn't introducing excessive speculative checks even if individual
1272 // target looks beneficial to promote and inline. That means we should
1273 // only do ICP when there's a small number dominant targets.
1274 if (ICPCount >= Opts.sample_profile_icp_relative_hotness_skip &&
1275 EntryCountDistributed * 100 <
1276 SumOrigin * Opts.sample_profile_icp_relative_hotness)
1277 break;
1278 // TODO: Fix CallAnalyzer to handle all indirect calls.
1279 // For indirect call, we don't run CallAnalyzer to get InlineCost
1280 // before actual inlining. This is because we could see two different
1281 // types from the same definition, which makes CallAnalyzer choke as
1282 // it's expecting matching parameter type on both caller and callee
1283 // side. See example from PR18962 for the triggering cases (the bug was
1284 // fixed, but we generate different types).
1285 if (!PSI->isHotCount(EntryCountDistributed))
1286 break;
1287 SmallVector<CallBase *, 8> InlinedCallSites;
1288 // Attach function profile for promoted indirect callee, and update
1289 // call site count for the promoted inline candidate too.
1290 Candidate = {I, FS, EntryCountDistributed,
1291 Candidate.CallsiteDistribution};
1292 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1293 &InlinedCallSites)) {
1294 for (auto *CB : InlinedCallSites) {
1295 if (getInlineCandidate(&NewCandidate, CB))
1296 CQueue.emplace(NewCandidate);
1297 }
1298 ICPCount++;
1299 Changed = true;
1300 } else if (!ContextTracker) {
1301 LocalNotInlinedCallSites.insert({I, FS});
1302 }
1303 }
1304 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1305 !CalledFunction->isDeclaration()) {
1306 SmallVector<CallBase *, 8> InlinedCallSites;
1307 if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1308 for (auto *CB : InlinedCallSites) {
1309 if (getInlineCandidate(&NewCandidate, CB))
1310 CQueue.emplace(NewCandidate);
1311 }
1312 Changed = true;
1313 } else if (!ContextTracker) {
1314 LocalNotInlinedCallSites.insert({I, Candidate.CalleeSamples});
1315 }
1316 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1317 findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1318 InlinedGUIDs,
1319 PSI->getOrCompHotCountThreshold());
1320 }
1321 }
1322
1323 if (!CQueue.empty()) {
1324 if (SizeLimit == InlineOpts.LimitMax)
1325 ++NumCSInlinedHitMaxLimit;
1326 else if (SizeLimit == InlineOpts.LimitMin)
1327 ++NumCSInlinedHitMinLimit;
1328 else
1329 ++NumCSInlinedHitGrowthLimit;
1330 }
1331
1332 // For CS profile, profile for not inlined context will be merged when
1333 // base profile is being retrieved.
1335 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1336 return Changed;
1337}
1338
1339void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1340 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
1341 const Function &F) {
1342 // Accumulate not inlined callsite information into notInlinedSamples
1343 for (const auto &Pair : NonInlinedCallSites) {
1344 CallBase *I = Pair.first;
1345 Function *Callee = I->getCalledFunction();
1346 if (!Callee || Callee->isDeclaration())
1347 continue;
1348
1349 ORE->emit(
1350 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
1351 I->getDebugLoc(), I->getParent())
1352 << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
1353 << "' into '" << ore::NV("Caller", &F) << "'");
1354
1355 ++NumCSNotInlined;
1356 const FunctionSamples *FS = Pair.second;
1357 if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
1358 continue;
1359 }
1360
1361 // Do not merge a context that is already duplicated into the base profile.
1362 if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
1363 continue;
1364
1365 if (ProfileMergeInlinee) {
1366 // A function call can be replicated by optimizations like callsite
1367 // splitting or jump threading and the replicates end up sharing the
1368 // sample nested callee profile instead of slicing the original
1369 // inlinee's profile. We want to do merge exactly once by filtering out
1370 // callee profiles with a non-zero head sample count.
1371 if (FS->getHeadSamples() == 0) {
1372 // Use entry samples as head samples during the merge, as inlinees
1373 // don't have head samples.
1374 const_cast<FunctionSamples *>(FS)->addHeadSamples(
1375 FS->getHeadSamplesEstimate());
1376
1377 // Note that we have to do the merge right after processing function.
1378 // This allows OutlineFS's profile to be used for annotation during
1379 // top-down processing of functions' annotation.
1380 FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
1381 // If outlined function does not exist in the profile, add it to a
1382 // separate map so that it does not rehash the original profile.
1383 if (!OutlineFS)
1384 OutlineFS = &OutlineFunctionSamples[
1385 FunctionId(FunctionSamples::getCanonicalFnName(Callee->getName()))];
1386 OutlineFS->merge(*FS, 1);
1387 // Set outlined profile to be synthetic to not bias the inliner.
1388 OutlineFS->setContextSynthetic();
1389 }
1390 } else {
1391 auto pair =
1392 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1393 pair.first->second.entryCount += FS->getHeadSamplesEstimate();
1394 }
1395 }
1396}
1397
1398/// Returns the sorted CallTargetMap \p M by count in descending order.
1402 for (const auto &I : SampleRecord::sortCallTargets(M)) {
1403 R.emplace_back(
1404 InstrProfValueData{I.first.getHashCode(), I.second});
1405 }
1406 return R;
1407}
1408
1409// Generate MD_prof metadata for every branch instruction using the
1410// edge weights computed during propagation.
1411void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1412 // Generate MD_prof metadata for every branch instruction using the
1413 // edge weights computed during propagation.
1414 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1415 LLVMContext &Ctx = F.getContext();
1416 MDBuilder MDB(Ctx);
1417 for (auto &BI : F) {
1418 BasicBlock *BB = &BI;
1419
1420 if (BlockWeights[BB]) {
1421 for (auto &I : *BB) {
1422 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1423 continue;
1425 const DebugLoc &DLoc = I.getDebugLoc();
1426 if (!DLoc)
1427 continue;
1428 const DILocation *DIL = DLoc;
1429 const FunctionSamples *FS = findFunctionSamples(I);
1430 if (!FS)
1431 continue;
1433 ErrorOr<SampleRecord::CallTargetMap> T =
1434 FS->findCallTargetMapAt(CallSite);
1435 if (!T || T.get().empty())
1436 continue;
1438 // Prorate the callsite counts based on the pre-ICP distribution
1439 // factor to reflect what is already done to the callsite before
1440 // ICP, such as calliste cloning.
1441 if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
1442 if (Probe->Factor < 1)
1443 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1444 }
1445 }
1446 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1448 uint64_t Sum = 0;
1449 for (const auto &C : T.get())
1450 Sum += C.second;
1451 // With CSSPGO all indirect call targets are counted torwards the
1452 // original indirect call site in the profile, including both
1453 // inlined and non-inlined targets.
1455 if (const FunctionSamplesMap *M =
1456 FS->findFunctionSamplesMapAt(CallSite)) {
1457 for (const auto &NameFS : *M)
1458 Sum += NameFS.second.getHeadSamplesEstimate();
1459 }
1460 }
1461 if (Sum)
1462 updateIDTMetaData(Opts, I, SortedCallTargets, Sum);
1463 else if (Opts.overwrite_existing_weights)
1464 I.setMetadata(LLVMContext::MD_prof, nullptr);
1465 } else if (!isa<IntrinsicInst>(&I)) {
1467 I, ArrayRef<uint32_t>{static_cast<uint32_t>(BlockWeights[BB])},
1468 /*IsExpected=*/false);
1469 }
1470 }
1471 } else if (Opts.overwrite_existing_weights ||
1472 Opts.profile_sample_block_accurate) {
1473 // Set profile metadata (possibly annotated by LTO prelink) to zero or
1474 // clear it for cold code.
1475 for (auto &I : *BB) {
1476 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1478 I.setMetadata(LLVMContext::MD_prof, nullptr);
1479 } else {
1480 setBranchWeights(I, ArrayRef<uint32_t>{uint32_t(0)},
1481 /*IsExpected=*/false);
1482 }
1483 }
1484 }
1485 }
1486
1487 Instruction *TI = BB->getTerminator();
1488 if (TI->getNumSuccessors() == 1)
1489 continue;
1490 if (!isa<CondBrInst>(TI) && !isa<SwitchInst>(TI) &&
1492 continue;
1493
1494 DebugLoc BranchLoc = TI->getDebugLoc();
1495 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1496 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1497 : Twine("<UNKNOWN LOCATION>"))
1498 << ".\n");
1499 SmallVector<uint32_t, 4> Weights;
1500 uint32_t MaxWeight = 0;
1501 Instruction *MaxDestInst;
1502 // Since profi treats multiple edges (multiway branches) as a single edge,
1503 // we need to distribute the computed weight among the branches. We do
1504 // this by evenly splitting the edge weight among destinations.
1505 DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
1506 std::vector<uint64_t> EdgeIndex;
1508 EdgeIndex.resize(TI->getNumSuccessors());
1509 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1510 const BasicBlock *Succ = TI->getSuccessor(I);
1511 EdgeIndex[I] = EdgeMultiplicity[Succ];
1512 EdgeMultiplicity[Succ]++;
1513 }
1514 }
1515 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1516 BasicBlock *Succ = TI->getSuccessor(I);
1517 Edge E = std::make_pair(BB, Succ);
1518 uint64_t Weight = EdgeWeights[E];
1519 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1520 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1521 // if needed. Sample counts in profiles are 64-bit unsigned values,
1522 // but internally branch weights are expressed as 32-bit values.
1523 if (Weight > std::numeric_limits<uint32_t>::max()) {
1524 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)\n");
1525 Weight = std::numeric_limits<uint32_t>::max();
1526 }
1527 if (!SampleProfileUseProfi) {
1528 // Weight is added by one to avoid propagation errors introduced by
1529 // 0 weights.
1530 Weights.push_back(static_cast<uint32_t>(
1531 Weight == std::numeric_limits<uint32_t>::max() ? Weight
1532 : Weight + 1));
1533 } else {
1534 // Profi creates proper weights that do not require "+1" adjustments but
1535 // we evenly split the weight among branches with the same destination.
1536 uint64_t W = Weight / EdgeMultiplicity[Succ];
1537 // Rounding up, if needed, so that first branches are hotter.
1538 if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
1539 W++;
1540 Weights.push_back(static_cast<uint32_t>(W));
1541 }
1542 if (Weight != 0) {
1543 if (Weight > MaxWeight) {
1544 MaxWeight = Weight;
1545 MaxDestInst = &*Succ->getFirstNonPHIOrLifetime();
1546 }
1547 }
1548 }
1549
1550 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
1551
1552 uint64_t TempWeight;
1553 // Only set weights if there is at least one non-zero weight.
1554 // In any other case, let the analyzer set weights.
1555 // Do not set weights if the weights are present unless under
1556 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1557 // twice. If the first annotation already set the weights, the second pass
1558 // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1559 // weight should have their existing metadata (possibly annotated by LTO
1560 // prelink) cleared.
1561 if (MaxWeight > 0 && (!TI->extractProfTotalWeight(TempWeight) ||
1562 Opts.overwrite_existing_weights)) {
1563 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1564 setBranchWeights(*TI, Weights, /*IsExpected=*/false);
1565 ORE->emit([&]() {
1566 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1567 << "most popular destination for conditional branches at "
1568 << ore::NV("CondBranchesLoc", BranchLoc);
1569 });
1570 } else {
1571 if (Opts.overwrite_existing_weights) {
1572 TI->setMetadata(LLVMContext::MD_prof, nullptr);
1573 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1574 } else {
1575 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1576 }
1577 }
1578 }
1579}
1580
1581/// Once all the branch weights are computed, we emit the MD_prof
1582/// metadata on BB using the computed values for each of its branches.
1583///
1584/// \param F The function to query.
1585///
1586/// \returns true if \p F was modified. Returns false, otherwise.
1587bool SampleProfileLoader::emitAnnotations(Function &F) {
1588 bool Changed = false;
1589
1591 LLVM_DEBUG({
1592 if (!ProbeManager->getDesc(F))
1593 dbgs() << "Probe descriptor missing for Function " << F.getName()
1594 << "\n";
1595 });
1596
1597 if (ProbeManager->profileIsValid(F, *Samples)) {
1598 ++NumMatchedProfile;
1599 } else {
1600 ++NumMismatchedProfile;
1601 LLVM_DEBUG(
1602 dbgs() << "Profile is invalid due to CFG mismatch for Function "
1603 << F.getName() << "\n");
1604 if (!SalvageStaleProfile)
1605 return false;
1606 }
1607 } else {
1608 if (getFunctionLoc(F) == 0)
1609 return false;
1610
1611 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1612 << F.getName() << ": " << getFunctionLoc(F) << "\n");
1613 }
1614
1615 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1616 if (CallsitePrioritizedInline)
1617 Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1618 else
1619 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1620
1621 Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1622
1623 if (Changed)
1624 generateMDProfMetadata(F);
1625
1626 emitCoverageRemarks(F);
1627 return Changed;
1628}
1629
1630std::unique_ptr<ProfiledCallGraph>
1631SampleProfileLoader::buildProfiledCallGraph(Module &M) {
1632 std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1634 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1635 else
1636 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1637
1638 // Add all functions into the profiled call graph even if they are not in
1639 // the profile. This makes sure functions missing from the profile still
1640 // gets a chance to be processed.
1641 for (Function &F : M) {
1643 continue;
1644 ProfiledCG->addProfiledFunction(
1646 }
1647
1648 return ProfiledCG;
1649}
1650
1651std::vector<Function *>
1652SampleProfileLoader::buildFunctionOrder(Module &M, LazyCallGraph &CG) {
1653 std::vector<Function *> FunctionOrderList;
1654 FunctionOrderList.reserve(M.size());
1655
1656 if (!Opts.sample_profile_top_down_load && Opts.use_profiled_call_graph)
1657 errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1658 "together with -sample-profile-top-down-load.\n";
1659
1660 if (!Opts.sample_profile_top_down_load) {
1661 if (ProfileMergeInlinee) {
1662 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1663 // because the profile for a function may be used for the profile
1664 // annotation of its outline copy before the profile merging of its
1665 // non-inlined inline instances, and that is not the way how
1666 // ProfileMergeInlinee is supposed to work.
1667 ProfileMergeInlinee = false;
1668 }
1669
1670 for (Function &F : M)
1672 FunctionOrderList.push_back(&F);
1673 return FunctionOrderList;
1674 }
1675
1676 if (Opts.use_profiled_call_graph) {
1677 // Use profiled call edges to augment the top-down order. There are cases
1678 // that the top-down order computed based on the static call graph doesn't
1679 // reflect real execution order. For example
1680 //
1681 // 1. Incomplete static call graph due to unknown indirect call targets.
1682 // Adjusting the order by considering indirect call edges from the
1683 // profile can enable the inlining of indirect call targets by allowing
1684 // the caller processed before them.
1685 // 2. Mutual call edges in an SCC. The static processing order computed for
1686 // an SCC may not reflect the call contexts in the context-sensitive
1687 // profile, thus may cause potential inlining to be overlooked. The
1688 // function order in one SCC is being adjusted to a top-down order based
1689 // on the profile to favor more inlining. This is only a problem with CS
1690 // profile.
1691 // 3. Transitive indirect call edges due to inlining. When a callee function
1692 // (say B) is inlined into a caller function (say A) in LTO prelink,
1693 // every call edge originated from the callee B will be transferred to
1694 // the caller A. If any transferred edge (say A->C) is indirect, the
1695 // original profiled indirect edge B->C, even if considered, would not
1696 // enforce a top-down order from the caller A to the potential indirect
1697 // call target C in LTO postlink since the inlined callee B is gone from
1698 // the static call graph.
1699 // 4. #3 can happen even for direct call targets, due to functions defined
1700 // in header files. A header function (say A), when included into source
1701 // files, is defined multiple times but only one definition survives due
1702 // to ODR. Therefore, the LTO prelink inlining done on those dropped
1703 // definitions can be useless based on a local file scope. More
1704 // importantly, the inlinee (say B), once fully inlined to a
1705 // to-be-dropped A, will have no profile to consume when its outlined
1706 // version is compiled. This can lead to a profile-less prelink
1707 // compilation for the outlined version of B which may be called from
1708 // external modules. while this isn't easy to fix, we rely on the
1709 // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1710 // the A can be inlined in its local scope in prelink, it may not exist
1711 // in the merged IR in postlink, and we'll need the profiled call edges
1712 // to enforce a top-down order for the rest of the functions.
1713 //
1714 // Considering those cases, a profiled call graph completely independent of
1715 // the static call graph is constructed based on profile data, where
1716 // function objects are not even needed to handle case #3 and case 4.
1717 //
1718 // Note that static callgraph edges are completely ignored since they
1719 // can be conflicting with profiled edges for cyclic SCCs and may result in
1720 // an SCC order incompatible with profile-defined one. Using strictly
1721 // profile order ensures a maximum inlining experience. On the other hand,
1722 // static call edges are not so important when they don't correspond to a
1723 // context in the profile.
1724
1725 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1726 scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1727 while (!CGI.isAtEnd()) {
1728 auto Range = *CGI;
1729 if (InlineOpts.SortProfiledSCC) {
1730 // Sort nodes in one SCC based on callsite hotness.
1731 scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
1732 Range = *SI;
1733 }
1734 for (auto *Node : Range) {
1735 Function *F = SymbolMap.lookup(Node->Name);
1736 if (F && !skipProfileForFunction(*F))
1737 FunctionOrderList.push_back(F);
1738 }
1739 ++CGI;
1740 }
1741 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1742 } else
1743 buildTopDownFuncOrder(CG, FunctionOrderList);
1744
1745 LLVM_DEBUG({
1746 dbgs() << "Function processing order:\n";
1747 for (auto F : FunctionOrderList) {
1748 dbgs() << F->getName() << "\n";
1749 }
1750 });
1751
1752 return FunctionOrderList;
1753}
1754
1755bool SampleProfileLoader::doInitialization(Module &M,
1757 auto &Ctx = M.getContext();
1758 InlineOpts =
1760
1761 auto ReaderOrErr = SampleProfileReader::create(
1762 Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
1763 if (std::error_code EC = ReaderOrErr.getError()) {
1764 std::string Msg = "Could not open profile: " + EC.message();
1765 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1766 return false;
1767 }
1768 Reader = std::move(ReaderOrErr.get());
1769 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1770 // set module before reading the profile so reader may be able to only
1771 // read the function profiles which are used by the current module.
1772 Reader->setModule(&M);
1773 if (std::error_code EC = Reader->read()) {
1774 std::string Msg = "profile reading failed: " + EC.message();
1775 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1776 return false;
1777 }
1778
1779 PSL = Reader->getProfileSymbolList();
1780
1781 DisableSampleProfileInlining =
1782 !valueOr(Opts.sample_loader_inlining, !DisableSampleProfileInlining);
1783
1784 if (UseFlattenedProfile)
1785 ProfileConverter::flattenProfile(Reader->getProfiles(),
1786 Reader->profileIsCS());
1787
1788 // While profile-sample-accurate is on, ignore symbol list.
1789 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL &&
1790 !Opts.profile_sample_accurate;
1791 if (ProfAccForSymsInList)
1792 CoverageTracker.setProfAccForSymsInList(true);
1793
1794 if (FAM && !Opts.sample_profile_inline_replay.empty()) {
1795 ExternalInlineAdvisor = getReplayInlineAdvisor(
1796 M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
1797 ReplayInlinerSettings{Opts.sample_profile_inline_replay,
1798 Opts.sample_profile_inline_replay_scope,
1799 Opts.sample_profile_inline_replay_fallback,
1800 {Opts.sample_profile_inline_replay_format}},
1801 /*EmitRemarks=*/false,
1802 InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
1803 }
1804
1805 // Apply tweaks if context-sensitive or probe-based profile is available.
1806 if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
1807 Reader->profileIsProbeBased()) {
1811 SampleProfileUseProfi = true;
1814 // Enable priority-base inliner and size inline by default for CSSPGO.
1815 ProfileSizeInline = valueOr(Opts.sample_profile_inline_size, true);
1816 CallsitePrioritizedInline =
1817 valueOr(Opts.sample_profile_prioritized_inline, true);
1818 // For CSSPGO, we also allow recursive inline to best use context profile.
1819 AllowRecursiveInline = valueOr(Opts.sample_profile_recursive_inline, true);
1820
1821 if (Reader->profileIsPreInlined())
1822 UsePreInlinerDecision = valueOr(Opts.sample_profile_use_preinliner, true);
1823
1824 // Enable stale profile matching by default for probe-based profile.
1825 // Currently the matching relies on if the checksum mismatch is detected,
1826 // which is currently only available for pseudo-probe mode. Removing the
1827 // checksum check could cause regressions for some cases, so further tuning
1828 // might be needed if we want to enable it for all cases.
1829 if (Reader->profileIsProbeBased()) {
1830 SalvageStaleProfile = valueOr(Opts.salvage_stale_profile, true);
1831 SalvageUnusedProfile = valueOr(Opts.salvage_unused_profile, true);
1832 }
1833
1834 if (!Reader->profileIsCS()) {
1835 // Non-CS profile should be fine without a function size budget for the
1836 // inliner since the contexts in the profile are either all from inlining
1837 // in the prevoius build or pre-computed by the preinliner with a size
1838 // cap, thus they are bounded.
1839 InlineOpts.LimitMin = Opts.sample_profile_inline_limit_min.value_or(
1840 std::numeric_limits<unsigned>::max());
1841 InlineOpts.LimitMax =
1842 std::max(Opts.sample_profile_inline_limit_max.value_or(
1843 std::numeric_limits<unsigned>::max()),
1844 InlineOpts.LimitMin);
1845 }
1846 }
1847
1848 if (Reader->profileIsCS()) {
1849 // Tracker for profiles under different context
1850 ContextTracker = std::make_unique<SampleContextTracker>(
1851 Reader->getProfiles(), &GUIDToFuncNameMap);
1852 }
1853
1854 // Load pseudo probe descriptors for probe-based function samples.
1855 if (Reader->profileIsProbeBased()) {
1856 ProbeManager = std::make_unique<PseudoProbeManager>(M);
1857 if (!ProbeManager->moduleIsProbed(M)) {
1858 const char *Msg =
1859 "Pseudo-probe-based profile requires SampleProfileProbePass";
1860 Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
1861 DS_Warning));
1862 return false;
1863 }
1864 }
1865
1866 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1867 SalvageStaleProfile) {
1868 MatchingManager = std::make_unique<SampleProfileMatcher>(
1869 Opts, M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
1870 FuncNameToProfNameMap, SalvageStaleProfile, SalvageUnusedProfile);
1871 }
1872
1873 return true;
1874}
1875
1876// Note that this is a module-level check. Even if one module is errored out,
1877// the entire build will be errored out. However, the user could make big
1878// changes to functions in single module but those changes might not be
1879// performance significant to the whole binary. Therefore, to avoid those false
1880// positives, we select a reasonable big set of hot functions that are supposed
1881// to be globally performance significant, only compute and check the mismatch
1882// within those functions. The function selection is based on two criteria:
1883// 1) The function is hot enough, which is tuned by a hotness-based
1884// flag(HotFuncCutoffForStalenessError). 2) The num of function is large enough
1885// which is tuned by the MinfuncsForStalenessError flag.
1886bool SampleProfileLoader::rejectHighStalenessProfile(
1887 Module &M, ProfileSummaryInfo *PSI, const SampleProfileMap &Profiles) {
1889 "Only support for probe-based profile");
1890 uint64_t TotalHotFunc = 0;
1891 uint64_t NumMismatchedFunc = 0;
1892 for (const auto &I : Profiles) {
1893 const auto &FS = I.second;
1894 const auto *FuncDesc = ProbeManager->getDesc(FS.getGUID());
1895 if (!FuncDesc)
1896 continue;
1897
1898 // Use a hotness-based threshold to control the function selection.
1899 if (!PSI->isHotCountNthPercentile(Opts.hot_func_cutoff_for_staleness_error,
1900 FS.getTotalSamples()))
1901 continue;
1902
1903 TotalHotFunc++;
1904 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS) &&
1905 !ProbeManager->probeFromWeakSymbol(FS.getGUID()))
1906 NumMismatchedFunc++;
1907 }
1908 // Make sure that the num of selected function is not too small to distinguish
1909 // from the user's benign changes.
1910 if (TotalHotFunc < Opts.min_functions_for_staleness_error)
1911 return false;
1912
1913 // Finally check the mismatch percentage against the threshold.
1914 if (NumMismatchedFunc * 100 >=
1915 TotalHotFunc * Opts.percent_mismatch_for_staleness_error) {
1916 auto &Ctx = M.getContext();
1917 const char *Msg =
1918 "The input profile significantly mismatches current source code. "
1919 "Please recollect profile to avoid performance regression.";
1920 Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg));
1921 return true;
1922 }
1923 return false;
1924}
1925
1926void SampleProfileLoader::removePseudoProbeInstsDiscriminator(Module &M) {
1927 for (auto &F : M) {
1928 std::vector<Instruction *> InstsToDel;
1929 for (auto &BB : F) {
1930 for (auto &I : BB) {
1931 if (isa<PseudoProbeInst>(&I))
1932 InstsToDel.push_back(&I);
1933 else if (isa<CallBase>(&I))
1934 if (const DILocation *DIL = I.getDebugLoc().get()) {
1935 // Restore dwarf discriminator for call.
1936 unsigned Discriminator = DIL->getDiscriminator();
1937 if (DILocation::isPseudoProbeDiscriminator(Discriminator)) {
1938 std::optional<uint32_t> DwarfDiscriminator =
1940 Discriminator);
1941 I.setDebugLoc(
1942 DIL->cloneWithDiscriminator(DwarfDiscriminator.value_or(0)));
1943 }
1944 }
1945 }
1946 }
1947 for (auto *I : InstsToDel)
1948 I->eraseFromParent();
1949 }
1950}
1951
1952bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager &AM,
1953 ProfileSummaryInfo *_PSI) {
1954 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1955
1956 PSI = _PSI;
1957 if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1958 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1960 PSI->refresh();
1961 }
1962
1964 rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
1965 return false;
1966
1967 auto Remapper = Reader->getRemapper();
1968 // Populate the symbol map.
1969 for (const auto &N_F : M.getValueSymbolTable()) {
1970 StringRef OrigName = N_F.getKey();
1971 Function *F = dyn_cast<Function>(N_F.getValue());
1972 if (F == nullptr || OrigName.empty())
1973 continue;
1974 SymbolMap[FunctionId(OrigName)] = F;
1975 StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
1976 if (OrigName != NewName && !NewName.empty()) {
1977 auto r = SymbolMap.emplace(FunctionId(NewName), F);
1978 // Failiing to insert means there is already an entry in SymbolMap,
1979 // thus there are multiple functions that are mapped to the same
1980 // stripped name. In this case of name conflicting, set the value
1981 // to nullptr to avoid confusion.
1982 if (!r.second)
1983 r.first->second = nullptr;
1984 OrigName = NewName;
1985 }
1986 // Insert the remapped names into SymbolMap.
1987 if (Remapper) {
1988 if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1989 if (*MapName != OrigName && !MapName->empty())
1990 SymbolMap.emplace(FunctionId(*MapName), F);
1991 }
1992 }
1993 }
1994
1995 // Stale profile matching.
1996 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1997 SalvageStaleProfile) {
1998 MatchingManager->runOnModule();
1999 MatchingManager->clearMatchingData();
2000 }
2001 assert(SymbolMap.count(FunctionId()) == 0 &&
2002 "No empty StringRef should be added in SymbolMap");
2003 assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2004 "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2005 "not enabled");
2006
2007 bool retval = false;
2008 for (auto *F : buildFunctionOrder(M, CG)) {
2009 assert(!F->isDeclaration());
2010 clearFunctionData();
2011 retval |= runOnFunction(*F, AM);
2012 }
2013
2014 // Account for cold calls not inlined....
2016 for (const auto &[Fn, Info] : notInlinedCallInfo)
2017 updateProfileCallee(Fn, Info.entryCount);
2018
2019 if (Opts.sample_profile_remove_probe &&
2021 removePseudoProbeInstsDiscriminator(M);
2022 if (auto *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName))
2023 M.eraseNamedMetadata(FuncInfo);
2024 }
2025
2026 return retval;
2027}
2028
2029bool SampleProfileLoader::runOnFunction(Function &F,
2031 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
2032 DILocation2SampleMap.clear();
2033 // By default the entry count is initialized to -1, which will be treated
2034 // conservatively by getEntryCount as the same as unknown (None). This is
2035 // to avoid newly added code to be treated as cold. If we have samples
2036 // this will be overwritten in emitAnnotations.
2037 uint64_t initialEntryCount = -1;
2038
2039 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL;
2040 if (Opts.profile_sample_accurate ||
2041 F.hasFnAttribute("profile-sample-accurate")) {
2042 // initialize all the function entry counts to 0. It means all the
2043 // functions without profile will be regarded as cold.
2044 initialEntryCount = 0;
2045 // profile-sample-accurate is a user assertion which has a higher precedence
2046 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2047 ProfAccForSymsInList = false;
2048 }
2049 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2050
2051 // PSL -- profile symbol list include all the symbols in sampled binary.
2052 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2053 // old functions without samples being cold, without having to worry
2054 // about new and hot functions being mistakenly treated as cold.
2055 if (ProfAccForSymsInList) {
2056 // Initialize the entry count to 0 for functions in the list.
2057 if (PSL->contains(F.getName()))
2058 initialEntryCount = 0;
2059
2060 // Function in the symbol list but without sample will be regarded as
2061 // cold. To minimize the potential negative performance impact it could
2062 // have, we want to be a little conservative here saying if a function
2063 // shows up in the profile, no matter as outline function, inline instance
2064 // or call targets, treat the function as not being cold. This will handle
2065 // the cases such as most callsites of a function are inlined in sampled
2066 // binary but not inlined in current build (because of source code drift,
2067 // imprecise debug information, or the callsites are all cold individually
2068 // but not cold accumulatively...), so the outline function showing up as
2069 // cold in sampled binary will actually not be cold after current build.
2070 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2072 ? Reader->contains(
2073 Function::getGUIDAssumingExternalLinkage(CanonName))
2074 : Reader->contains(CanonName))
2075 initialEntryCount = -1;
2076 }
2077
2078 // Initialize entry count when the function has no existing entry
2079 // count value.
2080 if (!F.getEntryCount())
2081 F.setEntryCount(initialEntryCount);
2082 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2083 .getManager();
2084 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2085
2087 Samples = ContextTracker->getBaseSamplesFor(F);
2088 else {
2089 Samples = Reader->getSamplesFor(F);
2090 // Try search in previously inlined functions that were split or duplicated
2091 // into base.
2092 if (!Samples) {
2093 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2094 auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
2095 if (It != OutlineFunctionSamples.end()) {
2096 Samples = &It->second;
2097 } else if (auto Remapper = Reader->getRemapper()) {
2098 if (auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
2099 It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
2100 if (It != OutlineFunctionSamples.end())
2101 Samples = &It->second;
2102 }
2103 }
2104 }
2105 }
2106
2107 if (Samples && !Samples->empty())
2108 return emitAnnotations(F);
2109 return false;
2110}
2114
2117 SampleProfileInlineOptions Defaults) {
2118 const auto &Opts = C.get<IPOOptions>();
2119 Defaults.HotCallSiteThreshold =
2120 Opts.sample_profile_hot_inline_threshold.value_or(
2121 Defaults.HotCallSiteThreshold);
2122 Defaults.ColdCallSiteThreshold =
2123 Opts.sample_profile_cold_inline_threshold.value_or(
2124 Defaults.ColdCallSiteThreshold);
2125 Defaults.GrowthLimit =
2126 Opts.sample_profile_inline_growth_limit.value_or(Defaults.GrowthLimit);
2127 Defaults.LimitMin =
2128 Opts.sample_profile_inline_limit_min.value_or(Defaults.LimitMin);
2129 Defaults.LimitMax =
2130 Opts.sample_profile_inline_limit_max.value_or(Defaults.LimitMax);
2131 Defaults.SortProfiledSCC =
2132 valueOr(Opts.sort_profiled_scc_member, Defaults.SortProfiledSCC);
2133 return Defaults;
2134}
2135
2137 std::string File, std::string RemappingFile, ThinOrFullLTOPhase LTOPhase,
2138 IntrusiveRefCntPtr<vfs::FileSystem> FS, bool DisableSampleProfileInlining,
2139 bool UseFlattenedProfile)
2140 : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
2141 LTOPhase(LTOPhase), FS(std::move(FS)),
2142 DisableSampleProfileInlining(DisableSampleProfileInlining),
2143 UseFlattenedProfile(UseFlattenedProfile) {}
2144
2149
2150 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2151 return FAM.getResult<AssumptionAnalysis>(F);
2152 };
2153 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2154 return FAM.getResult<TargetIRAnalysis>(F);
2155 };
2156 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2157 return FAM.getResult<TargetLibraryAnalysis>(F);
2158 };
2159
2160 if (!FS)
2163
2164 const IPOOptions &Opts = getIPOOptions(M);
2165 SampleProfileLoader SampleLoader(
2166 Opts,
2167 ProfileFileName.empty() ? Opts.sample_profile_file
2168 : StringRef(ProfileFileName),
2169 ProfileRemappingFileName.empty() ? Opts.sample_profile_remapping_file
2170 : StringRef(ProfileRemappingFileName),
2171 LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG,
2172 DisableSampleProfileInlining, UseFlattenedProfile);
2173 if (!SampleLoader.doInitialization(M, &FAM))
2174 return PreservedAnalyses::all();
2175
2177 if (!SampleLoader.runOnModule(M, AM, PSI))
2178 return PreservedAnalyses::all();
2179
2180 return PreservedAnalyses::none();
2181}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
Provides ErrorOr<T> smart pointer.
#define DEBUG_TYPE
static cl::opt< unsigned > SizeLimit("eif-limit", cl::init(6), cl::Hidden, cl::desc("Size limit in Hexagon early if-conversion"))
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static LVReader * CurrentReader
Definition LVReader.cpp:179
Implements a lazy call graph analysis and related passes for the new pass manager.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static const Function * getCalledFunction(const Value *V)
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static constexpr StringLiteral Filename
FunctionAnalysisManager FAM
This file defines the PriorityQueue class.
This file contains the declarations for profiling metadata utility functions.
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
const char * Msg
std::pair< BasicBlock *, BasicBlock * > Edge
This file provides the interface for context-sensitive profile tracker used by CSSPGO.
This file provides the interface for the sampled PGO profile loader base implementation.
This file provides the utility functions for the sampled PGO loader base implementation.
This file provides the interface for SampleProfileMatcher.
This file provides the interface for the pseudo probe implementation for AutoFDO.
static void updateIDTMetaData(const IPOOptions &Opts, Instruction &Inst, const SmallVectorImpl< InstrProfValueData > &CallTargets, uint64_t Sum)
Update indirect call target profile metadata for Inst.
static bool doesHistoryAllowICP(const IPOOptions &Opts, const Instruction &Inst, StringRef Candidate)
Check whether the indirect call promotion history of Inst allows the promotion for Candidate.
static SmallVector< InstrProfValueData, 2 > GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M)
Returns the sorted CallTargetMap M by count in descending order.
#define CSINLINE_DEBUG
This file provides the interface for the sampled PGO loader pass.
This file defines the SmallVector class.
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:119
This pass exposes codegen information to IR-level passes.
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
bool empty() const
Returns true if the analysis manager has an empty results cache.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static bool isPseudoProbeDiscriminator(unsigned Discriminator)
const DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
A debug info location.
Definition DebugLoc.h:127
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:43
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents either an error or a value T.
Definition ErrorOr.h:56
DISubprogram * getSubprogram() const
Get the attached subprogram.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:135
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:130
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
Definition InlineCost.h:124
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
An analysis pass which computes the call graph for a module.
A lazily constructed view of the call graph of a module.
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:111
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:211
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
void computeDominanceAndLoopInfo(FunctionT &F)
static LLVM_ABI SampleProfileInlineOptions getInlineOptions(const cl::LibraryOptionsContext &C, SampleProfileInlineOptions Defaults)
Return Defaults overridden by the inliner options given in C.
static LLVM_ABI StringRef getSampleProfileFile(const LLVMContext &C)
Return -sample-profile-file.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SampleProfileLoaderPass(std::string File="", std::string RemappingFile="", ThinOrFullLTOPhase LTOPhase=ThinOrFullLTOPhase::None, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr, bool DisableSampleProfileInlining=false, bool UseFlattenedProfile=false)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
size_type size() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
const ParentTy * getParent() const
Definition ilist_node.h:34
Representation of the samples collected for a function.
Definition SampleProf.h:854
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold, bool IncludeLocalTargets=false) const
Recursively collect import GUIDs from contexts with total samples greater than Threshold,...
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
FunctionId getFunction() const
Return the function name.
SampleContext & getContext() const LLVM_LIFETIME_BOUND
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static void addImportGUID(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, FunctionId Name, bool IncludeLocal)
Add the import GUID of profiled function Name to S.
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
static LLVM_ABI std::atomic< bool > ProfileIsCS
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.
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
bool hasAttribute(ContextAttributeMask A)
Definition SampleProf.h:717
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition SampleProf.h:509
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition SampleProf.h:516
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
Definition SampleProf.h:436
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI void checkExpectAnnotations(const Instruction &I, ArrayRef< uint32_t > ExistingWeights, bool IsFrontend)
checkExpectAnnotations - compares PGO counters to the thresholds used for llvm.expect and warns if th...
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:844
LLVM_ABI bool callsiteIsHot(const FunctionSamples *CallsiteFS, ProfileSummaryInfo *PSI, bool ProfAccForSymsInList)
Return true if the given callsite is hot wrt to hot cutoff threshold.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
static bool isIndirectCall(const MachineInstr &MI)
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
InstructionCost Cost
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static void buildTopDownFuncOrder(LazyCallGraph &CG, std::vector< Function * > &FunctionOrderList)
LLVM_ABI InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This function inlines the called function into the basic block of the caller.
LLVM_ABI void setProbeDistributionFactor(Instruction &Inst, float Factor)
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
LLVM_ABI std::string AnnotateInlinePassName(InlineContext IC)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
LLVM_ABI cl::opt< bool > SampleProfileUseProfi
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:36
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
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:209
LLVM_ABI void emitInlinedIntoBasedOnCost(OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, const Function &Callee, const Function &Caller, const InlineCost &IC, bool ForProfileContext=false, const char *PassName=nullptr)
Emit ORE message based in cost (default heuristic).
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI std::unique_ptr< InlineAdvisor > getReplayInlineAdvisor(Module &M, FunctionAnalysisManager &FAM, LLVMContext &Context, std::unique_ptr< InlineAdvisor > OriginalAdvisor, const ReplayInlinerSettings &ReplaySettings, bool EmitRemarks, InlineContext IC)
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
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void updateProfileCallee(Function *Callee, int64_t EntryDelta, const ValueMap< const Value *, WeakTrackingVH > *VMap=nullptr)
Updates profile information by adjusting the entry count by adding EntryDelta then scaling callsite i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static bool skipProfileForFunction(const Function &F)
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
cl::opt< bool > EnableExtTspBlockPlacement
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition Metadata.h:60
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
constexpr const char * PseudoProbeDescMetadataName
Definition PseudoProbe.h:26
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
A wrapper of binary function with basic blocks and jumps.
std::optional< bool > AllowRecursiveCall
Indicate whether we allow inlining for recursive call.
Definition InlineCost.h:247
std::optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
Definition InlineCost.h:241
static std::optional< uint32_t > extractDwarfBaseDiscriminator(uint32_t Value)
Definition PseudoProbe.h:81
The thresholds of the priority-based sample profile loader inliner.