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