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