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