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