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