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