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 
24 #include "llvm/Transforms/IPO/SampleProfile.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/None.h"
29 #include "llvm/ADT/PriorityQueue.h"
30 #include "llvm/ADT/SCCIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/AssumptionCache.h"
39 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
40 #include "llvm/Analysis/CallGraph.h"
41 #include "llvm/Analysis/CallGraphSCCPass.h"
42 #include "llvm/Analysis/InlineAdvisor.h"
43 #include "llvm/Analysis/InlineCost.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
46 #include "llvm/Analysis/PostDominators.h"
47 #include "llvm/Analysis/ProfileSummaryInfo.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/TargetTransformInfo.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/CFG.h"
52 #include "llvm/IR/DebugInfoMetadata.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DiagnosticInfo.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/GlobalValue.h"
58 #include "llvm/IR/InstrTypes.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/PassManager.h"
66 #include "llvm/IR/ValueSymbolTable.h"
67 #include "llvm/InitializePasses.h"
68 #include "llvm/Pass.h"
69 #include "llvm/ProfileData/InstrProf.h"
70 #include "llvm/ProfileData/SampleProf.h"
71 #include "llvm/ProfileData/SampleProfReader.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/ErrorOr.h"
77 #include "llvm/Support/GenericDomTree.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Transforms/IPO.h"
80 #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
81 #include "llvm/Transforms/IPO/SampleContextTracker.h"
82 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
83 #include "llvm/Transforms/Instrumentation.h"
84 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
85 #include "llvm/Transforms/Utils/Cloning.h"
86 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
87 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstdint>
91 #include <functional>
92 #include <limits>
93 #include <map>
94 #include <memory>
95 #include <queue>
96 #include <string>
97 #include <system_error>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 using namespace sampleprof;
103 using namespace llvm::sampleprofutil;
104 using ProfileCount = Function::ProfileCount;
105 #define DEBUG_TYPE "sample-profile"
106 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
107 
108 STATISTIC(NumCSInlined,
109           "Number of functions inlined with context sensitive profile");
110 STATISTIC(NumCSNotInlined,
111           "Number of functions not inlined with context sensitive profile");
112 STATISTIC(NumMismatchedProfile,
113           "Number of functions with CFG mismatched profile");
114 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
115 STATISTIC(NumDuplicatedInlinesite,
116           "Number of inlined callsites with a partial distribution factor");
117 
118 STATISTIC(NumCSInlinedHitMinLimit,
119           "Number of functions with FDO inline stopped due to min size limit");
120 STATISTIC(NumCSInlinedHitMaxLimit,
121           "Number of functions with FDO inline stopped due to max size limit");
122 STATISTIC(
123     NumCSInlinedHitGrowthLimit,
124     "Number of functions with FDO inline stopped due to growth size limit");
125 
126 // Command line option to specify the file to read samples from. This is
127 // mainly used for debugging.
128 static cl::opt<std::string> SampleProfileFile(
129     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
130     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
131 
132 // The named file contains a set of transformations that may have been applied
133 // to the symbol names between the program from which the sample data was
134 // collected and the current program's symbols.
135 static cl::opt<std::string> SampleProfileRemappingFile(
136     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
137     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
138 
139 static cl::opt<bool> ProfileSampleAccurate(
140     "profile-sample-accurate", cl::Hidden, cl::init(false),
141     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
142              "callsite and function as having 0 samples. Otherwise, treat "
143              "un-sampled callsites and functions conservatively as unknown. "));
144 
145 static cl::opt<bool> ProfileSampleBlockAccurate(
146     "profile-sample-block-accurate", cl::Hidden, cl::init(false),
147     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
148              "branches and calls as having 0 samples. Otherwise, treat "
149              "them conservatively as unknown. "));
150 
151 static cl::opt<bool> ProfileAccurateForSymsInList(
152     "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
153     cl::init(true),
154     cl::desc("For symbols in profile symbol list, regard their profiles to "
155              "be accurate. It may be overriden by profile-sample-accurate. "));
156 
157 static cl::opt<bool> ProfileMergeInlinee(
158     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
159     cl::desc("Merge past inlinee's profile to outline version if sample "
160              "profile loader decided not to inline a call site. It will "
161              "only be enabled when top-down order of profile loading is "
162              "enabled. "));
163 
164 static cl::opt<bool> ProfileTopDownLoad(
165     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
166     cl::desc("Do profile annotation and inlining for functions in top-down "
167              "order of call graph during sample profile loading. It only "
168              "works for new pass manager. "));
169 
170 static cl::opt<bool>
171     UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
172                          cl::desc("Process functions in a top-down order "
173                                   "defined by the profiled call graph when "
174                                   "-sample-profile-top-down-load is on."));
175 
176 static cl::opt<bool> ProfileSizeInline(
177     "sample-profile-inline-size", cl::Hidden, cl::init(false),
178     cl::desc("Inline cold call sites in profile loader if it's beneficial "
179              "for code size."));
180 
181 cl::opt<int> ProfileInlineGrowthLimit(
182     "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
183     cl::desc("The size growth ratio limit for proirity-based sample profile "
184              "loader inlining."));
185 
186 cl::opt<int> ProfileInlineLimitMin(
187     "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
188     cl::desc("The lower bound of size growth limit for "
189              "proirity-based sample profile loader inlining."));
190 
191 cl::opt<int> ProfileInlineLimitMax(
192     "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
193     cl::desc("The upper bound of size growth limit for "
194              "proirity-based sample profile loader inlining."));
195 
196 cl::opt<int> SampleHotCallSiteThreshold(
197     "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
198     cl::desc("Hot callsite threshold for proirity-based sample profile loader "
199              "inlining."));
200 
201 cl::opt<int> SampleColdCallSiteThreshold(
202     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
203     cl::desc("Threshold for inlining cold callsites"));
204 
205 static cl::opt<unsigned> ProfileICPRelativeHotness(
206     "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
207     cl::desc(
208         "Relative hotness percentage threshold for indirect "
209         "call promotion in proirity-based sample profile loader inlining."));
210 
211 static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
212     "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
213     cl::desc(
214         "Skip relative hotness check for ICP up to given number of targets."));
215 
216 static cl::opt<bool> CallsitePrioritizedInline(
217     "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore,
218     cl::init(false),
219     cl::desc("Use call site prioritized inlining for sample profile loader."
220              "Currently only CSSPGO is supported."));
221 
222 static cl::opt<bool> UsePreInlinerDecision(
223     "sample-profile-use-preinliner", cl::Hidden, cl::ZeroOrMore,
224     cl::init(false),
225     cl::desc("Use the preinliner decisions stored in profile context."));
226 
227 static cl::opt<bool> AllowRecursiveInline(
228     "sample-profile-recursive-inline", cl::Hidden, cl::ZeroOrMore,
229     cl::init(false),
230     cl::desc("Allow sample loader inliner to inline recursive calls."));
231 
232 static cl::opt<std::string> ProfileInlineReplayFile(
233     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
234     cl::desc(
235         "Optimization remarks file containing inline remarks to be replayed "
236         "by inlining from sample profile loader."),
237     cl::Hidden);
238 
239 static cl::opt<ReplayInlineScope> ProfileInlineReplayScope(
240     "sample-profile-inline-replay-scope", cl::init(ReplayInlineScope::Function),
241     cl::values(clEnumValN(ReplayInlineScope::Function, "Function",
242                           "Replay on functions that have remarks associated "
243                           "with them (default)"),
244                clEnumValN(ReplayInlineScope::Module, "Module",
245                           "Replay on the entire module")),
246     cl::desc("Whether inline replay should be applied to the entire "
247              "Module or just the Functions (default) that are present as "
248              "callers in remarks during sample profile inlining."),
249     cl::Hidden);
250 
251 static cl::opt<unsigned>
252     MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
253                      cl::ZeroOrMore,
254                      cl::desc("Max number of promotions for a single indirect "
255                               "call callsite in sample profile loader"));
256 
257 static cl::opt<bool> OverwriteExistingWeights(
258     "overwrite-existing-weights", cl::Hidden, cl::init(false),
259     cl::desc("Ignore existing branch weights on IR and always overwrite."));
260 
261 namespace {
262 
263 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
264 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
265 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
266 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
267 using BlockEdgeMap =
268     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
269 
270 class GUIDToFuncNameMapper {
271 public:
272   GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
273                        DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
274       : CurrentReader(Reader), CurrentModule(M),
275         CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
276     if (!CurrentReader.useMD5())
277       return;
278 
279     for (const auto &F : CurrentModule) {
280       StringRef OrigName = F.getName();
281       CurrentGUIDToFuncNameMap.insert(
282           {Function::getGUID(OrigName), OrigName});
283 
284       // Local to global var promotion used by optimization like thinlto
285       // will rename the var and add suffix like ".llvm.xxx" to the
286       // original local name. In sample profile, the suffixes of function
287       // names are all stripped. Since it is possible that the mapper is
288       // built in post-thin-link phase and var promotion has been done,
289       // we need to add the substring of function name without the suffix
290       // into the GUIDToFuncNameMap.
291       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
292       if (CanonName != OrigName)
293         CurrentGUIDToFuncNameMap.insert(
294             {Function::getGUID(CanonName), CanonName});
295     }
296 
297     // Update GUIDToFuncNameMap for each function including inlinees.
298     SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
299   }
300 
301   ~GUIDToFuncNameMapper() {
302     if (!CurrentReader.useMD5())
303       return;
304 
305     CurrentGUIDToFuncNameMap.clear();
306 
307     // Reset GUIDToFuncNameMap for of each function as they're no
308     // longer valid at this point.
309     SetGUIDToFuncNameMapForAll(nullptr);
310   }
311 
312 private:
313   void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
314     std::queue<FunctionSamples *> FSToUpdate;
315     for (auto &IFS : CurrentReader.getProfiles()) {
316       FSToUpdate.push(&IFS.second);
317     }
318 
319     while (!FSToUpdate.empty()) {
320       FunctionSamples *FS = FSToUpdate.front();
321       FSToUpdate.pop();
322       FS->GUIDToFuncNameMap = Map;
323       for (const auto &ICS : FS->getCallsiteSamples()) {
324         const FunctionSamplesMap &FSMap = ICS.second;
325         for (auto &IFS : FSMap) {
326           FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
327           FSToUpdate.push(&FS);
328         }
329       }
330     }
331   }
332 
333   SampleProfileReader &CurrentReader;
334   Module &CurrentModule;
335   DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
336 };
337 
338 // Inline candidate used by iterative callsite prioritized inliner
339 struct InlineCandidate {
340   CallBase *CallInstr;
341   const FunctionSamples *CalleeSamples;
342   // Prorated callsite count, which will be used to guide inlining. For example,
343   // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
344   // copies will get their own distribution factors and their prorated counts
345   // will be used to decide if they should be inlined independently.
346   uint64_t CallsiteCount;
347   // Call site distribution factor to prorate the profile samples for a
348   // duplicated callsite. Default value is 1.0.
349   float CallsiteDistribution;
350 };
351 
352 // Inline candidate comparer using call site weight
353 struct CandidateComparer {
354   bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
355     if (LHS.CallsiteCount != RHS.CallsiteCount)
356       return LHS.CallsiteCount < RHS.CallsiteCount;
357 
358     const FunctionSamples *LCS = LHS.CalleeSamples;
359     const FunctionSamples *RCS = RHS.CalleeSamples;
360     assert(LCS && RCS && "Expect non-null FunctionSamples");
361 
362     // Tie breaker using number of samples try to favor smaller functions first
363     if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
364       return LCS->getBodySamples().size() > RCS->getBodySamples().size();
365 
366     // Tie breaker using GUID so we have stable/deterministic inlining order
367     return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
368   }
369 };
370 
371 using CandidateQueue =
372     PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
373                   CandidateComparer>;
374 
375 /// Sample profile pass.
376 ///
377 /// This pass reads profile data from the file specified by
378 /// -sample-profile-file and annotates every affected function with the
379 /// profile information found in that file.
380 class SampleProfileLoader final
381     : public SampleProfileLoaderBaseImpl<BasicBlock> {
382 public:
383   SampleProfileLoader(
384       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
385       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
386       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
387       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
388       : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)),
389         GetAC(std::move(GetAssumptionCache)),
390         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
391         LTOPhase(LTOPhase) {}
392 
393   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
394   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
395                    ProfileSummaryInfo *_PSI, CallGraph *CG);
396 
397 protected:
398   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
399   bool emitAnnotations(Function &F);
400   ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
401   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
402   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
403   const FunctionSamples *
404   findFunctionSamples(const Instruction &I) const override;
405   std::vector<const FunctionSamples *>
406   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
407   void findExternalInlineCandidate(const FunctionSamples *Samples,
408                                    DenseSet<GlobalValue::GUID> &InlinedGUIDs,
409                                    const StringMap<Function *> &SymbolMap,
410                                    uint64_t Threshold);
411   // Attempt to promote indirect call and also inline the promoted call
412   bool tryPromoteAndInlineCandidate(
413       Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
414       uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
415   bool inlineHotFunctions(Function &F,
416                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
417   InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
418   bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
419   bool
420   tryInlineCandidate(InlineCandidate &Candidate,
421                      SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
422   bool
423   inlineHotFunctionsWithPriority(Function &F,
424                                  DenseSet<GlobalValue::GUID> &InlinedGUIDs);
425   // Inline cold/small functions in addition to hot ones
426   bool shouldInlineColdCallee(CallBase &CallInst);
427   void emitOptimizationRemarksForInlineCandidates(
428       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
429       bool Hot);
430   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
431   std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
432   void generateMDProfMetadata(Function &F);
433 
434   /// Map from function name to Function *. Used to find the function from
435   /// the function name. If the function name contains suffix, additional
436   /// entry is added to map from the stripped name to the function if there
437   /// is one-to-one mapping.
438   StringMap<Function *> SymbolMap;
439 
440   std::function<AssumptionCache &(Function &)> GetAC;
441   std::function<TargetTransformInfo &(Function &)> GetTTI;
442   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
443 
444   /// Profile tracker for different context.
445   std::unique_ptr<SampleContextTracker> ContextTracker;
446 
447   /// Flag indicating whether input profile is context-sensitive
448   bool ProfileIsCS = false;
449 
450   /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
451   ///
452   /// We need to know the LTO phase because for example in ThinLTOPrelink
453   /// phase, in annotation, we should not promote indirect calls. Instead,
454   /// we will mark GUIDs that needs to be annotated to the function.
455   ThinOrFullLTOPhase LTOPhase;
456 
457   /// Profle Symbol list tells whether a function name appears in the binary
458   /// used to generate the current profile.
459   std::unique_ptr<ProfileSymbolList> PSL;
460 
461   /// Total number of samples collected in this profile.
462   ///
463   /// This is the sum of all the samples collected in all the functions executed
464   /// at runtime.
465   uint64_t TotalCollectedSamples = 0;
466 
467   // Information recorded when we declined to inline a call site
468   // because we have determined it is too cold is accumulated for
469   // each callee function. Initially this is just the entry count.
470   struct NotInlinedProfileInfo {
471     uint64_t entryCount;
472   };
473   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
474 
475   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
476   // all the function symbols defined or declared in current module.
477   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
478 
479   // All the Names used in FunctionSamples including outline function
480   // names, inline instance names and call target names.
481   StringSet<> NamesInProfile;
482 
483   // For symbol in profile symbol list, whether to regard their profiles
484   // to be accurate. It is mainly decided by existance of profile symbol
485   // list and -profile-accurate-for-symsinlist flag, but it can be
486   // overriden by -profile-sample-accurate or profile-sample-accurate
487   // attribute.
488   bool ProfAccForSymsInList;
489 
490   // External inline advisor used to replay inline decision from remarks.
491   std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
492 
493   // A pseudo probe helper to correlate the imported sample counts.
494   std::unique_ptr<PseudoProbeManager> ProbeManager;
495 };
496 
497 class SampleProfileLoaderLegacyPass : public ModulePass {
498 public:
499   // Class identification, replacement for typeinfo
500   static char ID;
501 
502   SampleProfileLoaderLegacyPass(
503       StringRef Name = SampleProfileFile,
504       ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None)
505       : ModulePass(ID), SampleLoader(
506                             Name, SampleProfileRemappingFile, LTOPhase,
507                             [&](Function &F) -> AssumptionCache & {
508                               return ACT->getAssumptionCache(F);
509                             },
510                             [&](Function &F) -> TargetTransformInfo & {
511                               return TTIWP->getTTI(F);
512                             },
513                             [&](Function &F) -> TargetLibraryInfo & {
514                               return TLIWP->getTLI(F);
515                             }) {
516     initializeSampleProfileLoaderLegacyPassPass(
517         *PassRegistry::getPassRegistry());
518   }
519 
520   void dump() { SampleLoader.dump(); }
521 
522   bool doInitialization(Module &M) override {
523     return SampleLoader.doInitialization(M);
524   }
525 
526   StringRef getPassName() const override { return "Sample profile pass"; }
527   bool runOnModule(Module &M) override;
528 
529   void getAnalysisUsage(AnalysisUsage &AU) const override {
530     AU.addRequired<AssumptionCacheTracker>();
531     AU.addRequired<TargetTransformInfoWrapperPass>();
532     AU.addRequired<TargetLibraryInfoWrapperPass>();
533     AU.addRequired<ProfileSummaryInfoWrapperPass>();
534   }
535 
536 private:
537   SampleProfileLoader SampleLoader;
538   AssumptionCacheTracker *ACT = nullptr;
539   TargetTransformInfoWrapperPass *TTIWP = nullptr;
540   TargetLibraryInfoWrapperPass *TLIWP = nullptr;
541 };
542 
543 } // end anonymous namespace
544 
545 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
546   if (FunctionSamples::ProfileIsProbeBased)
547     return getProbeWeight(Inst);
548 
549   const DebugLoc &DLoc = Inst.getDebugLoc();
550   if (!DLoc)
551     return std::error_code();
552 
553   // Ignore all intrinsics, phinodes and branch instructions.
554   // Branch and phinodes instruction usually contains debug info from sources
555   // outside of the residing basic block, thus we ignore them during annotation.
556   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
557     return std::error_code();
558 
559   // For non-CS profile, if a direct call/invoke instruction is inlined in
560   // profile (findCalleeFunctionSamples returns non-empty result), but not
561   // inlined here, it means that the inlined callsite has no sample, thus the
562   // call instruction should have 0 count.
563   // For CS profile, the callsite count of previously inlined callees is
564   // populated with the entry count of the callees.
565   if (!ProfileIsCS)
566     if (const auto *CB = dyn_cast<CallBase>(&Inst))
567       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
568         return 0;
569 
570   return getInstWeightImpl(Inst);
571 }
572 
573 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
574 // of non-probe instruction. So if all instructions of the BB give error_code,
575 // tell the inference algorithm to infer the BB weight.
576 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
577   assert(FunctionSamples::ProfileIsProbeBased &&
578          "Profile is not pseudo probe based");
579   Optional<PseudoProbe> Probe = extractProbe(Inst);
580   // Ignore the non-probe instruction. If none of the instruction in the BB is
581   // probe, we choose to infer the BB's weight.
582   if (!Probe)
583     return std::error_code();
584 
585   const FunctionSamples *FS = findFunctionSamples(Inst);
586   // If none of the instruction has FunctionSample, we choose to return zero
587   // value sample to indicate the BB is cold. This could happen when the
588   // instruction is from inlinee and no profile data is found.
589   // FIXME: This should not be affected by the source drift issue as 1) if the
590   // newly added function is top-level inliner, it won't match the CFG checksum
591   // in the function profile or 2) if it's the inlinee, the inlinee should have
592   // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
593   // we can improve it by adding a switch for profile-sample-block-accurate for
594   // block level counts in the future.
595   if (!FS)
596     return 0;
597 
598   // For non-CS profile, If a direct call/invoke instruction is inlined in
599   // profile (findCalleeFunctionSamples returns non-empty result), but not
600   // inlined here, it means that the inlined callsite has no sample, thus the
601   // call instruction should have 0 count.
602   // For CS profile, the callsite count of previously inlined callees is
603   // populated with the entry count of the callees.
604   if (!ProfileIsCS)
605     if (const auto *CB = dyn_cast<CallBase>(&Inst))
606       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
607         return 0;
608 
609   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
610   if (R) {
611     uint64_t Samples = R.get() * Probe->Factor;
612     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
613     if (FirstMark) {
614       ORE->emit([&]() {
615         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
616         Remark << "Applied " << ore::NV("NumSamples", Samples);
617         Remark << " samples from profile (ProbeId=";
618         Remark << ore::NV("ProbeId", Probe->Id);
619         Remark << ", Factor=";
620         Remark << ore::NV("Factor", Probe->Factor);
621         Remark << ", OriginalSamples=";
622         Remark << ore::NV("OriginalSamples", R.get());
623         Remark << ")";
624         return Remark;
625       });
626     }
627     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
628                       << " - weight: " << R.get() << " - factor: "
629                       << format("%0.2f", Probe->Factor) << ")\n");
630     return Samples;
631   }
632   return R;
633 }
634 
635 /// Get the FunctionSamples for a call instruction.
636 ///
637 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
638 /// instance in which that call instruction is calling to. It contains
639 /// all samples that resides in the inlined instance. We first find the
640 /// inlined instance in which the call instruction is from, then we
641 /// traverse its children to find the callsite with the matching
642 /// location.
643 ///
644 /// \param Inst Call/Invoke instruction to query.
645 ///
646 /// \returns The FunctionSamples pointer to the inlined instance.
647 const FunctionSamples *
648 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
649   const DILocation *DIL = Inst.getDebugLoc();
650   if (!DIL) {
651     return nullptr;
652   }
653 
654   StringRef CalleeName;
655   if (Function *Callee = Inst.getCalledFunction())
656     CalleeName = Callee->getName();
657 
658   if (ProfileIsCS)
659     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
660 
661   const FunctionSamples *FS = findFunctionSamples(Inst);
662   if (FS == nullptr)
663     return nullptr;
664 
665   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
666                                    CalleeName, Reader->getRemapper());
667 }
668 
669 /// Returns a vector of FunctionSamples that are the indirect call targets
670 /// of \p Inst. The vector is sorted by the total number of samples. Stores
671 /// the total call count of the indirect call in \p Sum.
672 std::vector<const FunctionSamples *>
673 SampleProfileLoader::findIndirectCallFunctionSamples(
674     const Instruction &Inst, uint64_t &Sum) const {
675   const DILocation *DIL = Inst.getDebugLoc();
676   std::vector<const FunctionSamples *> R;
677 
678   if (!DIL) {
679     return R;
680   }
681 
682   auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
683     assert(L && R && "Expect non-null FunctionSamples");
684     if (L->getEntrySamples() != R->getEntrySamples())
685       return L->getEntrySamples() > R->getEntrySamples();
686     return FunctionSamples::getGUID(L->getName()) <
687            FunctionSamples::getGUID(R->getName());
688   };
689 
690   if (ProfileIsCS) {
691     auto CalleeSamples =
692         ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
693     if (CalleeSamples.empty())
694       return R;
695 
696     // For CSSPGO, we only use target context profile's entry count
697     // as that already includes both inlined callee and non-inlined ones..
698     Sum = 0;
699     for (const auto *const FS : CalleeSamples) {
700       Sum += FS->getEntrySamples();
701       R.push_back(FS);
702     }
703     llvm::sort(R, FSCompare);
704     return R;
705   }
706 
707   const FunctionSamples *FS = findFunctionSamples(Inst);
708   if (FS == nullptr)
709     return R;
710 
711   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
712   auto T = FS->findCallTargetMapAt(CallSite);
713   Sum = 0;
714   if (T)
715     for (const auto &T_C : T.get())
716       Sum += T_C.second;
717   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
718     if (M->empty())
719       return R;
720     for (const auto &NameFS : *M) {
721       Sum += NameFS.second.getEntrySamples();
722       R.push_back(&NameFS.second);
723     }
724     llvm::sort(R, FSCompare);
725   }
726   return R;
727 }
728 
729 const FunctionSamples *
730 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
731   if (FunctionSamples::ProfileIsProbeBased) {
732     Optional<PseudoProbe> Probe = extractProbe(Inst);
733     if (!Probe)
734       return nullptr;
735   }
736 
737   const DILocation *DIL = Inst.getDebugLoc();
738   if (!DIL)
739     return Samples;
740 
741   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
742   if (it.second) {
743     if (ProfileIsCS)
744       it.first->second = ContextTracker->getContextSamplesFor(DIL);
745     else
746       it.first->second =
747           Samples->findFunctionSamples(DIL, Reader->getRemapper());
748   }
749   return it.first->second;
750 }
751 
752 /// Check whether the indirect call promotion history of \p Inst allows
753 /// the promotion for \p Candidate.
754 /// If the profile count for the promotion candidate \p Candidate is
755 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
756 /// for \p Inst. If we already have at least MaxNumPromotions
757 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
758 /// cannot promote for \p Inst anymore.
759 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
760   uint32_t NumVals = 0;
761   uint64_t TotalCount = 0;
762   std::unique_ptr<InstrProfValueData[]> ValueData =
763       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
764   bool Valid =
765       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
766                                ValueData.get(), NumVals, TotalCount, true);
767   // No valid value profile so no promoted targets have been recorded
768   // before. Ok to do ICP.
769   if (!Valid)
770     return true;
771 
772   unsigned NumPromoted = 0;
773   for (uint32_t I = 0; I < NumVals; I++) {
774     if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
775       continue;
776 
777     // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
778     // metadata, it means the candidate has been promoted for this
779     // indirect call.
780     if (ValueData[I].Value == Function::getGUID(Candidate))
781       return false;
782     NumPromoted++;
783     // If already have MaxNumPromotions promotion, don't do it anymore.
784     if (NumPromoted == MaxNumPromotions)
785       return false;
786   }
787   return true;
788 }
789 
790 /// Update indirect call target profile metadata for \p Inst.
791 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
792 /// If it is 0, it means updateIDTMetaData is used to mark a
793 /// certain target to be promoted already. If it is not zero,
794 /// we expect to use it to update the total count in the value profile.
795 static void
796 updateIDTMetaData(Instruction &Inst,
797                   const SmallVectorImpl<InstrProfValueData> &CallTargets,
798                   uint64_t Sum) {
799   uint32_t NumVals = 0;
800   // OldSum is the existing total count in the value profile data.
801   uint64_t OldSum = 0;
802   std::unique_ptr<InstrProfValueData[]> ValueData =
803       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
804   bool Valid =
805       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
806                                ValueData.get(), NumVals, OldSum, true);
807 
808   DenseMap<uint64_t, uint64_t> ValueCountMap;
809   if (Sum == 0) {
810     assert((CallTargets.size() == 1 &&
811             CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
812            "If sum is 0, assume only one element in CallTargets "
813            "with count being NOMORE_ICP_MAGICNUM");
814     // Initialize ValueCountMap with existing value profile data.
815     if (Valid) {
816       for (uint32_t I = 0; I < NumVals; I++)
817         ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
818     }
819     auto Pair =
820         ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
821     // If the target already exists in value profile, decrease the total
822     // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
823     if (!Pair.second) {
824       OldSum -= Pair.first->second;
825       Pair.first->second = NOMORE_ICP_MAGICNUM;
826     }
827     Sum = OldSum;
828   } else {
829     // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
830     // counts in the value profile.
831     if (Valid) {
832       for (uint32_t I = 0; I < NumVals; I++) {
833         if (ValueData[I].Count == NOMORE_ICP_MAGICNUM)
834           ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
835       }
836     }
837 
838     for (const auto &Data : CallTargets) {
839       auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
840       if (Pair.second)
841         continue;
842       // The target represented by Data.Value has already been promoted.
843       // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
844       // Sum by Data.Count.
845       assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
846       Sum -= Data.Count;
847     }
848   }
849 
850   SmallVector<InstrProfValueData, 8> NewCallTargets;
851   for (const auto &ValueCount : ValueCountMap) {
852     NewCallTargets.emplace_back(
853         InstrProfValueData{ValueCount.first, ValueCount.second});
854   }
855 
856   llvm::sort(NewCallTargets,
857              [](const InstrProfValueData &L, const InstrProfValueData &R) {
858                if (L.Count != R.Count)
859                  return L.Count > R.Count;
860                return L.Value > R.Value;
861              });
862 
863   uint32_t MaxMDCount =
864       std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
865   annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
866                     NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
867 }
868 
869 /// Attempt to promote indirect call and also inline the promoted call.
870 ///
871 /// \param F  Caller function.
872 /// \param Candidate  ICP and inline candidate.
873 /// \param SumOrigin  Original sum of target counts for indirect call before
874 ///                   promoting given candidate.
875 /// \param Sum        Prorated sum of remaining target counts for indirect call
876 ///                   after promoting given candidate.
877 /// \param InlinedCallSite  Output vector for new call sites exposed after
878 /// inlining.
879 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
880     Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
881     SmallVector<CallBase *, 8> *InlinedCallSite) {
882   auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
883   auto R = SymbolMap.find(CalleeFunctionName);
884   if (R == SymbolMap.end() || !R->getValue())
885     return false;
886 
887   auto &CI = *Candidate.CallInstr;
888   if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
889     return false;
890 
891   const char *Reason = "Callee function not available";
892   // R->getValue() != &F is to prevent promoting a recursive call.
893   // If it is a recursive call, we do not inline it as it could bloat
894   // the code exponentially. There is way to better handle this, e.g.
895   // clone the caller first, and inline the cloned caller if it is
896   // recursive. As llvm does not inline recursive calls, we will
897   // simply ignore it instead of handling it explicitly.
898   if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
899       R->getValue()->hasFnAttribute("use-sample-profile") &&
900       R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
901     // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
902     // in the value profile metadata so the target won't be promoted again.
903     SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
904         Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
905     updateIDTMetaData(CI, SortedCallTargets, 0);
906 
907     auto *DI = &pgo::promoteIndirectCall(
908         CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
909     if (DI) {
910       Sum -= Candidate.CallsiteCount;
911       // Do not prorate the indirect callsite distribution since the original
912       // distribution will be used to scale down non-promoted profile target
913       // counts later. By doing this we lose track of the real callsite count
914       // for the leftover indirect callsite as a trade off for accurate call
915       // target counts.
916       // TODO: Ideally we would have two separate factors, one for call site
917       // counts and one is used to prorate call target counts.
918       // Do not update the promoted direct callsite distribution at this
919       // point since the original distribution combined with the callee profile
920       // will be used to prorate callsites from the callee if inlined. Once not
921       // inlined, the direct callsite distribution should be prorated so that
922       // the it will reflect the real callsite counts.
923       Candidate.CallInstr = DI;
924       if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
925         bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
926         if (!Inlined) {
927           // Prorate the direct callsite distribution so that it reflects real
928           // callsite counts.
929           setProbeDistributionFactor(
930               *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
931         }
932         return Inlined;
933       }
934     }
935   } else {
936     LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
937                       << Candidate.CalleeSamples->getFuncName() << " because "
938                       << Reason << "\n");
939   }
940   return false;
941 }
942 
943 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
944   if (!ProfileSizeInline)
945     return false;
946 
947   Function *Callee = CallInst.getCalledFunction();
948   if (Callee == nullptr)
949     return false;
950 
951   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
952                                   GetAC, GetTLI);
953 
954   if (Cost.isNever())
955     return false;
956 
957   if (Cost.isAlways())
958     return true;
959 
960   return Cost.getCost() <= SampleColdCallSiteThreshold;
961 }
962 
963 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
964     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
965     bool Hot) {
966   for (auto I : Candidates) {
967     Function *CalledFunction = I->getCalledFunction();
968     if (CalledFunction) {
969       ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
970                                            I->getDebugLoc(), I->getParent())
971                 << "previous inlining reattempted for "
972                 << (Hot ? "hotness: '" : "size: '")
973                 << ore::NV("Callee", CalledFunction) << "' into '"
974                 << ore::NV("Caller", &F) << "'");
975     }
976   }
977 }
978 
979 void SampleProfileLoader::findExternalInlineCandidate(
980     const FunctionSamples *Samples, DenseSet<GlobalValue::GUID> &InlinedGUIDs,
981     const StringMap<Function *> &SymbolMap, uint64_t Threshold) {
982   assert(Samples && "expect non-null caller profile");
983 
984   // For AutoFDO profile, retrieve candidate profiles by walking over
985   // the nested inlinee profiles.
986   if (!ProfileIsCS) {
987     Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
988     return;
989   }
990 
991   ContextTrieNode *Caller =
992       ContextTracker->getContextFor(Samples->getContext());
993   std::queue<ContextTrieNode *> CalleeList;
994   CalleeList.push(Caller);
995   while (!CalleeList.empty()) {
996     ContextTrieNode *Node = CalleeList.front();
997     CalleeList.pop();
998     FunctionSamples *CalleeSample = Node->getFunctionSamples();
999     // For CSSPGO profile, retrieve candidate profile by walking over the
1000     // trie built for context profile. Note that also take call targets
1001     // even if callee doesn't have a corresponding context profile.
1002     if (!CalleeSample)
1003       continue;
1004 
1005     // If pre-inliner decision is used, honor that for importing as well.
1006     bool PreInline =
1007         UsePreInlinerDecision &&
1008         CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
1009     if (!PreInline && CalleeSample->getEntrySamples() < Threshold)
1010       continue;
1011 
1012     StringRef Name = CalleeSample->getFuncName();
1013     Function *Func = SymbolMap.lookup(Name);
1014     // Add to the import list only when it's defined out of module.
1015     if (!Func || Func->isDeclaration())
1016       InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeSample->getName()));
1017 
1018     // Import hot CallTargets, which may not be available in IR because full
1019     // profile annotation cannot be done until backend compilation in ThinLTO.
1020     for (const auto &BS : CalleeSample->getBodySamples())
1021       for (const auto &TS : BS.second.getCallTargets())
1022         if (TS.getValue() > Threshold) {
1023           StringRef CalleeName = CalleeSample->getFuncName(TS.getKey());
1024           const Function *Callee = SymbolMap.lookup(CalleeName);
1025           if (!Callee || Callee->isDeclaration())
1026             InlinedGUIDs.insert(FunctionSamples::getGUID(TS.getKey()));
1027         }
1028 
1029     // Import hot child context profile associted with callees. Note that this
1030     // may have some overlap with the call target loop above, but doing this
1031     // based child context profile again effectively allow us to use the max of
1032     // entry count and call target count to determine importing.
1033     for (auto &Child : Node->getAllChildContext()) {
1034       ContextTrieNode *CalleeNode = &Child.second;
1035       CalleeList.push(CalleeNode);
1036     }
1037   }
1038 }
1039 
1040 /// Iteratively inline hot callsites of a function.
1041 ///
1042 /// Iteratively traverse all callsites of the function \p F, and find if
1043 /// the corresponding inlined instance exists and is hot in profile. If
1044 /// it is hot enough, inline the callsites and adds new callsites of the
1045 /// callee into the caller. If the call is an indirect call, first promote
1046 /// it to direct call. Each indirect call is limited with a single target.
1047 ///
1048 /// \param F function to perform iterative inlining.
1049 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1050 ///     inlined in the profiled binary.
1051 ///
1052 /// \returns True if there is any inline happened.
1053 bool SampleProfileLoader::inlineHotFunctions(
1054     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1055   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1056   // Profile symbol list is ignored when profile-sample-accurate is on.
1057   assert((!ProfAccForSymsInList ||
1058           (!ProfileSampleAccurate &&
1059            !F.hasFnAttribute("profile-sample-accurate"))) &&
1060          "ProfAccForSymsInList should be false when profile-sample-accurate "
1061          "is enabled");
1062 
1063   DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1064   bool Changed = false;
1065   bool LocalChanged = true;
1066   while (LocalChanged) {
1067     LocalChanged = false;
1068     SmallVector<CallBase *, 10> CIS;
1069     for (auto &BB : F) {
1070       bool Hot = false;
1071       SmallVector<CallBase *, 10> AllCandidates;
1072       SmallVector<CallBase *, 10> ColdCandidates;
1073       for (auto &I : BB.getInstList()) {
1074         const FunctionSamples *FS = nullptr;
1075         if (auto *CB = dyn_cast<CallBase>(&I)) {
1076           if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
1077             assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1078                    "GUIDToFuncNameMap has to be populated");
1079             AllCandidates.push_back(CB);
1080             if (FS->getEntrySamples() > 0 || ProfileIsCS)
1081               LocalNotInlinedCallSites.try_emplace(CB, FS);
1082             if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1083               Hot = true;
1084             else if (shouldInlineColdCallee(*CB))
1085               ColdCandidates.push_back(CB);
1086           }
1087         }
1088       }
1089       if (Hot || ExternalInlineAdvisor) {
1090         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1091         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1092       } else {
1093         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1094         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1095       }
1096     }
1097     for (CallBase *I : CIS) {
1098       Function *CalledFunction = I->getCalledFunction();
1099       InlineCandidate Candidate = {
1100           I,
1101           LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I]
1102                                             : nullptr,
1103           0 /* dummy count */, 1.0 /* dummy distribution factor */};
1104       // Do not inline recursive calls.
1105       if (CalledFunction == &F)
1106         continue;
1107       if (I->isIndirectCall()) {
1108         uint64_t Sum;
1109         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1110           uint64_t SumOrigin = Sum;
1111           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1112             findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap,
1113                                         PSI->getOrCompHotCountThreshold());
1114             continue;
1115           }
1116           if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1117             continue;
1118 
1119           Candidate = {I, FS, FS->getEntrySamples(), 1.0};
1120           if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1121             LocalNotInlinedCallSites.erase(I);
1122             LocalChanged = true;
1123           }
1124         }
1125       } else if (CalledFunction && CalledFunction->getSubprogram() &&
1126                  !CalledFunction->isDeclaration()) {
1127         if (tryInlineCandidate(Candidate)) {
1128           LocalNotInlinedCallSites.erase(I);
1129           LocalChanged = true;
1130         }
1131       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1132         findExternalInlineCandidate(findCalleeFunctionSamples(*I), InlinedGUIDs,
1133                                     SymbolMap,
1134                                     PSI->getOrCompHotCountThreshold());
1135       }
1136     }
1137     Changed |= LocalChanged;
1138   }
1139 
1140   // For CS profile, profile for not inlined context will be merged when
1141   // base profile is being trieved
1142   if (ProfileIsCS)
1143     return Changed;
1144 
1145   // Accumulate not inlined callsite information into notInlinedSamples
1146   for (const auto &Pair : LocalNotInlinedCallSites) {
1147     CallBase *I = Pair.getFirst();
1148     Function *Callee = I->getCalledFunction();
1149     if (!Callee || Callee->isDeclaration())
1150       continue;
1151 
1152     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1153                                          I->getDebugLoc(), I->getParent())
1154               << "previous inlining not repeated: '"
1155               << ore::NV("Callee", Callee) << "' into '"
1156               << ore::NV("Caller", &F) << "'");
1157 
1158     ++NumCSNotInlined;
1159     const FunctionSamples *FS = Pair.getSecond();
1160     if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1161       continue;
1162     }
1163 
1164     if (ProfileMergeInlinee) {
1165       // A function call can be replicated by optimizations like callsite
1166       // splitting or jump threading and the replicates end up sharing the
1167       // sample nested callee profile instead of slicing the original inlinee's
1168       // profile. We want to do merge exactly once by filtering out callee
1169       // profiles with a non-zero head sample count.
1170       if (FS->getHeadSamples() == 0) {
1171         // Use entry samples as head samples during the merge, as inlinees
1172         // don't have head samples.
1173         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1174             FS->getEntrySamples());
1175 
1176         // Note that we have to do the merge right after processing function.
1177         // This allows OutlineFS's profile to be used for annotation during
1178         // top-down processing of functions' annotation.
1179         FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1180         OutlineFS->merge(*FS);
1181       }
1182     } else {
1183       auto pair =
1184           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1185       pair.first->second.entryCount += FS->getEntrySamples();
1186     }
1187   }
1188   return Changed;
1189 }
1190 
1191 bool SampleProfileLoader::tryInlineCandidate(
1192     InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1193 
1194   CallBase &CB = *Candidate.CallInstr;
1195   Function *CalledFunction = CB.getCalledFunction();
1196   assert(CalledFunction && "Expect a callee with definition");
1197   DebugLoc DLoc = CB.getDebugLoc();
1198   BasicBlock *BB = CB.getParent();
1199 
1200   InlineCost Cost = shouldInlineCandidate(Candidate);
1201   if (Cost.isNever()) {
1202     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1203               << "incompatible inlining");
1204     return false;
1205   }
1206 
1207   if (!Cost)
1208     return false;
1209 
1210   InlineFunctionInfo IFI(nullptr, GetAC);
1211   IFI.UpdateProfile = false;
1212   if (InlineFunction(CB, IFI).isSuccess()) {
1213     // Merge the attributes based on the inlining.
1214     AttributeFuncs::mergeAttributesForInlining(*BB->getParent(),
1215                                                *CalledFunction);
1216 
1217     // The call to InlineFunction erases I, so we can't pass it here.
1218     emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction,
1219                                *BB->getParent(), Cost, true, CSINLINE_DEBUG);
1220 
1221     // Now populate the list of newly exposed call sites.
1222     if (InlinedCallSites) {
1223       InlinedCallSites->clear();
1224       for (auto &I : IFI.InlinedCallSites)
1225         InlinedCallSites->push_back(I);
1226     }
1227 
1228     if (ProfileIsCS)
1229       ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1230     ++NumCSInlined;
1231 
1232     // Prorate inlined probes for a duplicated inlining callsite which probably
1233     // has a distribution less than 100%. Samples for an inlinee should be
1234     // distributed among the copies of the original callsite based on each
1235     // callsite's distribution factor for counts accuracy. Note that an inlined
1236     // probe may come with its own distribution factor if it has been duplicated
1237     // in the inlinee body. The two factor are multiplied to reflect the
1238     // aggregation of duplication.
1239     if (Candidate.CallsiteDistribution < 1) {
1240       for (auto &I : IFI.InlinedCallSites) {
1241         if (Optional<PseudoProbe> Probe = extractProbe(*I))
1242           setProbeDistributionFactor(*I, Probe->Factor *
1243                                              Candidate.CallsiteDistribution);
1244       }
1245       NumDuplicatedInlinesite++;
1246     }
1247 
1248     return true;
1249   }
1250   return false;
1251 }
1252 
1253 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1254                                              CallBase *CB) {
1255   assert(CB && "Expect non-null call instruction");
1256 
1257   if (isa<IntrinsicInst>(CB))
1258     return false;
1259 
1260   // Find the callee's profile. For indirect call, find hottest target profile.
1261   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1262   if (!CalleeSamples)
1263     return false;
1264 
1265   float Factor = 1.0;
1266   if (Optional<PseudoProbe> Probe = extractProbe(*CB))
1267     Factor = Probe->Factor;
1268 
1269   uint64_t CallsiteCount = 0;
1270   ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
1271   if (Weight)
1272     CallsiteCount = Weight.get();
1273   if (CalleeSamples)
1274     CallsiteCount = std::max(
1275         CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
1276 
1277   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1278   return true;
1279 }
1280 
1281 InlineCost
1282 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1283   std::unique_ptr<InlineAdvice> Advice = nullptr;
1284   if (ExternalInlineAdvisor) {
1285     Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr);
1286     if (Advice) {
1287       if (!Advice->isInliningRecommended()) {
1288         Advice->recordUnattemptedInlining();
1289         return InlineCost::getNever("not previously inlined");
1290       }
1291       Advice->recordInlining();
1292       return InlineCost::getAlways("previously inlined");
1293     }
1294   }
1295 
1296   // Adjust threshold based on call site hotness, only do this for callsite
1297   // prioritized inliner because otherwise cost-benefit check is done earlier.
1298   int SampleThreshold = SampleColdCallSiteThreshold;
1299   if (CallsitePrioritizedInline) {
1300     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1301       SampleThreshold = SampleHotCallSiteThreshold;
1302     else if (!ProfileSizeInline)
1303       return InlineCost::getNever("cold callsite");
1304   }
1305 
1306   Function *Callee = Candidate.CallInstr->getCalledFunction();
1307   assert(Callee && "Expect a definition for inline candidate of direct call");
1308 
1309   InlineParams Params = getInlineParams();
1310   // We will ignore the threshold from inline cost, so always get full cost.
1311   Params.ComputeFullInlineCost = true;
1312   Params.AllowRecursiveCall = AllowRecursiveInline;
1313   // Checks if there is anything in the reachable portion of the callee at
1314   // this callsite that makes this inlining potentially illegal. Need to
1315   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1316   // when cost exceeds threshold without checking all IRs in the callee.
1317   // The acutal cost does not matter because we only checks isNever() to
1318   // see if it is legal to inline the callsite.
1319   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1320                                   GetTTI(*Callee), GetAC, GetTLI);
1321 
1322   // Honor always inline and never inline from call analyzer
1323   if (Cost.isNever() || Cost.isAlways())
1324     return Cost;
1325 
1326   // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1327   // decisions based on hotness as well as accurate function byte sizes for
1328   // given context using function/inlinee sizes from previous build. It
1329   // stores the decision in profile, and also adjust/merge context profile
1330   // aiming at better context-sensitive post-inline profile quality, assuming
1331   // all inline decision estimates are going to be honored by compiler. Here
1332   // we replay that inline decision under `sample-profile-use-preinliner`.
1333   // Note that we don't need to handle negative decision from preinliner as
1334   // context profile for not inlined calls are merged by preinliner already.
1335   if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1336     // Once two node are merged due to promotion, we're losing some context
1337     // so the original context-sensitive preinliner decision should be ignored
1338     // for SyntheticContext.
1339     SampleContext &Context = Candidate.CalleeSamples->getContext();
1340     if (!Context.hasState(SyntheticContext) &&
1341         Context.hasAttribute(ContextShouldBeInlined))
1342       return InlineCost::getAlways("preinliner");
1343   }
1344 
1345   // For old FDO inliner, we inline the call site as long as cost is not
1346   // "Never". The cost-benefit check is done earlier.
1347   if (!CallsitePrioritizedInline) {
1348     return InlineCost::get(Cost.getCost(), INT_MAX);
1349   }
1350 
1351   // Otherwise only use the cost from call analyzer, but overwite threshold with
1352   // Sample PGO threshold.
1353   return InlineCost::get(Cost.getCost(), SampleThreshold);
1354 }
1355 
1356 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1357     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1358   assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now");
1359 
1360   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1361   // Profile symbol list is ignored when profile-sample-accurate is on.
1362   assert((!ProfAccForSymsInList ||
1363           (!ProfileSampleAccurate &&
1364            !F.hasFnAttribute("profile-sample-accurate"))) &&
1365          "ProfAccForSymsInList should be false when profile-sample-accurate "
1366          "is enabled");
1367 
1368   // Populating worklist with initial call sites from root inliner, along
1369   // with call site weights.
1370   CandidateQueue CQueue;
1371   InlineCandidate NewCandidate;
1372   for (auto &BB : F) {
1373     for (auto &I : BB.getInstList()) {
1374       auto *CB = dyn_cast<CallBase>(&I);
1375       if (!CB)
1376         continue;
1377       if (getInlineCandidate(&NewCandidate, CB))
1378         CQueue.push(NewCandidate);
1379     }
1380   }
1381 
1382   // Cap the size growth from profile guided inlining. This is needed even
1383   // though cost of each inline candidate already accounts for callee size,
1384   // because with top-down inlining, we can grow inliner size significantly
1385   // with large number of smaller inlinees each pass the cost check.
1386   assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1387          "Max inline size limit should not be smaller than min inline size "
1388          "limit.");
1389   unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1390   SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1391   SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1392   if (ExternalInlineAdvisor)
1393     SizeLimit = std::numeric_limits<unsigned>::max();
1394 
1395   // Perform iterative BFS call site prioritized inlining
1396   bool Changed = false;
1397   while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1398     InlineCandidate Candidate = CQueue.top();
1399     CQueue.pop();
1400     CallBase *I = Candidate.CallInstr;
1401     Function *CalledFunction = I->getCalledFunction();
1402 
1403     if (CalledFunction == &F)
1404       continue;
1405     if (I->isIndirectCall()) {
1406       uint64_t Sum = 0;
1407       auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1408       uint64_t SumOrigin = Sum;
1409       Sum *= Candidate.CallsiteDistribution;
1410       unsigned ICPCount = 0;
1411       for (const auto *FS : CalleeSamples) {
1412         // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1413         if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1414           findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap,
1415                                       PSI->getOrCompHotCountThreshold());
1416           continue;
1417         }
1418         uint64_t EntryCountDistributed =
1419             FS->getEntrySamples() * Candidate.CallsiteDistribution;
1420         // In addition to regular inline cost check, we also need to make sure
1421         // ICP isn't introducing excessive speculative checks even if individual
1422         // target looks beneficial to promote and inline. That means we should
1423         // only do ICP when there's a small number dominant targets.
1424         if (ICPCount >= ProfileICPRelativeHotnessSkip &&
1425             EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
1426           break;
1427         // TODO: Fix CallAnalyzer to handle all indirect calls.
1428         // For indirect call, we don't run CallAnalyzer to get InlineCost
1429         // before actual inlining. This is because we could see two different
1430         // types from the same definition, which makes CallAnalyzer choke as
1431         // it's expecting matching parameter type on both caller and callee
1432         // side. See example from PR18962 for the triggering cases (the bug was
1433         // fixed, but we generate different types).
1434         if (!PSI->isHotCount(EntryCountDistributed))
1435           break;
1436         SmallVector<CallBase *, 8> InlinedCallSites;
1437         // Attach function profile for promoted indirect callee, and update
1438         // call site count for the promoted inline candidate too.
1439         Candidate = {I, FS, EntryCountDistributed,
1440                      Candidate.CallsiteDistribution};
1441         if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1442                                          &InlinedCallSites)) {
1443           for (auto *CB : InlinedCallSites) {
1444             if (getInlineCandidate(&NewCandidate, CB))
1445               CQueue.emplace(NewCandidate);
1446           }
1447           ICPCount++;
1448           Changed = true;
1449         }
1450       }
1451     } else if (CalledFunction && CalledFunction->getSubprogram() &&
1452                !CalledFunction->isDeclaration()) {
1453       SmallVector<CallBase *, 8> InlinedCallSites;
1454       if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1455         for (auto *CB : InlinedCallSites) {
1456           if (getInlineCandidate(&NewCandidate, CB))
1457             CQueue.emplace(NewCandidate);
1458         }
1459         Changed = true;
1460       }
1461     } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1462       findExternalInlineCandidate(Candidate.CalleeSamples, InlinedGUIDs,
1463                                   SymbolMap, PSI->getOrCompHotCountThreshold());
1464     }
1465   }
1466 
1467   if (!CQueue.empty()) {
1468     if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1469       ++NumCSInlinedHitMaxLimit;
1470     else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1471       ++NumCSInlinedHitMinLimit;
1472     else
1473       ++NumCSInlinedHitGrowthLimit;
1474   }
1475 
1476   return Changed;
1477 }
1478 
1479 /// Returns the sorted CallTargetMap \p M by count in descending order.
1480 static SmallVector<InstrProfValueData, 2>
1481 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
1482   SmallVector<InstrProfValueData, 2> R;
1483   for (const auto &I : SampleRecord::SortCallTargets(M)) {
1484     R.emplace_back(
1485         InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1486   }
1487   return R;
1488 }
1489 
1490 // Generate MD_prof metadata for every branch instruction using the
1491 // edge weights computed during propagation.
1492 void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1493   // Generate MD_prof metadata for every branch instruction using the
1494   // edge weights computed during propagation.
1495   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1496   LLVMContext &Ctx = F.getContext();
1497   MDBuilder MDB(Ctx);
1498   for (auto &BI : F) {
1499     BasicBlock *BB = &BI;
1500 
1501     if (BlockWeights[BB]) {
1502       for (auto &I : BB->getInstList()) {
1503         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1504           continue;
1505         if (!cast<CallBase>(I).getCalledFunction()) {
1506           const DebugLoc &DLoc = I.getDebugLoc();
1507           if (!DLoc)
1508             continue;
1509           const DILocation *DIL = DLoc;
1510           const FunctionSamples *FS = findFunctionSamples(I);
1511           if (!FS)
1512             continue;
1513           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1514           auto T = FS->findCallTargetMapAt(CallSite);
1515           if (!T || T.get().empty())
1516             continue;
1517           if (FunctionSamples::ProfileIsProbeBased) {
1518             // Prorate the callsite counts based on the pre-ICP distribution
1519             // factor to reflect what is already done to the callsite before
1520             // ICP, such as calliste cloning.
1521             if (Optional<PseudoProbe> Probe = extractProbe(I)) {
1522               if (Probe->Factor < 1)
1523                 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1524             }
1525           }
1526           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1527               GetSortedValueDataFromCallTargets(T.get());
1528           uint64_t Sum = 0;
1529           for (const auto &C : T.get())
1530             Sum += C.second;
1531           // With CSSPGO all indirect call targets are counted torwards the
1532           // original indirect call site in the profile, including both
1533           // inlined and non-inlined targets.
1534           if (!FunctionSamples::ProfileIsCS) {
1535             if (const FunctionSamplesMap *M =
1536                     FS->findFunctionSamplesMapAt(CallSite)) {
1537               for (const auto &NameFS : *M)
1538                 Sum += NameFS.second.getEntrySamples();
1539             }
1540           }
1541           if (Sum)
1542             updateIDTMetaData(I, SortedCallTargets, Sum);
1543           else if (OverwriteExistingWeights)
1544             I.setMetadata(LLVMContext::MD_prof, nullptr);
1545         } else if (!isa<IntrinsicInst>(&I)) {
1546           I.setMetadata(LLVMContext::MD_prof,
1547                         MDB.createBranchWeights(
1548                             {static_cast<uint32_t>(BlockWeights[BB])}));
1549         }
1550       }
1551     } else if (OverwriteExistingWeights || ProfileSampleBlockAccurate) {
1552       // Set profile metadata (possibly annotated by LTO prelink) to zero or
1553       // clear it for cold code.
1554       for (auto &I : BB->getInstList()) {
1555         if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1556           if (cast<CallBase>(I).isIndirectCall())
1557             I.setMetadata(LLVMContext::MD_prof, nullptr);
1558           else
1559             I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0));
1560         }
1561       }
1562     }
1563 
1564     Instruction *TI = BB->getTerminator();
1565     if (TI->getNumSuccessors() == 1)
1566       continue;
1567     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
1568         !isa<IndirectBrInst>(TI))
1569       continue;
1570 
1571     DebugLoc BranchLoc = TI->getDebugLoc();
1572     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1573                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1574                                       : Twine("<UNKNOWN LOCATION>"))
1575                       << ".\n");
1576     SmallVector<uint32_t, 4> Weights;
1577     uint32_t MaxWeight = 0;
1578     Instruction *MaxDestInst;
1579     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1580       BasicBlock *Succ = TI->getSuccessor(I);
1581       Edge E = std::make_pair(BB, Succ);
1582       uint64_t Weight = EdgeWeights[E];
1583       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1584       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1585       // if needed. Sample counts in profiles are 64-bit unsigned values,
1586       // but internally branch weights are expressed as 32-bit values.
1587       if (Weight > std::numeric_limits<uint32_t>::max()) {
1588         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1589         Weight = std::numeric_limits<uint32_t>::max();
1590       }
1591       // Weight is added by one to avoid propagation errors introduced by
1592       // 0 weights.
1593       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1594       if (Weight != 0) {
1595         if (Weight > MaxWeight) {
1596           MaxWeight = Weight;
1597           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1598         }
1599       }
1600     }
1601 
1602     uint64_t TempWeight;
1603     // Only set weights if there is at least one non-zero weight.
1604     // In any other case, let the analyzer set weights.
1605     // Do not set weights if the weights are present unless under
1606     // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1607     // twice. If the first annotation already set the weights, the second pass
1608     // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1609     // weight should have their existing metadata (possibly annotated by LTO
1610     // prelink) cleared.
1611     if (MaxWeight > 0 &&
1612         (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
1613       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1614       TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1615       ORE->emit([&]() {
1616         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1617                << "most popular destination for conditional branches at "
1618                << ore::NV("CondBranchesLoc", BranchLoc);
1619       });
1620     } else {
1621       if (OverwriteExistingWeights) {
1622         TI->setMetadata(LLVMContext::MD_prof, nullptr);
1623         LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1624       } else {
1625         LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1626       }
1627     }
1628   }
1629 }
1630 
1631 /// Once all the branch weights are computed, we emit the MD_prof
1632 /// metadata on BB using the computed values for each of its branches.
1633 ///
1634 /// \param F The function to query.
1635 ///
1636 /// \returns true if \p F was modified. Returns false, otherwise.
1637 bool SampleProfileLoader::emitAnnotations(Function &F) {
1638   bool Changed = false;
1639 
1640   if (FunctionSamples::ProfileIsProbeBased) {
1641     if (!ProbeManager->profileIsValid(F, *Samples)) {
1642       LLVM_DEBUG(
1643           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1644                  << F.getName());
1645       ++NumMismatchedProfile;
1646       return false;
1647     }
1648     ++NumMatchedProfile;
1649   } else {
1650     if (getFunctionLoc(F) == 0)
1651       return false;
1652 
1653     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1654                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1655   }
1656 
1657   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1658   if (ProfileIsCS && CallsitePrioritizedInline)
1659     Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1660   else
1661     Changed |= inlineHotFunctions(F, InlinedGUIDs);
1662 
1663   Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1664 
1665   if (Changed)
1666     generateMDProfMetadata(F);
1667 
1668   emitCoverageRemarks(F);
1669   return Changed;
1670 }
1671 
1672 char SampleProfileLoaderLegacyPass::ID = 0;
1673 
1674 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1675                       "Sample Profile loader", false, false)
1676 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1677 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1678 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1679 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1680 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1681                     "Sample Profile loader", false, false)
1682 
1683 std::unique_ptr<ProfiledCallGraph>
1684 SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) {
1685   std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1686   if (ProfileIsCS)
1687     ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1688   else
1689     ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1690 
1691   // Add all functions into the profiled call graph even if they are not in
1692   // the profile. This makes sure functions missing from the profile still
1693   // gets a chance to be processed.
1694   for (auto &Node : CG) {
1695     const auto *F = Node.first;
1696     if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
1697       continue;
1698     ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F));
1699   }
1700 
1701   return ProfiledCG;
1702 }
1703 
1704 std::vector<Function *>
1705 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1706   std::vector<Function *> FunctionOrderList;
1707   FunctionOrderList.reserve(M.size());
1708 
1709   if (!ProfileTopDownLoad && UseProfiledCallGraph)
1710     errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1711               "together with -sample-profile-top-down-load.\n";
1712 
1713   if (!ProfileTopDownLoad || CG == nullptr) {
1714     if (ProfileMergeInlinee) {
1715       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1716       // because the profile for a function may be used for the profile
1717       // annotation of its outline copy before the profile merging of its
1718       // non-inlined inline instances, and that is not the way how
1719       // ProfileMergeInlinee is supposed to work.
1720       ProfileMergeInlinee = false;
1721     }
1722 
1723     for (Function &F : M)
1724       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1725         FunctionOrderList.push_back(&F);
1726     return FunctionOrderList;
1727   }
1728 
1729   assert(&CG->getModule() == &M);
1730 
1731   if (UseProfiledCallGraph ||
1732       (ProfileIsCS && !UseProfiledCallGraph.getNumOccurrences())) {
1733     // Use profiled call edges to augment the top-down order. There are cases
1734     // that the top-down order computed based on the static call graph doesn't
1735     // reflect real execution order. For example
1736     //
1737     // 1. Incomplete static call graph due to unknown indirect call targets.
1738     //    Adjusting the order by considering indirect call edges from the
1739     //    profile can enable the inlining of indirect call targets by allowing
1740     //    the caller processed before them.
1741     // 2. Mutual call edges in an SCC. The static processing order computed for
1742     //    an SCC may not reflect the call contexts in the context-sensitive
1743     //    profile, thus may cause potential inlining to be overlooked. The
1744     //    function order in one SCC is being adjusted to a top-down order based
1745     //    on the profile to favor more inlining. This is only a problem with CS
1746     //    profile.
1747     // 3. Transitive indirect call edges due to inlining. When a callee function
1748     //    (say B) is inlined into into a caller function (say A) in LTO prelink,
1749     //    every call edge originated from the callee B will be transferred to
1750     //    the caller A. If any transferred edge (say A->C) is indirect, the
1751     //    original profiled indirect edge B->C, even if considered, would not
1752     //    enforce a top-down order from the caller A to the potential indirect
1753     //    call target C in LTO postlink since the inlined callee B is gone from
1754     //    the static call graph.
1755     // 4. #3 can happen even for direct call targets, due to functions defined
1756     //    in header files. A header function (say A), when included into source
1757     //    files, is defined multiple times but only one definition survives due
1758     //    to ODR. Therefore, the LTO prelink inlining done on those dropped
1759     //    definitions can be useless based on a local file scope. More
1760     //    importantly, the inlinee (say B), once fully inlined to a
1761     //    to-be-dropped A, will have no profile to consume when its outlined
1762     //    version is compiled. This can lead to a profile-less prelink
1763     //    compilation for the outlined version of B which may be called from
1764     //    external modules. while this isn't easy to fix, we rely on the
1765     //    postlink AutoFDO pipeline to optimize B. Since the survived copy of
1766     //    the A can be inlined in its local scope in prelink, it may not exist
1767     //    in the merged IR in postlink, and we'll need the profiled call edges
1768     //    to enforce a top-down order for the rest of the functions.
1769     //
1770     // Considering those cases, a profiled call graph completely independent of
1771     // the static call graph is constructed based on profile data, where
1772     // function objects are not even needed to handle case #3 and case 4.
1773     //
1774     // Note that static callgraph edges are completely ignored since they
1775     // can be conflicting with profiled edges for cyclic SCCs and may result in
1776     // an SCC order incompatible with profile-defined one. Using strictly
1777     // profile order ensures a maximum inlining experience. On the other hand,
1778     // static call edges are not so important when they don't correspond to a
1779     // context in the profile.
1780 
1781     std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG);
1782     scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1783     while (!CGI.isAtEnd()) {
1784       for (ProfiledCallGraphNode *Node : *CGI) {
1785         Function *F = SymbolMap.lookup(Node->Name);
1786         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1787           FunctionOrderList.push_back(F);
1788       }
1789       ++CGI;
1790     }
1791   } else {
1792     scc_iterator<CallGraph *> CGI = scc_begin(CG);
1793     while (!CGI.isAtEnd()) {
1794       for (CallGraphNode *Node : *CGI) {
1795         auto *F = Node->getFunction();
1796         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1797           FunctionOrderList.push_back(F);
1798       }
1799       ++CGI;
1800     }
1801   }
1802 
1803   LLVM_DEBUG({
1804     dbgs() << "Function processing order:\n";
1805     for (auto F : reverse(FunctionOrderList)) {
1806       dbgs() << F->getName() << "\n";
1807     }
1808   });
1809 
1810   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1811   return FunctionOrderList;
1812 }
1813 
1814 bool SampleProfileLoader::doInitialization(Module &M,
1815                                            FunctionAnalysisManager *FAM) {
1816   auto &Ctx = M.getContext();
1817 
1818   auto ReaderOrErr = SampleProfileReader::create(
1819       Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename);
1820   if (std::error_code EC = ReaderOrErr.getError()) {
1821     std::string Msg = "Could not open profile: " + EC.message();
1822     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1823     return false;
1824   }
1825   Reader = std::move(ReaderOrErr.get());
1826   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1827   // set module before reading the profile so reader may be able to only
1828   // read the function profiles which are used by the current module.
1829   Reader->setModule(&M);
1830   if (std::error_code EC = Reader->read()) {
1831     std::string Msg = "profile reading failed: " + EC.message();
1832     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1833     return false;
1834   }
1835 
1836   PSL = Reader->getProfileSymbolList();
1837 
1838   // While profile-sample-accurate is on, ignore symbol list.
1839   ProfAccForSymsInList =
1840       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1841   if (ProfAccForSymsInList) {
1842     NamesInProfile.clear();
1843     if (auto NameTable = Reader->getNameTable())
1844       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1845     CoverageTracker.setProfAccForSymsInList(true);
1846   }
1847 
1848   if (FAM && !ProfileInlineReplayFile.empty()) {
1849     ExternalInlineAdvisor = getReplayInlineAdvisor(
1850         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
1851         ProfileInlineReplayScope, /*EmitRemarks=*/false);
1852   }
1853 
1854   // Apply tweaks if context-sensitive profile is available.
1855   if (Reader->profileIsCS()) {
1856     ProfileIsCS = true;
1857     FunctionSamples::ProfileIsCS = true;
1858 
1859     // Enable priority-base inliner and size inline by default for CSSPGO.
1860     if (!ProfileSizeInline.getNumOccurrences())
1861       ProfileSizeInline = true;
1862     if (!CallsitePrioritizedInline.getNumOccurrences())
1863       CallsitePrioritizedInline = true;
1864 
1865     // For CSSPGO, use preinliner decision by default when available.
1866     if (!UsePreInlinerDecision.getNumOccurrences())
1867       UsePreInlinerDecision = true;
1868 
1869     // For CSSPGO, we also allow recursive inline to best use context profile.
1870     if (!AllowRecursiveInline.getNumOccurrences())
1871       AllowRecursiveInline = true;
1872 
1873     // Enable iterative-BFI by default for CSSPGO.
1874     if (!UseIterativeBFIInference.getNumOccurrences())
1875       UseIterativeBFIInference = true;
1876 
1877     // Tracker for profiles under different context
1878     ContextTracker = std::make_unique<SampleContextTracker>(
1879         Reader->getProfiles(), &GUIDToFuncNameMap);
1880   }
1881 
1882   // Load pseudo probe descriptors for probe-based function samples.
1883   if (Reader->profileIsProbeBased()) {
1884     ProbeManager = std::make_unique<PseudoProbeManager>(M);
1885     if (!ProbeManager->moduleIsProbed(M)) {
1886       const char *Msg =
1887           "Pseudo-probe-based profile requires SampleProfileProbePass";
1888       Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1889       return false;
1890     }
1891   }
1892 
1893   return true;
1894 }
1895 
1896 ModulePass *llvm::createSampleProfileLoaderPass() {
1897   return new SampleProfileLoaderLegacyPass();
1898 }
1899 
1900 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1901   return new SampleProfileLoaderLegacyPass(Name);
1902 }
1903 
1904 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1905                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
1906   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1907 
1908   PSI = _PSI;
1909   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1910     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1911                         ProfileSummary::PSK_Sample);
1912     PSI->refresh();
1913   }
1914   // Compute the total number of samples collected in this profile.
1915   for (const auto &I : Reader->getProfiles())
1916     TotalCollectedSamples += I.second.getTotalSamples();
1917 
1918   auto Remapper = Reader->getRemapper();
1919   // Populate the symbol map.
1920   for (const auto &N_F : M.getValueSymbolTable()) {
1921     StringRef OrigName = N_F.getKey();
1922     Function *F = dyn_cast<Function>(N_F.getValue());
1923     if (F == nullptr || OrigName.empty())
1924       continue;
1925     SymbolMap[OrigName] = F;
1926     StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
1927     if (OrigName != NewName && !NewName.empty()) {
1928       auto r = SymbolMap.insert(std::make_pair(NewName, F));
1929       // Failiing to insert means there is already an entry in SymbolMap,
1930       // thus there are multiple functions that are mapped to the same
1931       // stripped name. In this case of name conflicting, set the value
1932       // to nullptr to avoid confusion.
1933       if (!r.second)
1934         r.first->second = nullptr;
1935       OrigName = NewName;
1936     }
1937     // Insert the remapped names into SymbolMap.
1938     if (Remapper) {
1939       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1940         if (*MapName != OrigName && !MapName->empty())
1941           SymbolMap.insert(std::make_pair(*MapName, F));
1942       }
1943     }
1944   }
1945   assert(SymbolMap.count(StringRef()) == 0 &&
1946          "No empty StringRef should be added in SymbolMap");
1947 
1948   bool retval = false;
1949   for (auto F : buildFunctionOrder(M, CG)) {
1950     assert(!F->isDeclaration());
1951     clearFunctionData();
1952     retval |= runOnFunction(*F, AM);
1953   }
1954 
1955   // Account for cold calls not inlined....
1956   if (!ProfileIsCS)
1957     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
1958          notInlinedCallInfo)
1959       updateProfileCallee(pair.first, pair.second.entryCount);
1960 
1961   return retval;
1962 }
1963 
1964 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1965   ACT = &getAnalysis<AssumptionCacheTracker>();
1966   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1967   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
1968   ProfileSummaryInfo *PSI =
1969       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1970   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
1971 }
1972 
1973 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1974   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
1975   DILocation2SampleMap.clear();
1976   // By default the entry count is initialized to -1, which will be treated
1977   // conservatively by getEntryCount as the same as unknown (None). This is
1978   // to avoid newly added code to be treated as cold. If we have samples
1979   // this will be overwritten in emitAnnotations.
1980   uint64_t initialEntryCount = -1;
1981 
1982   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
1983   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
1984     // initialize all the function entry counts to 0. It means all the
1985     // functions without profile will be regarded as cold.
1986     initialEntryCount = 0;
1987     // profile-sample-accurate is a user assertion which has a higher precedence
1988     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
1989     ProfAccForSymsInList = false;
1990   }
1991   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
1992 
1993   // PSL -- profile symbol list include all the symbols in sampled binary.
1994   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
1995   // old functions without samples being cold, without having to worry
1996   // about new and hot functions being mistakenly treated as cold.
1997   if (ProfAccForSymsInList) {
1998     // Initialize the entry count to 0 for functions in the list.
1999     if (PSL->contains(F.getName()))
2000       initialEntryCount = 0;
2001 
2002     // Function in the symbol list but without sample will be regarded as
2003     // cold. To minimize the potential negative performance impact it could
2004     // have, we want to be a little conservative here saying if a function
2005     // shows up in the profile, no matter as outline function, inline instance
2006     // or call targets, treat the function as not being cold. This will handle
2007     // the cases such as most callsites of a function are inlined in sampled
2008     // binary but not inlined in current build (because of source code drift,
2009     // imprecise debug information, or the callsites are all cold individually
2010     // but not cold accumulatively...), so the outline function showing up as
2011     // cold in sampled binary will actually not be cold after current build.
2012     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2013     if (NamesInProfile.count(CanonName))
2014       initialEntryCount = -1;
2015   }
2016 
2017   // Initialize entry count when the function has no existing entry
2018   // count value.
2019   if (!F.getEntryCount().hasValue())
2020     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
2021   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
2022   if (AM) {
2023     auto &FAM =
2024         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2025             .getManager();
2026     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2027   } else {
2028     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2029     ORE = OwnedORE.get();
2030   }
2031 
2032   if (ProfileIsCS)
2033     Samples = ContextTracker->getBaseSamplesFor(F);
2034   else
2035     Samples = Reader->getSamplesFor(F);
2036 
2037   if (Samples && !Samples->empty())
2038     return emitAnnotations(F);
2039   return false;
2040 }
2041 
2042 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2043                                                ModuleAnalysisManager &AM) {
2044   FunctionAnalysisManager &FAM =
2045       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2046 
2047   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2048     return FAM.getResult<AssumptionAnalysis>(F);
2049   };
2050   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2051     return FAM.getResult<TargetIRAnalysis>(F);
2052   };
2053   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2054     return FAM.getResult<TargetLibraryAnalysis>(F);
2055   };
2056 
2057   SampleProfileLoader SampleLoader(
2058       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
2059       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2060                                        : ProfileRemappingFileName,
2061       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
2062 
2063   if (!SampleLoader.doInitialization(M, &FAM))
2064     return PreservedAnalyses::all();
2065 
2066   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2067   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2068   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2069     return PreservedAnalyses::all();
2070 
2071   return PreservedAnalyses::none();
2072 }
2073