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