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