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   // For non-CS profile, if a direct call/invoke instruction is inlined in
524   // profile (findCalleeFunctionSamples returns non-empty result), but not
525   // inlined here, it means that the inlined callsite has no sample, thus the
526   // call instruction should have 0 count.
527   // For CS profile, the callsite count of previously inlined callees is
528   // populated with the entry count of the callees.
529   if (!ProfileIsCS)
530     if (const auto *CB = dyn_cast<CallBase>(&Inst))
531       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
532         return 0;
533 
534   return getInstWeightImpl(Inst);
535 }
536 
537 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
538   assert(FunctionSamples::ProfileIsProbeBased &&
539          "Profile is not pseudo probe based");
540   Optional<PseudoProbe> Probe = extractProbe(Inst);
541   if (!Probe)
542     return std::error_code();
543 
544   // Ignore danling probes since they are logically deleted and should not
545   // consume any profile samples.
546   if (Probe->isDangling())
547     return std::error_code();
548 
549   const FunctionSamples *FS = findFunctionSamples(Inst);
550   if (!FS)
551     return std::error_code();
552 
553   // For non-CS profile, If a direct call/invoke instruction is inlined in
554   // profile (findCalleeFunctionSamples returns non-empty result), but not
555   // inlined here, it means that the inlined callsite has no sample, thus the
556   // call instruction should have 0 count.
557   // For CS profile, the callsite count of previously inlined callees is
558   // populated with the entry count of the callees.
559   if (!ProfileIsCS)
560     if (const auto *CB = dyn_cast<CallBase>(&Inst))
561       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
562         return 0;
563 
564   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
565   if (R) {
566     uint64_t Samples = R.get() * Probe->Factor;
567     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
568     if (FirstMark) {
569       ORE->emit([&]() {
570         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
571         Remark << "Applied " << ore::NV("NumSamples", Samples);
572         Remark << " samples from profile (ProbeId=";
573         Remark << ore::NV("ProbeId", Probe->Id);
574         Remark << ", Factor=";
575         Remark << ore::NV("Factor", Probe->Factor);
576         Remark << ", OriginalSamples=";
577         Remark << ore::NV("OriginalSamples", R.get());
578         Remark << ")";
579         return Remark;
580       });
581     }
582     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
583                       << " - weight: " << R.get() << " - factor: "
584                       << format("%0.2f", Probe->Factor) << ")\n");
585     return Samples;
586   }
587   return R;
588 }
589 
590 /// Get the FunctionSamples for a call instruction.
591 ///
592 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
593 /// instance in which that call instruction is calling to. It contains
594 /// all samples that resides in the inlined instance. We first find the
595 /// inlined instance in which the call instruction is from, then we
596 /// traverse its children to find the callsite with the matching
597 /// location.
598 ///
599 /// \param Inst Call/Invoke instruction to query.
600 ///
601 /// \returns The FunctionSamples pointer to the inlined instance.
602 const FunctionSamples *
603 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
604   const DILocation *DIL = Inst.getDebugLoc();
605   if (!DIL) {
606     return nullptr;
607   }
608 
609   StringRef CalleeName;
610   if (Function *Callee = Inst.getCalledFunction())
611     CalleeName = FunctionSamples::getCanonicalFnName(*Callee);
612 
613   if (ProfileIsCS)
614     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
615 
616   const FunctionSamples *FS = findFunctionSamples(Inst);
617   if (FS == nullptr)
618     return nullptr;
619 
620   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
621                                    CalleeName, Reader->getRemapper());
622 }
623 
624 /// Returns a vector of FunctionSamples that are the indirect call targets
625 /// of \p Inst. The vector is sorted by the total number of samples. Stores
626 /// the total call count of the indirect call in \p Sum.
627 std::vector<const FunctionSamples *>
628 SampleProfileLoader::findIndirectCallFunctionSamples(
629     const Instruction &Inst, uint64_t &Sum) const {
630   const DILocation *DIL = Inst.getDebugLoc();
631   std::vector<const FunctionSamples *> R;
632 
633   if (!DIL) {
634     return R;
635   }
636 
637   auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
638     assert(L && R && "Expect non-null FunctionSamples");
639     if (L->getEntrySamples() != R->getEntrySamples())
640       return L->getEntrySamples() > R->getEntrySamples();
641     return FunctionSamples::getGUID(L->getName()) <
642            FunctionSamples::getGUID(R->getName());
643   };
644 
645   if (ProfileIsCS) {
646     auto CalleeSamples =
647         ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
648     if (CalleeSamples.empty())
649       return R;
650 
651     // For CSSPGO, we only use target context profile's entry count
652     // as that already includes both inlined callee and non-inlined ones..
653     Sum = 0;
654     for (const auto *const FS : CalleeSamples) {
655       Sum += FS->getEntrySamples();
656       R.push_back(FS);
657     }
658     llvm::sort(R, FSCompare);
659     return R;
660   }
661 
662   const FunctionSamples *FS = findFunctionSamples(Inst);
663   if (FS == nullptr)
664     return R;
665 
666   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
667   auto T = FS->findCallTargetMapAt(CallSite);
668   Sum = 0;
669   if (T)
670     for (const auto &T_C : T.get())
671       Sum += T_C.second;
672   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
673     if (M->empty())
674       return R;
675     for (const auto &NameFS : *M) {
676       Sum += NameFS.second.getEntrySamples();
677       R.push_back(&NameFS.second);
678     }
679     llvm::sort(R, FSCompare);
680   }
681   return R;
682 }
683 
684 const FunctionSamples *
685 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
686   if (FunctionSamples::ProfileIsProbeBased) {
687     Optional<PseudoProbe> Probe = extractProbe(Inst);
688     if (!Probe)
689       return nullptr;
690   }
691 
692   const DILocation *DIL = Inst.getDebugLoc();
693   if (!DIL)
694     return Samples;
695 
696   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
697   if (it.second) {
698     if (ProfileIsCS)
699       it.first->second = ContextTracker->getContextSamplesFor(DIL);
700     else
701       it.first->second =
702           Samples->findFunctionSamples(DIL, Reader->getRemapper());
703   }
704   return it.first->second;
705 }
706 
707 /// Check whether the indirect call promotion history of \p Inst allows
708 /// the promotion for \p Candidate.
709 /// If the profile count for the promotion candidate \p Candidate is
710 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
711 /// for \p Inst. If we already have at least MaxNumPromotions
712 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
713 /// cannot promote for \p Inst anymore.
714 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
715   uint32_t NumVals = 0;
716   uint64_t TotalCount = 0;
717   std::unique_ptr<InstrProfValueData[]> ValueData =
718       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
719   bool Valid =
720       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
721                                ValueData.get(), NumVals, TotalCount, true);
722   // No valid value profile so no promoted targets have been recorded
723   // before. Ok to do ICP.
724   if (!Valid)
725     return true;
726 
727   unsigned NumPromoted = 0;
728   for (uint32_t I = 0; I < NumVals; I++) {
729     if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
730       continue;
731 
732     // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
733     // metadata, it means the candidate has been promoted for this
734     // indirect call.
735     if (ValueData[I].Value == Function::getGUID(Candidate))
736       return false;
737     NumPromoted++;
738     // If already have MaxNumPromotions promotion, don't do it anymore.
739     if (NumPromoted == MaxNumPromotions)
740       return false;
741   }
742   return true;
743 }
744 
745 /// Update indirect call target profile metadata for \p Inst.
746 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
747 /// If it is 0, it means updateIDTMetaData is used to mark a
748 /// certain target to be promoted already. If it is not zero,
749 /// we expect to use it to update the total count in the value profile.
750 static void
751 updateIDTMetaData(Instruction &Inst,
752                   const SmallVectorImpl<InstrProfValueData> &CallTargets,
753                   uint64_t Sum) {
754   assert((Sum != 0 || (CallTargets.size() == 1 &&
755                        CallTargets[0].Count == NOMORE_ICP_MAGICNUM)) &&
756          "If sum is 0, assume only one element in CallTargets with count "
757          "being NOMORE_ICP_MAGICNUM");
758 
759   uint32_t NumVals = 0;
760   // OldSum is the existing total count in the value profile data.
761   // It will be replaced by Sum if Sum is not 0.
762   uint64_t OldSum = 0;
763   std::unique_ptr<InstrProfValueData[]> ValueData =
764       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
765   bool Valid =
766       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
767                                ValueData.get(), NumVals, OldSum, true);
768 
769   DenseMap<uint64_t, uint64_t> ValueCountMap;
770   // Initialize ValueCountMap with existing value profile data.
771   if (Valid) {
772     for (uint32_t I = 0; I < NumVals; I++)
773       ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
774   }
775 
776   for (const auto &Data : CallTargets) {
777     auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
778     if (Pair.second)
779       continue;
780     // Whenever the count is NOMORE_ICP_MAGICNUM for a value, keep it
781     // in the ValueCountMap. If both the count in CallTargets and the
782     // count in ValueCountMap is not NOMORE_ICP_MAGICNUM, keep the
783     // count in CallTargets.
784     if (Pair.first->second != NOMORE_ICP_MAGICNUM &&
785         Data.Count == NOMORE_ICP_MAGICNUM) {
786       OldSum -= Pair.first->second;
787       Pair.first->second = NOMORE_ICP_MAGICNUM;
788     } else if (Pair.first->second == NOMORE_ICP_MAGICNUM &&
789                Data.Count != NOMORE_ICP_MAGICNUM) {
790       assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
791       Sum -= Data.Count;
792     } else if (Pair.first->second != NOMORE_ICP_MAGICNUM &&
793                Data.Count != NOMORE_ICP_MAGICNUM) {
794       // Sum will be used in this case. Although the existing count
795       // for the current value in value profile will be overriden,
796       // no need to update OldSum.
797       Pair.first->second = Data.Count;
798     }
799   }
800 
801   SmallVector<InstrProfValueData, 8> NewCallTargets;
802   for (const auto &ValueCount : ValueCountMap) {
803     NewCallTargets.emplace_back(
804         InstrProfValueData{ValueCount.first, ValueCount.second});
805   }
806 
807   llvm::sort(NewCallTargets,
808              [](const InstrProfValueData &L, const InstrProfValueData &R) {
809                if (L.Count != R.Count)
810                  return L.Count > R.Count;
811                return L.Value > R.Value;
812              });
813 
814   uint32_t MaxMDCount =
815       std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
816   annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
817                     NewCallTargets, Sum ? Sum : OldSum, IPVK_IndirectCallTarget,
818                     MaxMDCount);
819 }
820 
821 /// Attempt to promote indirect call and also inline the promoted call.
822 ///
823 /// \param F  Caller function.
824 /// \param Candidate  ICP and inline candidate.
825 /// \param Sum  Sum of target counts for indirect call.
826 /// \param InlinedCallSite  Output vector for new call sites exposed after
827 /// inlining.
828 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
829     Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
830     SmallVector<CallBase *, 8> *InlinedCallSite) {
831   auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
832   auto R = SymbolMap.find(CalleeFunctionName);
833   if (R == SymbolMap.end() || !R->getValue())
834     return false;
835 
836   auto &CI = *Candidate.CallInstr;
837   if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
838     return false;
839 
840   const char *Reason = "Callee function not available";
841   // R->getValue() != &F is to prevent promoting a recursive call.
842   // If it is a recursive call, we do not inline it as it could bloat
843   // the code exponentially. There is way to better handle this, e.g.
844   // clone the caller first, and inline the cloned caller if it is
845   // recursive. As llvm does not inline recursive calls, we will
846   // simply ignore it instead of handling it explicitly.
847   if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
848       R->getValue()->hasFnAttribute("use-sample-profile") &&
849       R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
850     // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
851     // in the value profile metadata so the target won't be promoted again.
852     SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
853         Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
854     updateIDTMetaData(CI, SortedCallTargets, 0);
855 
856     auto *DI = &pgo::promoteIndirectCall(
857         CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
858     if (DI) {
859       Sum -= Candidate.CallsiteCount;
860       // Prorate the indirect callsite distribution.
861       // Do not update the promoted direct callsite distribution at this
862       // point since the original distribution combined with the callee
863       // profile will be used to prorate callsites from the callee if
864       // inlined. Once not inlined, the direct callsite distribution should
865       // be prorated so that the it will reflect the real callsite counts.
866       setProbeDistributionFactor(CI, Candidate.CallsiteDistribution * Sum /
867                                          SumOrigin);
868       Candidate.CallInstr = DI;
869       if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
870         bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
871         if (!Inlined) {
872           // Prorate the direct callsite distribution so that it reflects real
873           // callsite counts.
874           setProbeDistributionFactor(*DI, Candidate.CallsiteDistribution *
875                                               Candidate.CallsiteCount /
876                                               SumOrigin);
877         }
878         return Inlined;
879       }
880     }
881   } else {
882     LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
883                       << Candidate.CalleeSamples->getFuncName() << " because "
884                       << Reason << "\n");
885   }
886   return false;
887 }
888 
889 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
890   if (!ProfileSizeInline)
891     return false;
892 
893   Function *Callee = CallInst.getCalledFunction();
894   if (Callee == nullptr)
895     return false;
896 
897   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
898                                   GetAC, GetTLI);
899 
900   if (Cost.isNever())
901     return false;
902 
903   if (Cost.isAlways())
904     return true;
905 
906   return Cost.getCost() <= SampleColdCallSiteThreshold;
907 }
908 
909 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
910     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
911     bool Hot) {
912   for (auto I : Candidates) {
913     Function *CalledFunction = I->getCalledFunction();
914     if (CalledFunction) {
915       ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
916                                            I->getDebugLoc(), I->getParent())
917                 << "previous inlining reattempted for "
918                 << (Hot ? "hotness: '" : "size: '")
919                 << ore::NV("Callee", CalledFunction) << "' into '"
920                 << ore::NV("Caller", &F) << "'");
921     }
922   }
923 }
924 
925 /// Iteratively inline hot callsites of a function.
926 ///
927 /// Iteratively traverse all callsites of the function \p F, and find if
928 /// the corresponding inlined instance exists and is hot in profile. If
929 /// it is hot enough, inline the callsites and adds new callsites of the
930 /// callee into the caller. If the call is an indirect call, first promote
931 /// it to direct call. Each indirect call is limited with a single target.
932 ///
933 /// \param F function to perform iterative inlining.
934 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
935 ///     inlined in the profiled binary.
936 ///
937 /// \returns True if there is any inline happened.
938 bool SampleProfileLoader::inlineHotFunctions(
939     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
940   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
941   // Profile symbol list is ignored when profile-sample-accurate is on.
942   assert((!ProfAccForSymsInList ||
943           (!ProfileSampleAccurate &&
944            !F.hasFnAttribute("profile-sample-accurate"))) &&
945          "ProfAccForSymsInList should be false when profile-sample-accurate "
946          "is enabled");
947 
948   DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
949   bool Changed = false;
950   bool LocalChanged = true;
951   while (LocalChanged) {
952     LocalChanged = false;
953     SmallVector<CallBase *, 10> CIS;
954     for (auto &BB : F) {
955       bool Hot = false;
956       SmallVector<CallBase *, 10> AllCandidates;
957       SmallVector<CallBase *, 10> ColdCandidates;
958       for (auto &I : BB.getInstList()) {
959         const FunctionSamples *FS = nullptr;
960         if (auto *CB = dyn_cast<CallBase>(&I)) {
961           if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
962             assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
963                    "GUIDToFuncNameMap has to be populated");
964             AllCandidates.push_back(CB);
965             if (FS->getEntrySamples() > 0 || ProfileIsCS)
966               LocalNotInlinedCallSites.try_emplace(CB, FS);
967             if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
968               Hot = true;
969             else if (shouldInlineColdCallee(*CB))
970               ColdCandidates.push_back(CB);
971           }
972         }
973       }
974       if (Hot || ExternalInlineAdvisor) {
975         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
976         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
977       } else {
978         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
979         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
980       }
981     }
982     for (CallBase *I : CIS) {
983       Function *CalledFunction = I->getCalledFunction();
984       InlineCandidate Candidate = {
985           I,
986           LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I]
987                                             : nullptr,
988           0 /* dummy count */, 1.0 /* dummy distribution factor */};
989       // Do not inline recursive calls.
990       if (CalledFunction == &F)
991         continue;
992       if (I->isIndirectCall()) {
993         uint64_t Sum;
994         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
995           uint64_t SumOrigin = Sum;
996           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
997             FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
998                                      PSI->getOrCompHotCountThreshold());
999             continue;
1000           }
1001           if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1002             continue;
1003 
1004           Candidate = {I, FS, FS->getEntrySamples(), 1.0};
1005           if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1006             LocalNotInlinedCallSites.erase(I);
1007             LocalChanged = true;
1008           }
1009         }
1010       } else if (CalledFunction && CalledFunction->getSubprogram() &&
1011                  !CalledFunction->isDeclaration()) {
1012         if (tryInlineCandidate(Candidate)) {
1013           LocalNotInlinedCallSites.erase(I);
1014           LocalChanged = true;
1015         }
1016       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1017         findCalleeFunctionSamples(*I)->findInlinedFunctions(
1018             InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
1019       }
1020     }
1021     Changed |= LocalChanged;
1022   }
1023 
1024   // For CS profile, profile for not inlined context will be merged when
1025   // base profile is being trieved
1026   if (ProfileIsCS)
1027     return Changed;
1028 
1029   // Accumulate not inlined callsite information into notInlinedSamples
1030   for (const auto &Pair : LocalNotInlinedCallSites) {
1031     CallBase *I = Pair.getFirst();
1032     Function *Callee = I->getCalledFunction();
1033     if (!Callee || Callee->isDeclaration())
1034       continue;
1035 
1036     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1037                                          I->getDebugLoc(), I->getParent())
1038               << "previous inlining not repeated: '"
1039               << ore::NV("Callee", Callee) << "' into '"
1040               << ore::NV("Caller", &F) << "'");
1041 
1042     ++NumCSNotInlined;
1043     const FunctionSamples *FS = Pair.getSecond();
1044     if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1045       continue;
1046     }
1047 
1048     if (ProfileMergeInlinee) {
1049       // A function call can be replicated by optimizations like callsite
1050       // splitting or jump threading and the replicates end up sharing the
1051       // sample nested callee profile instead of slicing the original inlinee's
1052       // profile. We want to do merge exactly once by filtering out callee
1053       // profiles with a non-zero head sample count.
1054       if (FS->getHeadSamples() == 0) {
1055         // Use entry samples as head samples during the merge, as inlinees
1056         // don't have head samples.
1057         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1058             FS->getEntrySamples());
1059 
1060         // Note that we have to do the merge right after processing function.
1061         // This allows OutlineFS's profile to be used for annotation during
1062         // top-down processing of functions' annotation.
1063         FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1064         OutlineFS->merge(*FS);
1065       }
1066     } else {
1067       auto pair =
1068           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1069       pair.first->second.entryCount += FS->getEntrySamples();
1070     }
1071   }
1072   return Changed;
1073 }
1074 
1075 bool SampleProfileLoader::tryInlineCandidate(
1076     InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1077 
1078   CallBase &CB = *Candidate.CallInstr;
1079   Function *CalledFunction = CB.getCalledFunction();
1080   assert(CalledFunction && "Expect a callee with definition");
1081   DebugLoc DLoc = CB.getDebugLoc();
1082   BasicBlock *BB = CB.getParent();
1083 
1084   InlineCost Cost = shouldInlineCandidate(Candidate);
1085   if (Cost.isNever()) {
1086     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1087               << "incompatible inlining");
1088     return false;
1089   }
1090 
1091   if (!Cost)
1092     return false;
1093 
1094   InlineFunctionInfo IFI(nullptr, GetAC);
1095   if (InlineFunction(CB, IFI).isSuccess()) {
1096     // The call to InlineFunction erases I, so we can't pass it here.
1097     emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
1098                     true, CSINLINE_DEBUG);
1099 
1100     // Now populate the list of newly exposed call sites.
1101     if (InlinedCallSites) {
1102       InlinedCallSites->clear();
1103       for (auto &I : IFI.InlinedCallSites)
1104         InlinedCallSites->push_back(I);
1105     }
1106 
1107     if (ProfileIsCS)
1108       ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1109     ++NumCSInlined;
1110 
1111     // Prorate inlined probes for a duplicated inlining callsite which probably
1112     // has a distribution less than 100%. Samples for an inlinee should be
1113     // distributed among the copies of the original callsite based on each
1114     // callsite's distribution factor for counts accuracy. Note that an inlined
1115     // probe may come with its own distribution factor if it has been duplicated
1116     // in the inlinee body. The two factor are multiplied to reflect the
1117     // aggregation of duplication.
1118     if (Candidate.CallsiteDistribution < 1) {
1119       for (auto &I : IFI.InlinedCallSites) {
1120         if (Optional<PseudoProbe> Probe = extractProbe(*I))
1121           setProbeDistributionFactor(*I, Probe->Factor *
1122                                              Candidate.CallsiteDistribution);
1123       }
1124       NumDuplicatedInlinesite++;
1125     }
1126 
1127     return true;
1128   }
1129   return false;
1130 }
1131 
1132 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1133                                              CallBase *CB) {
1134   assert(CB && "Expect non-null call instruction");
1135 
1136   if (isa<IntrinsicInst>(CB))
1137     return false;
1138 
1139   // Find the callee's profile. For indirect call, find hottest target profile.
1140   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1141   if (!CalleeSamples)
1142     return false;
1143 
1144   float Factor = 1.0;
1145   if (Optional<PseudoProbe> Probe = extractProbe(*CB))
1146     Factor = Probe->Factor;
1147 
1148   uint64_t CallsiteCount = 0;
1149   ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
1150   if (Weight)
1151     CallsiteCount = Weight.get();
1152   if (CalleeSamples)
1153     CallsiteCount = std::max(
1154         CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
1155 
1156   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1157   return true;
1158 }
1159 
1160 InlineCost
1161 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1162   std::unique_ptr<InlineAdvice> Advice = nullptr;
1163   if (ExternalInlineAdvisor) {
1164     Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr);
1165     if (!Advice->isInliningRecommended()) {
1166       Advice->recordUnattemptedInlining();
1167       return InlineCost::getNever("not previously inlined");
1168     }
1169     Advice->recordInlining();
1170     return InlineCost::getAlways("previously inlined");
1171   }
1172 
1173   // Adjust threshold based on call site hotness, only do this for callsite
1174   // prioritized inliner because otherwise cost-benefit check is done earlier.
1175   int SampleThreshold = SampleColdCallSiteThreshold;
1176   if (CallsitePrioritizedInline) {
1177     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1178       SampleThreshold = SampleHotCallSiteThreshold;
1179     else if (!ProfileSizeInline)
1180       return InlineCost::getNever("cold callsite");
1181   }
1182 
1183   Function *Callee = Candidate.CallInstr->getCalledFunction();
1184   assert(Callee && "Expect a definition for inline candidate of direct call");
1185 
1186   InlineParams Params = getInlineParams();
1187   Params.ComputeFullInlineCost = true;
1188   // Checks if there is anything in the reachable portion of the callee at
1189   // this callsite that makes this inlining potentially illegal. Need to
1190   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1191   // when cost exceeds threshold without checking all IRs in the callee.
1192   // The acutal cost does not matter because we only checks isNever() to
1193   // see if it is legal to inline the callsite.
1194   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1195                                   GetTTI(*Callee), GetAC, GetTLI);
1196 
1197   // Honor always inline and never inline from call analyzer
1198   if (Cost.isNever() || Cost.isAlways())
1199     return Cost;
1200 
1201   // For old FDO inliner, we inline the call site as long as cost is not
1202   // "Never". The cost-benefit check is done earlier.
1203   if (!CallsitePrioritizedInline) {
1204     return InlineCost::get(Cost.getCost(), INT_MAX);
1205   }
1206 
1207   // Otherwise only use the cost from call analyzer, but overwite threshold with
1208   // Sample PGO threshold.
1209   return InlineCost::get(Cost.getCost(), SampleThreshold);
1210 }
1211 
1212 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1213     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1214   assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now");
1215 
1216   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1217   // Profile symbol list is ignored when profile-sample-accurate is on.
1218   assert((!ProfAccForSymsInList ||
1219           (!ProfileSampleAccurate &&
1220            !F.hasFnAttribute("profile-sample-accurate"))) &&
1221          "ProfAccForSymsInList should be false when profile-sample-accurate "
1222          "is enabled");
1223 
1224   // Populating worklist with initial call sites from root inliner, along
1225   // with call site weights.
1226   CandidateQueue CQueue;
1227   InlineCandidate NewCandidate;
1228   for (auto &BB : F) {
1229     for (auto &I : BB.getInstList()) {
1230       auto *CB = dyn_cast<CallBase>(&I);
1231       if (!CB)
1232         continue;
1233       if (getInlineCandidate(&NewCandidate, CB))
1234         CQueue.push(NewCandidate);
1235     }
1236   }
1237 
1238   // Cap the size growth from profile guided inlining. This is needed even
1239   // though cost of each inline candidate already accounts for callee size,
1240   // because with top-down inlining, we can grow inliner size significantly
1241   // with large number of smaller inlinees each pass the cost check.
1242   assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1243          "Max inline size limit should not be smaller than min inline size "
1244          "limit.");
1245   unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1246   SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1247   SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1248   if (ExternalInlineAdvisor)
1249     SizeLimit = std::numeric_limits<unsigned>::max();
1250 
1251   // Perform iterative BFS call site prioritized inlining
1252   bool Changed = false;
1253   while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1254     InlineCandidate Candidate = CQueue.top();
1255     CQueue.pop();
1256     CallBase *I = Candidate.CallInstr;
1257     Function *CalledFunction = I->getCalledFunction();
1258 
1259     if (CalledFunction == &F)
1260       continue;
1261     if (I->isIndirectCall()) {
1262       uint64_t Sum;
1263       auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1264       uint64_t SumOrigin = Sum;
1265       Sum *= Candidate.CallsiteDistribution;
1266       for (const auto *FS : CalleeSamples) {
1267         // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1268         if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1269           FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
1270                                    PSI->getOrCompHotCountThreshold());
1271           continue;
1272         }
1273         uint64_t EntryCountDistributed =
1274             FS->getEntrySamples() * Candidate.CallsiteDistribution;
1275         // In addition to regular inline cost check, we also need to make sure
1276         // ICP isn't introducing excessive speculative checks even if individual
1277         // target looks beneficial to promote and inline. That means we should
1278         // only do ICP when there's a small number dominant targets.
1279         if (EntryCountDistributed < SumOrigin / ProfileICPThreshold)
1280           break;
1281         // TODO: Fix CallAnalyzer to handle all indirect calls.
1282         // For indirect call, we don't run CallAnalyzer to get InlineCost
1283         // before actual inlining. This is because we could see two different
1284         // types from the same definition, which makes CallAnalyzer choke as
1285         // it's expecting matching parameter type on both caller and callee
1286         // side. See example from PR18962 for the triggering cases (the bug was
1287         // fixed, but we generate different types).
1288         if (!PSI->isHotCount(EntryCountDistributed))
1289           break;
1290         SmallVector<CallBase *, 8> InlinedCallSites;
1291         // Attach function profile for promoted indirect callee, and update
1292         // call site count for the promoted inline candidate too.
1293         Candidate = {I, FS, EntryCountDistributed,
1294                      Candidate.CallsiteDistribution};
1295         if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1296                                          &InlinedCallSites)) {
1297           for (auto *CB : InlinedCallSites) {
1298             if (getInlineCandidate(&NewCandidate, CB))
1299               CQueue.emplace(NewCandidate);
1300           }
1301           Changed = true;
1302         }
1303       }
1304     } else if (CalledFunction && CalledFunction->getSubprogram() &&
1305                !CalledFunction->isDeclaration()) {
1306       SmallVector<CallBase *, 8> InlinedCallSites;
1307       if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1308         for (auto *CB : InlinedCallSites) {
1309           if (getInlineCandidate(&NewCandidate, CB))
1310             CQueue.emplace(NewCandidate);
1311         }
1312         Changed = true;
1313       }
1314     } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1315       findCalleeFunctionSamples(*I)->findInlinedFunctions(
1316           InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
1317     }
1318   }
1319 
1320   if (!CQueue.empty()) {
1321     if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1322       ++NumCSInlinedHitMaxLimit;
1323     else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1324       ++NumCSInlinedHitMinLimit;
1325     else
1326       ++NumCSInlinedHitGrowthLimit;
1327   }
1328 
1329   return Changed;
1330 }
1331 
1332 /// Returns the sorted CallTargetMap \p M by count in descending order.
1333 static SmallVector<InstrProfValueData, 2>
1334 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
1335   SmallVector<InstrProfValueData, 2> R;
1336   for (const auto &I : SampleRecord::SortCallTargets(M)) {
1337     R.emplace_back(
1338         InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1339   }
1340   return R;
1341 }
1342 
1343 // Generate MD_prof metadata for every branch instruction using the
1344 // edge weights computed during propagation.
1345 void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1346   // Generate MD_prof metadata for every branch instruction using the
1347   // edge weights computed during propagation.
1348   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1349   LLVMContext &Ctx = F.getContext();
1350   MDBuilder MDB(Ctx);
1351   for (auto &BI : F) {
1352     BasicBlock *BB = &BI;
1353 
1354     if (BlockWeights[BB]) {
1355       for (auto &I : BB->getInstList()) {
1356         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1357           continue;
1358         if (!cast<CallBase>(I).getCalledFunction()) {
1359           const DebugLoc &DLoc = I.getDebugLoc();
1360           if (!DLoc)
1361             continue;
1362           const DILocation *DIL = DLoc;
1363           const FunctionSamples *FS = findFunctionSamples(I);
1364           if (!FS)
1365             continue;
1366           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1367           auto T = FS->findCallTargetMapAt(CallSite);
1368           if (!T || T.get().empty())
1369             continue;
1370           // Prorate the callsite counts to reflect what is already done to the
1371           // callsite, such as ICP or calliste cloning.
1372           if (FunctionSamples::ProfileIsProbeBased) {
1373             if (Optional<PseudoProbe> Probe = extractProbe(I)) {
1374               if (Probe->Factor < 1)
1375                 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1376             }
1377           }
1378           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1379               GetSortedValueDataFromCallTargets(T.get());
1380           uint64_t Sum = 0;
1381           for (const auto &C : T.get())
1382             Sum += C.second;
1383           // With CSSPGO all indirect call targets are counted torwards the
1384           // original indirect call site in the profile, including both
1385           // inlined and non-inlined targets.
1386           if (!FunctionSamples::ProfileIsCS) {
1387             if (const FunctionSamplesMap *M =
1388                     FS->findFunctionSamplesMapAt(CallSite)) {
1389               for (const auto &NameFS : *M)
1390                 Sum += NameFS.second.getEntrySamples();
1391             }
1392           }
1393           if (!Sum)
1394             continue;
1395           updateIDTMetaData(I, SortedCallTargets, Sum);
1396         } else if (!isa<IntrinsicInst>(&I)) {
1397           I.setMetadata(LLVMContext::MD_prof,
1398                         MDB.createBranchWeights(
1399                             {static_cast<uint32_t>(BlockWeights[BB])}));
1400         }
1401       }
1402     }
1403     Instruction *TI = BB->getTerminator();
1404     if (TI->getNumSuccessors() == 1)
1405       continue;
1406     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1407       continue;
1408 
1409     DebugLoc BranchLoc = TI->getDebugLoc();
1410     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1411                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1412                                       : Twine("<UNKNOWN LOCATION>"))
1413                       << ".\n");
1414     SmallVector<uint32_t, 4> Weights;
1415     uint32_t MaxWeight = 0;
1416     Instruction *MaxDestInst;
1417     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1418       BasicBlock *Succ = TI->getSuccessor(I);
1419       Edge E = std::make_pair(BB, Succ);
1420       uint64_t Weight = EdgeWeights[E];
1421       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1422       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1423       // if needed. Sample counts in profiles are 64-bit unsigned values,
1424       // but internally branch weights are expressed as 32-bit values.
1425       if (Weight > std::numeric_limits<uint32_t>::max()) {
1426         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1427         Weight = std::numeric_limits<uint32_t>::max();
1428       }
1429       // Weight is added by one to avoid propagation errors introduced by
1430       // 0 weights.
1431       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1432       if (Weight != 0) {
1433         if (Weight > MaxWeight) {
1434           MaxWeight = Weight;
1435           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1436         }
1437       }
1438     }
1439 
1440     uint64_t TempWeight;
1441     // Only set weights if there is at least one non-zero weight.
1442     // In any other case, let the analyzer set weights.
1443     // Do not set weights if the weights are present. In ThinLTO, the profile
1444     // annotation is done twice. If the first annotation already set the
1445     // weights, the second pass does not need to set it.
1446     if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1447       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1448       TI->setMetadata(LLVMContext::MD_prof,
1449                       MDB.createBranchWeights(Weights));
1450       ORE->emit([&]() {
1451         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1452                << "most popular destination for conditional branches at "
1453                << ore::NV("CondBranchesLoc", BranchLoc);
1454       });
1455     } else {
1456       LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1457     }
1458   }
1459 }
1460 
1461 /// Once all the branch weights are computed, we emit the MD_prof
1462 /// metadata on BB using the computed values for each of its branches.
1463 ///
1464 /// \param F The function to query.
1465 ///
1466 /// \returns true if \p F was modified. Returns false, otherwise.
1467 bool SampleProfileLoader::emitAnnotations(Function &F) {
1468   bool Changed = false;
1469 
1470   if (FunctionSamples::ProfileIsProbeBased) {
1471     if (!ProbeManager->profileIsValid(F, *Samples)) {
1472       LLVM_DEBUG(
1473           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1474                  << F.getName());
1475       ++NumMismatchedProfile;
1476       return false;
1477     }
1478     ++NumMatchedProfile;
1479   } else {
1480     if (getFunctionLoc(F) == 0)
1481       return false;
1482 
1483     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1484                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1485   }
1486 
1487   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1488   if (ProfileIsCS && CallsitePrioritizedInline)
1489     Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1490   else
1491     Changed |= inlineHotFunctions(F, InlinedGUIDs);
1492 
1493   Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1494 
1495   if (Changed)
1496     generateMDProfMetadata(F);
1497 
1498   emitCoverageRemarks(F);
1499   return Changed;
1500 }
1501 
1502 char SampleProfileLoaderLegacyPass::ID = 0;
1503 
1504 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1505                       "Sample Profile loader", false, false)
1506 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1507 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1508 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1509 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1510 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1511                     "Sample Profile loader", false, false)
1512 
1513 // Add inlined profile call edges to the call graph.
1514 void SampleProfileLoader::addCallGraphEdges(CallGraph &CG,
1515                                             const FunctionSamples &Samples) {
1516   Function *Caller = SymbolMap.lookup(Samples.getFuncName());
1517   if (!Caller || Caller->isDeclaration())
1518     return;
1519 
1520   // Skip non-inlined call edges which are not important since top down inlining
1521   // for non-CS profile is to get more precise profile matching, not to enable
1522   // more inlining.
1523 
1524   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
1525     for (const auto &InlinedSamples : CallsiteSamples.second) {
1526       Function *Callee = SymbolMap.lookup(InlinedSamples.first);
1527       if (Callee && !Callee->isDeclaration())
1528         CG[Caller]->addCalledFunction(nullptr, CG[Callee]);
1529       addCallGraphEdges(CG, InlinedSamples.second);
1530     }
1531   }
1532 }
1533 
1534 // Replace call graph edges with dynamic call edges from the profile.
1535 void SampleProfileLoader::replaceCallGraphEdges(
1536     CallGraph &CG, StringMap<Function *> &SymbolMap) {
1537   // Remove static call edges from the call graph except for the ones from the
1538   // root which make the call graph connected.
1539   for (const auto &Node : CG)
1540     if (Node.second.get() != CG.getExternalCallingNode())
1541       Node.second->removeAllCalledFunctions();
1542 
1543   // Add profile call edges to the call graph.
1544   if (ProfileIsCS) {
1545     ContextTracker->addCallGraphEdges(CG, SymbolMap);
1546   } else {
1547     for (const auto &Samples : Reader->getProfiles())
1548       addCallGraphEdges(CG, Samples.second);
1549   }
1550 }
1551 
1552 std::vector<Function *>
1553 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1554   std::vector<Function *> FunctionOrderList;
1555   FunctionOrderList.reserve(M.size());
1556 
1557   if (!ProfileTopDownLoad || CG == nullptr) {
1558     if (ProfileMergeInlinee) {
1559       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1560       // because the profile for a function may be used for the profile
1561       // annotation of its outline copy before the profile merging of its
1562       // non-inlined inline instances, and that is not the way how
1563       // ProfileMergeInlinee is supposed to work.
1564       ProfileMergeInlinee = false;
1565     }
1566 
1567     for (Function &F : M)
1568       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1569         FunctionOrderList.push_back(&F);
1570     return FunctionOrderList;
1571   }
1572 
1573   assert(&CG->getModule() == &M);
1574 
1575   // Add indirect call edges from profile to augment the static call graph.
1576   // Functions will be processed in a top-down order defined by the static call
1577   // graph. Adjusting the order by considering indirect call edges from the
1578   // profile (which don't exist in the static call graph) can enable the
1579   // inlining of indirect call targets by processing the caller before them.
1580   // TODO: enable this for non-CS profile and fix the counts returning logic to
1581   // have a full support for indirect calls.
1582   if (UseProfileIndirectCallEdges && ProfileIsCS) {
1583     for (auto &Entry : *CG) {
1584       const auto *F = Entry.first;
1585       if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
1586         continue;
1587       auto &AllContexts = ContextTracker->getAllContextSamplesFor(F->getName());
1588       if (AllContexts.empty())
1589         continue;
1590 
1591       for (const auto &BB : *F) {
1592         for (const auto &I : BB.getInstList()) {
1593           const auto *CB = dyn_cast<CallBase>(&I);
1594           if (!CB || !CB->isIndirectCall())
1595             continue;
1596           const DebugLoc &DLoc = I.getDebugLoc();
1597           if (!DLoc)
1598             continue;
1599           auto CallSite = FunctionSamples::getCallSiteIdentifier(DLoc);
1600           for (FunctionSamples *Samples : AllContexts) {
1601             if (auto CallTargets = Samples->findCallTargetMapAt(CallSite)) {
1602               for (const auto &Target : CallTargets.get()) {
1603                 Function *Callee = SymbolMap.lookup(Target.first());
1604                 if (Callee && !Callee->isDeclaration())
1605                   Entry.second->addCalledFunction(nullptr, (*CG)[Callee]);
1606               }
1607             }
1608           }
1609         }
1610       }
1611     }
1612   }
1613 
1614   // Compute a top-down order the profile which is used to sort functions in
1615   // one SCC later. The static processing order computed for an SCC may not
1616   // reflect the call contexts in the context-sensitive profile, thus may cause
1617   // potential inlining to be overlooked. The function order in one SCC is being
1618   // adjusted to a top-down order based on the profile to favor more inlining.
1619   DenseMap<Function *, uint64_t> ProfileOrderMap;
1620   if (UseProfileTopDownOrder ||
1621       (ProfileIsCS && !UseProfileTopDownOrder.getNumOccurrences())) {
1622     // Create a static call graph. The call edges are not important since they
1623     // will be replaced by dynamic edges from the profile.
1624     CallGraph ProfileCG(M);
1625     replaceCallGraphEdges(ProfileCG, SymbolMap);
1626     scc_iterator<CallGraph *> CGI = scc_begin(&ProfileCG);
1627     uint64_t I = 0;
1628     while (!CGI.isAtEnd()) {
1629       for (CallGraphNode *Node : *CGI) {
1630         if (auto *F = Node->getFunction())
1631           ProfileOrderMap[F] = ++I;
1632       }
1633       ++CGI;
1634     }
1635   }
1636 
1637   scc_iterator<CallGraph *> CGI = scc_begin(CG);
1638   while (!CGI.isAtEnd()) {
1639     uint64_t Start = FunctionOrderList.size();
1640     for (CallGraphNode *Node : *CGI) {
1641       auto *F = Node->getFunction();
1642       if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1643         FunctionOrderList.push_back(F);
1644     }
1645 
1646     // Sort nodes in SCC based on the profile top-down order.
1647     if (!ProfileOrderMap.empty()) {
1648       std::stable_sort(FunctionOrderList.begin() + Start,
1649                        FunctionOrderList.end(),
1650                        [&ProfileOrderMap](Function *Left, Function *Right) {
1651                          return ProfileOrderMap[Left] < ProfileOrderMap[Right];
1652                        });
1653     }
1654 
1655     ++CGI;
1656   }
1657 
1658   LLVM_DEBUG({
1659     dbgs() << "Function processing order:\n";
1660     for (auto F : reverse(FunctionOrderList)) {
1661       dbgs() << F->getName() << "\n";
1662     }
1663   });
1664 
1665   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1666   return FunctionOrderList;
1667 }
1668 
1669 bool SampleProfileLoader::doInitialization(Module &M,
1670                                            FunctionAnalysisManager *FAM) {
1671   auto &Ctx = M.getContext();
1672 
1673   auto ReaderOrErr =
1674       SampleProfileReader::create(Filename, Ctx, RemappingFilename);
1675   if (std::error_code EC = ReaderOrErr.getError()) {
1676     std::string Msg = "Could not open profile: " + EC.message();
1677     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1678     return false;
1679   }
1680   Reader = std::move(ReaderOrErr.get());
1681   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1682   Reader->collectFuncsFrom(M);
1683   if (std::error_code EC = Reader->read()) {
1684     std::string Msg = "profile reading failed: " + EC.message();
1685     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1686     return false;
1687   }
1688 
1689   PSL = Reader->getProfileSymbolList();
1690 
1691   // While profile-sample-accurate is on, ignore symbol list.
1692   ProfAccForSymsInList =
1693       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1694   if (ProfAccForSymsInList) {
1695     NamesInProfile.clear();
1696     if (auto NameTable = Reader->getNameTable())
1697       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1698     CoverageTracker.setProfAccForSymsInList(true);
1699   }
1700 
1701   if (FAM && !ProfileInlineReplayFile.empty()) {
1702     ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
1703         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
1704         /*EmitRemarks=*/false);
1705     if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
1706       ExternalInlineAdvisor.reset();
1707   }
1708 
1709   // Apply tweaks if context-sensitive profile is available.
1710   if (Reader->profileIsCS()) {
1711     ProfileIsCS = true;
1712     FunctionSamples::ProfileIsCS = true;
1713 
1714     // Enable priority-base inliner and size inline by default for CSSPGO.
1715     if (!ProfileSizeInline.getNumOccurrences())
1716       ProfileSizeInline = true;
1717     if (!CallsitePrioritizedInline.getNumOccurrences())
1718       CallsitePrioritizedInline = true;
1719 
1720     // Tracker for profiles under different context
1721     ContextTracker =
1722         std::make_unique<SampleContextTracker>(Reader->getProfiles());
1723   }
1724 
1725   // Load pseudo probe descriptors for probe-based function samples.
1726   if (Reader->profileIsProbeBased()) {
1727     ProbeManager = std::make_unique<PseudoProbeManager>(M);
1728     if (!ProbeManager->moduleIsProbed(M)) {
1729       const char *Msg =
1730           "Pseudo-probe-based profile requires SampleProfileProbePass";
1731       Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1732       return false;
1733     }
1734   }
1735 
1736   return true;
1737 }
1738 
1739 ModulePass *llvm::createSampleProfileLoaderPass() {
1740   return new SampleProfileLoaderLegacyPass();
1741 }
1742 
1743 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1744   return new SampleProfileLoaderLegacyPass(Name);
1745 }
1746 
1747 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1748                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
1749   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1750 
1751   PSI = _PSI;
1752   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1753     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1754                         ProfileSummary::PSK_Sample);
1755     PSI->refresh();
1756   }
1757   // Compute the total number of samples collected in this profile.
1758   for (const auto &I : Reader->getProfiles())
1759     TotalCollectedSamples += I.second.getTotalSamples();
1760 
1761   auto Remapper = Reader->getRemapper();
1762   // Populate the symbol map.
1763   for (const auto &N_F : M.getValueSymbolTable()) {
1764     StringRef OrigName = N_F.getKey();
1765     Function *F = dyn_cast<Function>(N_F.getValue());
1766     if (F == nullptr)
1767       continue;
1768     SymbolMap[OrigName] = F;
1769     auto pos = OrigName.find('.');
1770     if (pos != StringRef::npos) {
1771       StringRef NewName = OrigName.substr(0, pos);
1772       auto r = SymbolMap.insert(std::make_pair(NewName, F));
1773       // Failiing to insert means there is already an entry in SymbolMap,
1774       // thus there are multiple functions that are mapped to the same
1775       // stripped name. In this case of name conflicting, set the value
1776       // to nullptr to avoid confusion.
1777       if (!r.second)
1778         r.first->second = nullptr;
1779       OrigName = NewName;
1780     }
1781     // Insert the remapped names into SymbolMap.
1782     if (Remapper) {
1783       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1784         if (*MapName == OrigName)
1785           continue;
1786         SymbolMap.insert(std::make_pair(*MapName, F));
1787       }
1788     }
1789   }
1790 
1791   bool retval = false;
1792   for (auto F : buildFunctionOrder(M, CG)) {
1793     assert(!F->isDeclaration());
1794     clearFunctionData();
1795     retval |= runOnFunction(*F, AM);
1796   }
1797 
1798   // Account for cold calls not inlined....
1799   if (!ProfileIsCS)
1800     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
1801          notInlinedCallInfo)
1802       updateProfileCallee(pair.first, pair.second.entryCount);
1803 
1804   return retval;
1805 }
1806 
1807 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1808   ACT = &getAnalysis<AssumptionCacheTracker>();
1809   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1810   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
1811   ProfileSummaryInfo *PSI =
1812       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1813   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
1814 }
1815 
1816 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1817   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
1818   DILocation2SampleMap.clear();
1819   // By default the entry count is initialized to -1, which will be treated
1820   // conservatively by getEntryCount as the same as unknown (None). This is
1821   // to avoid newly added code to be treated as cold. If we have samples
1822   // this will be overwritten in emitAnnotations.
1823   uint64_t initialEntryCount = -1;
1824 
1825   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
1826   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
1827     // initialize all the function entry counts to 0. It means all the
1828     // functions without profile will be regarded as cold.
1829     initialEntryCount = 0;
1830     // profile-sample-accurate is a user assertion which has a higher precedence
1831     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
1832     ProfAccForSymsInList = false;
1833   }
1834   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
1835 
1836   // PSL -- profile symbol list include all the symbols in sampled binary.
1837   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
1838   // old functions without samples being cold, without having to worry
1839   // about new and hot functions being mistakenly treated as cold.
1840   if (ProfAccForSymsInList) {
1841     // Initialize the entry count to 0 for functions in the list.
1842     if (PSL->contains(F.getName()))
1843       initialEntryCount = 0;
1844 
1845     // Function in the symbol list but without sample will be regarded as
1846     // cold. To minimize the potential negative performance impact it could
1847     // have, we want to be a little conservative here saying if a function
1848     // shows up in the profile, no matter as outline function, inline instance
1849     // or call targets, treat the function as not being cold. This will handle
1850     // the cases such as most callsites of a function are inlined in sampled
1851     // binary but not inlined in current build (because of source code drift,
1852     // imprecise debug information, or the callsites are all cold individually
1853     // but not cold accumulatively...), so the outline function showing up as
1854     // cold in sampled binary will actually not be cold after current build.
1855     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
1856     if (NamesInProfile.count(CanonName))
1857       initialEntryCount = -1;
1858   }
1859 
1860   // Initialize entry count when the function has no existing entry
1861   // count value.
1862   if (!F.getEntryCount().hasValue())
1863     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
1864   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1865   if (AM) {
1866     auto &FAM =
1867         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1868             .getManager();
1869     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1870   } else {
1871     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
1872     ORE = OwnedORE.get();
1873   }
1874 
1875   if (ProfileIsCS)
1876     Samples = ContextTracker->getBaseSamplesFor(F);
1877   else
1878     Samples = Reader->getSamplesFor(F);
1879 
1880   if (Samples && !Samples->empty())
1881     return emitAnnotations(F);
1882   return false;
1883 }
1884 
1885 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1886                                                ModuleAnalysisManager &AM) {
1887   FunctionAnalysisManager &FAM =
1888       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1889 
1890   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1891     return FAM.getResult<AssumptionAnalysis>(F);
1892   };
1893   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1894     return FAM.getResult<TargetIRAnalysis>(F);
1895   };
1896   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
1897     return FAM.getResult<TargetLibraryAnalysis>(F);
1898   };
1899 
1900   SampleProfileLoader SampleLoader(
1901       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1902       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
1903                                        : ProfileRemappingFileName,
1904       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
1905 
1906   if (!SampleLoader.doInitialization(M, &FAM))
1907     return PreservedAnalyses::all();
1908 
1909   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1910   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
1911   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
1912     return PreservedAnalyses::all();
1913 
1914   return PreservedAnalyses::none();
1915 }
1916