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