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