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