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