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