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