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