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