xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfile.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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/SCCIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringMap.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/AssumptionCache.h"
38 #include "llvm/Analysis/CallGraph.h"
39 #include "llvm/Analysis/CallGraphSCCPass.h"
40 #include "llvm/Analysis/InlineAdvisor.h"
41 #include "llvm/Analysis/InlineCost.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/PostDominators.h"
45 #include "llvm/Analysis/ProfileSummaryInfo.h"
46 #include "llvm/Analysis/ReplayInlineAdvisor.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/IR/BasicBlock.h"
50 #include "llvm/IR/CFG.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DiagnosticInfo.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/IR/MDBuilder.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/PassManager.h"
65 #include "llvm/IR/ValueSymbolTable.h"
66 #include "llvm/InitializePasses.h"
67 #include "llvm/Pass.h"
68 #include "llvm/ProfileData/InstrProf.h"
69 #include "llvm/ProfileData/SampleProf.h"
70 #include "llvm/ProfileData/SampleProfReader.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ErrorOr.h"
76 #include "llvm/Support/GenericDomTree.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/IPO.h"
79 #include "llvm/Transforms/IPO/SampleContextTracker.h"
80 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
81 #include "llvm/Transforms/Instrumentation.h"
82 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
83 #include "llvm/Transforms/Utils/Cloning.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstdint>
87 #include <functional>
88 #include <limits>
89 #include <map>
90 #include <memory>
91 #include <queue>
92 #include <string>
93 #include <system_error>
94 #include <utility>
95 #include <vector>
96 
97 using namespace llvm;
98 using namespace sampleprof;
99 using ProfileCount = Function::ProfileCount;
100 #define DEBUG_TYPE "sample-profile"
101 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
102 
103 STATISTIC(NumCSInlined,
104           "Number of functions inlined with context sensitive profile");
105 STATISTIC(NumCSNotInlined,
106           "Number of functions not inlined with context sensitive profile");
107 STATISTIC(NumMismatchedProfile,
108           "Number of functions with CFG mismatched profile");
109 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
110 
111 // Command line option to specify the file to read samples from. This is
112 // mainly used for debugging.
113 static cl::opt<std::string> SampleProfileFile(
114     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
115     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
116 
117 // The named file contains a set of transformations that may have been applied
118 // to the symbol names between the program from which the sample data was
119 // collected and the current program's symbols.
120 static cl::opt<std::string> SampleProfileRemappingFile(
121     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
122     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
123 
124 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
125     "sample-profile-max-propagate-iterations", cl::init(100),
126     cl::desc("Maximum number of iterations to go through when propagating "
127              "sample block/edge weights through the CFG."));
128 
129 static cl::opt<unsigned> SampleProfileRecordCoverage(
130     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
131     cl::desc("Emit a warning if less than N% of records in the input profile "
132              "are matched to the IR."));
133 
134 static cl::opt<unsigned> SampleProfileSampleCoverage(
135     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
136     cl::desc("Emit a warning if less than N% of samples in the input profile "
137              "are matched to the IR."));
138 
139 static cl::opt<bool> NoWarnSampleUnused(
140     "no-warn-sample-unused", cl::init(false), cl::Hidden,
141     cl::desc("Use this option to turn off/on warnings about function with "
142              "samples but without debug information to use those samples. "));
143 
144 static cl::opt<bool> ProfileSampleAccurate(
145     "profile-sample-accurate", cl::Hidden, cl::init(false),
146     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
147              "callsite and function as having 0 samples. Otherwise, treat "
148              "un-sampled callsites and functions conservatively as unknown. "));
149 
150 static cl::opt<bool> ProfileAccurateForSymsInList(
151     "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
152     cl::init(true),
153     cl::desc("For symbols in profile symbol list, regard their profiles to "
154              "be accurate. It may be overriden by profile-sample-accurate. "));
155 
156 static cl::opt<bool> ProfileMergeInlinee(
157     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
158     cl::desc("Merge past inlinee's profile to outline version if sample "
159              "profile loader decided not to inline a call site. It will "
160              "only be enabled when top-down order of profile loading is "
161              "enabled. "));
162 
163 static cl::opt<bool> ProfileTopDownLoad(
164     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
165     cl::desc("Do profile annotation and inlining for functions in top-down "
166              "order of call graph during sample profile loading. It only "
167              "works for new pass manager. "));
168 
169 static cl::opt<bool> ProfileSizeInline(
170     "sample-profile-inline-size", cl::Hidden, cl::init(false),
171     cl::desc("Inline cold call sites in profile loader if it's beneficial "
172              "for code size."));
173 
174 static cl::opt<int> SampleColdCallSiteThreshold(
175     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
176     cl::desc("Threshold for inlining cold callsites"));
177 
178 static cl::opt<std::string> ProfileInlineReplayFile(
179     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
180     cl::desc(
181         "Optimization remarks file containing inline remarks to be replayed "
182         "by inlining from sample profile loader."),
183     cl::Hidden);
184 
185 namespace {
186 
187 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
188 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
189 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
190 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
191 using BlockEdgeMap =
192     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
193 
194 class SampleProfileLoader;
195 
196 class SampleCoverageTracker {
197 public:
198   SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){};
199 
200   bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
201                        uint32_t Discriminator, uint64_t Samples);
202   unsigned computeCoverage(unsigned Used, unsigned Total) const;
203   unsigned countUsedRecords(const FunctionSamples *FS,
204                             ProfileSummaryInfo *PSI) const;
205   unsigned countBodyRecords(const FunctionSamples *FS,
206                             ProfileSummaryInfo *PSI) const;
207   uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
208   uint64_t countBodySamples(const FunctionSamples *FS,
209                             ProfileSummaryInfo *PSI) const;
210 
211   void clear() {
212     SampleCoverage.clear();
213     TotalUsedSamples = 0;
214   }
215 
216 private:
217   using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
218   using FunctionSamplesCoverageMap =
219       DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
220 
221   /// Coverage map for sampling records.
222   ///
223   /// This map keeps a record of sampling records that have been matched to
224   /// an IR instruction. This is used to detect some form of staleness in
225   /// profiles (see flag -sample-profile-check-coverage).
226   ///
227   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
228   /// another map that counts how many times the sample record at the
229   /// given location has been used.
230   FunctionSamplesCoverageMap SampleCoverage;
231 
232   /// Number of samples used from the profile.
233   ///
234   /// When a sampling record is used for the first time, the samples from
235   /// that record are added to this accumulator.  Coverage is later computed
236   /// based on the total number of samples available in this function and
237   /// its callsites.
238   ///
239   /// Note that this accumulator tracks samples used from a single function
240   /// and all the inlined callsites. Strictly, we should have a map of counters
241   /// keyed by FunctionSamples pointers, but these stats are cleared after
242   /// every function, so we just need to keep a single counter.
243   uint64_t TotalUsedSamples = 0;
244 
245   SampleProfileLoader &SPLoader;
246 };
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 /// Sample profile pass.
317 ///
318 /// This pass reads profile data from the file specified by
319 /// -sample-profile-file and annotates every affected function with the
320 /// profile information found in that file.
321 class SampleProfileLoader {
322 public:
323   SampleProfileLoader(
324       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
325       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
326       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
327       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
328       : GetAC(std::move(GetAssumptionCache)),
329         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
330         CoverageTracker(*this), Filename(std::string(Name)),
331         RemappingFilename(std::string(RemapName)), LTOPhase(LTOPhase) {}
332 
333   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
334   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
335                    ProfileSummaryInfo *_PSI, CallGraph *CG);
336 
337   void dump() { Reader->dump(); }
338 
339 protected:
340   friend class SampleCoverageTracker;
341 
342   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
343   unsigned getFunctionLoc(Function &F);
344   bool emitAnnotations(Function &F);
345   ErrorOr<uint64_t> getInstWeight(const Instruction &I);
346   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
347   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
348   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
349   std::vector<const FunctionSamples *>
350   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
351   mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap;
352   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
353   bool inlineCallInstruction(CallBase &CB);
354   bool inlineHotFunctions(Function &F,
355                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
356   // Inline cold/small functions in addition to hot ones
357   bool shouldInlineColdCallee(CallBase &CallInst);
358   void emitOptimizationRemarksForInlineCandidates(
359       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
360       bool Hot);
361   void printEdgeWeight(raw_ostream &OS, Edge E);
362   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
363   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
364   bool computeBlockWeights(Function &F);
365   void findEquivalenceClasses(Function &F);
366   template <bool IsPostDom>
367   void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
368                            DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
369 
370   void propagateWeights(Function &F);
371   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
372   void buildEdges(Function &F);
373   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
374   bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
375   void computeDominanceAndLoopInfo(Function &F);
376   void clearFunctionData();
377   bool callsiteIsHot(const FunctionSamples *CallsiteFS,
378                      ProfileSummaryInfo *PSI);
379 
380   /// Map basic blocks to their computed weights.
381   ///
382   /// The weight of a basic block is defined to be the maximum
383   /// of all the instruction weights in that block.
384   BlockWeightMap BlockWeights;
385 
386   /// Map edges to their computed weights.
387   ///
388   /// Edge weights are computed by propagating basic block weights in
389   /// SampleProfile::propagateWeights.
390   EdgeWeightMap EdgeWeights;
391 
392   /// Set of visited blocks during propagation.
393   SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
394 
395   /// Set of visited edges during propagation.
396   SmallSet<Edge, 32> VisitedEdges;
397 
398   /// Equivalence classes for block weights.
399   ///
400   /// Two blocks BB1 and BB2 are in the same equivalence class if they
401   /// dominate and post-dominate each other, and they are in the same loop
402   /// nest. When this happens, the two blocks are guaranteed to execute
403   /// the same number of times.
404   EquivalenceClassMap EquivalenceClass;
405 
406   /// Map from function name to Function *. Used to find the function from
407   /// the function name. If the function name contains suffix, additional
408   /// entry is added to map from the stripped name to the function if there
409   /// is one-to-one mapping.
410   StringMap<Function *> SymbolMap;
411 
412   /// Dominance, post-dominance and loop information.
413   std::unique_ptr<DominatorTree> DT;
414   std::unique_ptr<PostDominatorTree> PDT;
415   std::unique_ptr<LoopInfo> LI;
416 
417   std::function<AssumptionCache &(Function &)> GetAC;
418   std::function<TargetTransformInfo &(Function &)> GetTTI;
419   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
420 
421   /// Predecessors for each basic block in the CFG.
422   BlockEdgeMap Predecessors;
423 
424   /// Successors for each basic block in the CFG.
425   BlockEdgeMap Successors;
426 
427   SampleCoverageTracker CoverageTracker;
428 
429   /// Profile reader object.
430   std::unique_ptr<SampleProfileReader> Reader;
431 
432   /// Profile tracker for different context.
433   std::unique_ptr<SampleContextTracker> ContextTracker;
434 
435   /// Samples collected for the body of this function.
436   FunctionSamples *Samples = nullptr;
437 
438   /// Name of the profile file to load.
439   std::string Filename;
440 
441   /// Name of the profile remapping file to load.
442   std::string RemappingFilename;
443 
444   /// Flag indicating whether the profile input loaded successfully.
445   bool ProfileIsValid = false;
446 
447   /// Flag indicating whether input profile is context-sensitive
448   bool ProfileIsCS = false;
449 
450   /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
451   ///
452   /// We need to know the LTO phase because for example in ThinLTOPrelink
453   /// phase, in annotation, we should not promote indirect calls. Instead,
454   /// we will mark GUIDs that needs to be annotated to the function.
455   ThinOrFullLTOPhase LTOPhase;
456 
457   /// Profile Summary Info computed from sample profile.
458   ProfileSummaryInfo *PSI = nullptr;
459 
460   /// Profle Symbol list tells whether a function name appears in the binary
461   /// used to generate the current profile.
462   std::unique_ptr<ProfileSymbolList> PSL;
463 
464   /// Total number of samples collected in this profile.
465   ///
466   /// This is the sum of all the samples collected in all the functions executed
467   /// at runtime.
468   uint64_t TotalCollectedSamples = 0;
469 
470   /// Optimization Remark Emitter used to emit diagnostic remarks.
471   OptimizationRemarkEmitter *ORE = nullptr;
472 
473   // Information recorded when we declined to inline a call site
474   // because we have determined it is too cold is accumulated for
475   // each callee function. Initially this is just the entry count.
476   struct NotInlinedProfileInfo {
477     uint64_t entryCount;
478   };
479   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
480 
481   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
482   // all the function symbols defined or declared in current module.
483   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
484 
485   // All the Names used in FunctionSamples including outline function
486   // names, inline instance names and call target names.
487   StringSet<> NamesInProfile;
488 
489   // For symbol in profile symbol list, whether to regard their profiles
490   // to be accurate. It is mainly decided by existance of profile symbol
491   // list and -profile-accurate-for-symsinlist flag, but it can be
492   // overriden by -profile-sample-accurate or profile-sample-accurate
493   // attribute.
494   bool ProfAccForSymsInList;
495 
496   // External inline advisor used to replay inline decision from remarks.
497   std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor;
498 
499   // A pseudo probe helper to correlate the imported sample counts.
500   std::unique_ptr<PseudoProbeManager> ProbeManager;
501 };
502 
503 class SampleProfileLoaderLegacyPass : public ModulePass {
504 public:
505   // Class identification, replacement for typeinfo
506   static char ID;
507 
508   SampleProfileLoaderLegacyPass(
509       StringRef Name = SampleProfileFile,
510       ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None)
511       : ModulePass(ID), SampleLoader(
512                             Name, SampleProfileRemappingFile, LTOPhase,
513                             [&](Function &F) -> AssumptionCache & {
514                               return ACT->getAssumptionCache(F);
515                             },
516                             [&](Function &F) -> TargetTransformInfo & {
517                               return TTIWP->getTTI(F);
518                             },
519                             [&](Function &F) -> TargetLibraryInfo & {
520                               return TLIWP->getTLI(F);
521                             }) {
522     initializeSampleProfileLoaderLegacyPassPass(
523         *PassRegistry::getPassRegistry());
524   }
525 
526   void dump() { SampleLoader.dump(); }
527 
528   bool doInitialization(Module &M) override {
529     return SampleLoader.doInitialization(M);
530   }
531 
532   StringRef getPassName() const override { return "Sample profile pass"; }
533   bool runOnModule(Module &M) override;
534 
535   void getAnalysisUsage(AnalysisUsage &AU) const override {
536     AU.addRequired<AssumptionCacheTracker>();
537     AU.addRequired<TargetTransformInfoWrapperPass>();
538     AU.addRequired<TargetLibraryInfoWrapperPass>();
539     AU.addRequired<ProfileSummaryInfoWrapperPass>();
540   }
541 
542 private:
543   SampleProfileLoader SampleLoader;
544   AssumptionCacheTracker *ACT = nullptr;
545   TargetTransformInfoWrapperPass *TTIWP = nullptr;
546   TargetLibraryInfoWrapperPass *TLIWP = nullptr;
547 };
548 
549 } // end anonymous namespace
550 
551 /// Return true if the given callsite is hot wrt to hot cutoff threshold.
552 ///
553 /// Functions that were inlined in the original binary will be represented
554 /// in the inline stack in the sample profile. If the profile shows that
555 /// the original inline decision was "good" (i.e., the callsite is executed
556 /// frequently), then we will recreate the inline decision and apply the
557 /// profile from the inlined callsite.
558 ///
559 /// To decide whether an inlined callsite is hot, we compare the callsite
560 /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
561 /// regarded as hot if the count is above the cutoff value.
562 ///
563 /// When ProfileAccurateForSymsInList is enabled and profile symbol list
564 /// is present, functions in the profile symbol list but without profile will
565 /// be regarded as cold and much less inlining will happen in CGSCC inlining
566 /// pass, so we tend to lower the hot criteria here to allow more early
567 /// inlining to happen for warm callsites and it is helpful for performance.
568 bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS,
569                                         ProfileSummaryInfo *PSI) {
570   if (!CallsiteFS)
571     return false; // The callsite was not inlined in the original binary.
572 
573   assert(PSI && "PSI is expected to be non null");
574   uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
575   if (ProfAccForSymsInList)
576     return !PSI->isColdCount(CallsiteTotalSamples);
577   else
578     return PSI->isHotCount(CallsiteTotalSamples);
579 }
580 
581 /// Mark as used the sample record for the given function samples at
582 /// (LineOffset, Discriminator).
583 ///
584 /// \returns true if this is the first time we mark the given record.
585 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
586                                             uint32_t LineOffset,
587                                             uint32_t Discriminator,
588                                             uint64_t Samples) {
589   LineLocation Loc(LineOffset, Discriminator);
590   unsigned &Count = SampleCoverage[FS][Loc];
591   bool FirstTime = (++Count == 1);
592   if (FirstTime)
593     TotalUsedSamples += Samples;
594   return FirstTime;
595 }
596 
597 /// Return the number of sample records that were applied from this profile.
598 ///
599 /// This count does not include records from cold inlined callsites.
600 unsigned
601 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
602                                         ProfileSummaryInfo *PSI) const {
603   auto I = SampleCoverage.find(FS);
604 
605   // The size of the coverage map for FS represents the number of records
606   // that were marked used at least once.
607   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
608 
609   // If there are inlined callsites in this function, count the samples found
610   // in the respective bodies. However, do not bother counting callees with 0
611   // total samples, these are callees that were never invoked at runtime.
612   for (const auto &I : FS->getCallsiteSamples())
613     for (const auto &J : I.second) {
614       const FunctionSamples *CalleeSamples = &J.second;
615       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
616         Count += countUsedRecords(CalleeSamples, PSI);
617     }
618 
619   return Count;
620 }
621 
622 /// Return the number of sample records in the body of this profile.
623 ///
624 /// This count does not include records from cold inlined callsites.
625 unsigned
626 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
627                                         ProfileSummaryInfo *PSI) const {
628   unsigned Count = FS->getBodySamples().size();
629 
630   // Only count records in hot callsites.
631   for (const auto &I : FS->getCallsiteSamples())
632     for (const auto &J : I.second) {
633       const FunctionSamples *CalleeSamples = &J.second;
634       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
635         Count += countBodyRecords(CalleeSamples, PSI);
636     }
637 
638   return Count;
639 }
640 
641 /// Return the number of samples collected in the body of this profile.
642 ///
643 /// This count does not include samples from cold inlined callsites.
644 uint64_t
645 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
646                                         ProfileSummaryInfo *PSI) const {
647   uint64_t Total = 0;
648   for (const auto &I : FS->getBodySamples())
649     Total += I.second.getSamples();
650 
651   // Only count samples in hot callsites.
652   for (const auto &I : FS->getCallsiteSamples())
653     for (const auto &J : I.second) {
654       const FunctionSamples *CalleeSamples = &J.second;
655       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
656         Total += countBodySamples(CalleeSamples, PSI);
657     }
658 
659   return Total;
660 }
661 
662 /// Return the fraction of sample records used in this profile.
663 ///
664 /// The returned value is an unsigned integer in the range 0-100 indicating
665 /// the percentage of sample records that were used while applying this
666 /// profile to the associated function.
667 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
668                                                 unsigned Total) const {
669   assert(Used <= Total &&
670          "number of used records cannot exceed the total number of records");
671   return Total > 0 ? Used * 100 / Total : 100;
672 }
673 
674 /// Clear all the per-function data used to load samples and propagate weights.
675 void SampleProfileLoader::clearFunctionData() {
676   BlockWeights.clear();
677   EdgeWeights.clear();
678   VisitedBlocks.clear();
679   VisitedEdges.clear();
680   EquivalenceClass.clear();
681   DT = nullptr;
682   PDT = nullptr;
683   LI = nullptr;
684   Predecessors.clear();
685   Successors.clear();
686   CoverageTracker.clear();
687 }
688 
689 #ifndef NDEBUG
690 /// Print the weight of edge \p E on stream \p OS.
691 ///
692 /// \param OS  Stream to emit the output to.
693 /// \param E  Edge to print.
694 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
695   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
696      << "]: " << EdgeWeights[E] << "\n";
697 }
698 
699 /// Print the equivalence class of block \p BB on stream \p OS.
700 ///
701 /// \param OS  Stream to emit the output to.
702 /// \param BB  Block to print.
703 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
704                                                 const BasicBlock *BB) {
705   const BasicBlock *Equiv = EquivalenceClass[BB];
706   OS << "equivalence[" << BB->getName()
707      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
708 }
709 
710 /// Print the weight of block \p BB on stream \p OS.
711 ///
712 /// \param OS  Stream to emit the output to.
713 /// \param BB  Block to print.
714 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
715                                            const BasicBlock *BB) const {
716   const auto &I = BlockWeights.find(BB);
717   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
718   OS << "weight[" << BB->getName() << "]: " << W << "\n";
719 }
720 #endif
721 
722 /// Get the weight for an instruction.
723 ///
724 /// The "weight" of an instruction \p Inst is the number of samples
725 /// collected on that instruction at runtime. To retrieve it, we
726 /// need to compute the line number of \p Inst relative to the start of its
727 /// function. We use HeaderLineno to compute the offset. We then
728 /// look up the samples collected for \p Inst using BodySamples.
729 ///
730 /// \param Inst Instruction to query.
731 ///
732 /// \returns the weight of \p Inst.
733 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
734   if (FunctionSamples::ProfileIsProbeBased)
735     return getProbeWeight(Inst);
736 
737   const DebugLoc &DLoc = Inst.getDebugLoc();
738   if (!DLoc)
739     return std::error_code();
740 
741   const FunctionSamples *FS = findFunctionSamples(Inst);
742   if (!FS)
743     return std::error_code();
744 
745   // Ignore all intrinsics, phinodes and branch instructions.
746   // Branch and phinodes instruction usually contains debug info from sources outside of
747   // the residing basic block, thus we ignore them during annotation.
748   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
749     return std::error_code();
750 
751   // If a direct call/invoke instruction is inlined in profile
752   // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
753   // it means that the inlined callsite has no sample, thus the call
754   // instruction should have 0 count.
755   if (!ProfileIsCS)
756     if (const auto *CB = dyn_cast<CallBase>(&Inst))
757       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
758         return 0;
759 
760   const DILocation *DIL = DLoc;
761   uint32_t LineOffset = FunctionSamples::getOffset(DIL);
762   uint32_t Discriminator = DIL->getBaseDiscriminator();
763   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
764   if (R) {
765     bool FirstMark =
766         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
767     if (FirstMark) {
768       ORE->emit([&]() {
769         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
770         Remark << "Applied " << ore::NV("NumSamples", *R);
771         Remark << " samples from profile (offset: ";
772         Remark << ore::NV("LineOffset", LineOffset);
773         if (Discriminator) {
774           Remark << ".";
775           Remark << ore::NV("Discriminator", Discriminator);
776         }
777         Remark << ")";
778         return Remark;
779       });
780     }
781     LLVM_DEBUG(dbgs() << "    " << DLoc.getLine() << "."
782                       << DIL->getBaseDiscriminator() << ":" << Inst
783                       << " (line offset: " << LineOffset << "."
784                       << DIL->getBaseDiscriminator() << " - weight: " << R.get()
785                       << ")\n");
786   }
787   return R;
788 }
789 
790 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
791   assert(FunctionSamples::ProfileIsProbeBased &&
792          "Profile is not pseudo probe based");
793   Optional<PseudoProbe> Probe = extractProbe(Inst);
794   if (!Probe)
795     return std::error_code();
796 
797   const FunctionSamples *FS = findFunctionSamples(Inst);
798   if (!FS)
799     return std::error_code();
800 
801   // If a direct call/invoke instruction is inlined in profile
802   // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
803   // it means that the inlined callsite has no sample, thus the call
804   // instruction should have 0 count.
805   if (const auto *CB = dyn_cast<CallBase>(&Inst))
806     if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
807       return 0;
808 
809   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
810   if (R) {
811     uint64_t Samples = R.get();
812     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
813     if (FirstMark) {
814       ORE->emit([&]() {
815         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
816         Remark << "Applied " << ore::NV("NumSamples", Samples);
817         Remark << " samples from profile (ProbeId=";
818         Remark << ore::NV("ProbeId", Probe->Id);
819         Remark << ")";
820         return Remark;
821       });
822     }
823 
824     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
825                       << " - weight: " << R.get() << ")\n");
826     return Samples;
827   }
828   return R;
829 }
830 
831 /// Compute the weight of a basic block.
832 ///
833 /// The weight of basic block \p BB is the maximum weight of all the
834 /// instructions in BB.
835 ///
836 /// \param BB The basic block to query.
837 ///
838 /// \returns the weight for \p BB.
839 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
840   uint64_t Max = 0;
841   bool HasWeight = false;
842   for (auto &I : BB->getInstList()) {
843     const ErrorOr<uint64_t> &R = getInstWeight(I);
844     if (R) {
845       Max = std::max(Max, R.get());
846       HasWeight = true;
847     }
848   }
849   return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
850 }
851 
852 /// Compute and store the weights of every basic block.
853 ///
854 /// This populates the BlockWeights map by computing
855 /// the weights of every basic block in the CFG.
856 ///
857 /// \param F The function to query.
858 bool SampleProfileLoader::computeBlockWeights(Function &F) {
859   bool Changed = false;
860   LLVM_DEBUG(dbgs() << "Block weights\n");
861   for (const auto &BB : F) {
862     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
863     if (Weight) {
864       BlockWeights[&BB] = Weight.get();
865       VisitedBlocks.insert(&BB);
866       Changed = true;
867     }
868     LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
869   }
870 
871   return Changed;
872 }
873 
874 /// Get the FunctionSamples for a call instruction.
875 ///
876 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
877 /// instance in which that call instruction is calling to. It contains
878 /// all samples that resides in the inlined instance. We first find the
879 /// inlined instance in which the call instruction is from, then we
880 /// traverse its children to find the callsite with the matching
881 /// location.
882 ///
883 /// \param Inst Call/Invoke instruction to query.
884 ///
885 /// \returns The FunctionSamples pointer to the inlined instance.
886 const FunctionSamples *
887 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
888   const DILocation *DIL = Inst.getDebugLoc();
889   if (!DIL) {
890     return nullptr;
891   }
892 
893   StringRef CalleeName;
894   if (Function *Callee = Inst.getCalledFunction())
895     CalleeName = FunctionSamples::getCanonicalFnName(*Callee);
896 
897   if (ProfileIsCS)
898     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
899 
900   const FunctionSamples *FS = findFunctionSamples(Inst);
901   if (FS == nullptr)
902     return nullptr;
903 
904   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
905                                    CalleeName, Reader->getRemapper());
906 }
907 
908 /// Returns a vector of FunctionSamples that are the indirect call targets
909 /// of \p Inst. The vector is sorted by the total number of samples. Stores
910 /// the total call count of the indirect call in \p Sum.
911 std::vector<const FunctionSamples *>
912 SampleProfileLoader::findIndirectCallFunctionSamples(
913     const Instruction &Inst, uint64_t &Sum) const {
914   const DILocation *DIL = Inst.getDebugLoc();
915   std::vector<const FunctionSamples *> R;
916 
917   if (!DIL) {
918     return R;
919   }
920 
921   const FunctionSamples *FS = findFunctionSamples(Inst);
922   if (FS == nullptr)
923     return R;
924 
925   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
926   auto T = FS->findCallTargetMapAt(CallSite);
927   Sum = 0;
928   if (T)
929     for (const auto &T_C : T.get())
930       Sum += T_C.second;
931   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
932     if (M->empty())
933       return R;
934     for (const auto &NameFS : *M) {
935       Sum += NameFS.second.getEntrySamples();
936       R.push_back(&NameFS.second);
937     }
938     llvm::sort(R, [](const FunctionSamples *L, const FunctionSamples *R) {
939       if (L->getEntrySamples() != R->getEntrySamples())
940         return L->getEntrySamples() > R->getEntrySamples();
941       return FunctionSamples::getGUID(L->getName()) <
942              FunctionSamples::getGUID(R->getName());
943     });
944   }
945   return R;
946 }
947 
948 /// Get the FunctionSamples for an instruction.
949 ///
950 /// The FunctionSamples of an instruction \p Inst is the inlined instance
951 /// in which that instruction is coming from. We traverse the inline stack
952 /// of that instruction, and match it with the tree nodes in the profile.
953 ///
954 /// \param Inst Instruction to query.
955 ///
956 /// \returns the FunctionSamples pointer to the inlined instance.
957 const FunctionSamples *
958 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
959   if (FunctionSamples::ProfileIsProbeBased) {
960     Optional<PseudoProbe> Probe = extractProbe(Inst);
961     if (!Probe)
962       return nullptr;
963   }
964 
965   const DILocation *DIL = Inst.getDebugLoc();
966   if (!DIL)
967     return Samples;
968 
969   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
970   if (it.second) {
971     if (ProfileIsCS)
972       it.first->second = ContextTracker->getContextSamplesFor(DIL);
973     else
974       it.first->second =
975           Samples->findFunctionSamples(DIL, Reader->getRemapper());
976   }
977   return it.first->second;
978 }
979 
980 bool SampleProfileLoader::inlineCallInstruction(CallBase &CB) {
981   if (ExternalInlineAdvisor) {
982     auto Advice = ExternalInlineAdvisor->getAdvice(CB);
983     if (!Advice->isInliningRecommended()) {
984       Advice->recordUnattemptedInlining();
985       return false;
986     }
987     // Dummy record, we don't use it for replay.
988     Advice->recordInlining();
989   }
990 
991   Function *CalledFunction = CB.getCalledFunction();
992   assert(CalledFunction);
993   DebugLoc DLoc = CB.getDebugLoc();
994   BasicBlock *BB = CB.getParent();
995   InlineParams Params = getInlineParams();
996   Params.ComputeFullInlineCost = true;
997   // Checks if there is anything in the reachable portion of the callee at
998   // this callsite that makes this inlining potentially illegal. Need to
999   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1000   // when cost exceeds threshold without checking all IRs in the callee.
1001   // The acutal cost does not matter because we only checks isNever() to
1002   // see if it is legal to inline the callsite.
1003   InlineCost Cost =
1004       getInlineCost(CB, Params, GetTTI(*CalledFunction), GetAC, GetTLI);
1005   if (Cost.isNever()) {
1006     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1007               << "incompatible inlining");
1008     return false;
1009   }
1010   InlineFunctionInfo IFI(nullptr, GetAC);
1011   if (InlineFunction(CB, IFI).isSuccess()) {
1012     // The call to InlineFunction erases I, so we can't pass it here.
1013     emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
1014                     true, CSINLINE_DEBUG);
1015     return true;
1016   }
1017   return false;
1018 }
1019 
1020 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
1021   if (!ProfileSizeInline)
1022     return false;
1023 
1024   Function *Callee = CallInst.getCalledFunction();
1025   if (Callee == nullptr)
1026     return false;
1027 
1028   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
1029                                   GetAC, GetTLI);
1030 
1031   if (Cost.isNever())
1032     return false;
1033 
1034   if (Cost.isAlways())
1035     return true;
1036 
1037   return Cost.getCost() <= SampleColdCallSiteThreshold;
1038 }
1039 
1040 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
1041     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
1042     bool Hot) {
1043   for (auto I : Candidates) {
1044     Function *CalledFunction = I->getCalledFunction();
1045     if (CalledFunction) {
1046       ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
1047                                            I->getDebugLoc(), I->getParent())
1048                 << "previous inlining reattempted for "
1049                 << (Hot ? "hotness: '" : "size: '")
1050                 << ore::NV("Callee", CalledFunction) << "' into '"
1051                 << ore::NV("Caller", &F) << "'");
1052     }
1053   }
1054 }
1055 
1056 /// Iteratively inline hot callsites of a function.
1057 ///
1058 /// Iteratively traverse all callsites of the function \p F, and find if
1059 /// the corresponding inlined instance exists and is hot in profile. If
1060 /// it is hot enough, inline the callsites and adds new callsites of the
1061 /// callee into the caller. If the call is an indirect call, first promote
1062 /// it to direct call. Each indirect call is limited with a single target.
1063 ///
1064 /// \param F function to perform iterative inlining.
1065 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1066 ///     inlined in the profiled binary.
1067 ///
1068 /// \returns True if there is any inline happened.
1069 bool SampleProfileLoader::inlineHotFunctions(
1070     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1071   DenseSet<Instruction *> PromotedInsns;
1072 
1073   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1074   // Profile symbol list is ignored when profile-sample-accurate is on.
1075   assert((!ProfAccForSymsInList ||
1076           (!ProfileSampleAccurate &&
1077            !F.hasFnAttribute("profile-sample-accurate"))) &&
1078          "ProfAccForSymsInList should be false when profile-sample-accurate "
1079          "is enabled");
1080 
1081   DenseMap<CallBase *, const FunctionSamples *> localNotInlinedCallSites;
1082   bool Changed = false;
1083   while (true) {
1084     bool LocalChanged = false;
1085     SmallVector<CallBase *, 10> CIS;
1086     for (auto &BB : F) {
1087       bool Hot = false;
1088       SmallVector<CallBase *, 10> AllCandidates;
1089       SmallVector<CallBase *, 10> ColdCandidates;
1090       for (auto &I : BB.getInstList()) {
1091         const FunctionSamples *FS = nullptr;
1092         if (auto *CB = dyn_cast<CallBase>(&I)) {
1093           if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
1094             assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1095                    "GUIDToFuncNameMap has to be populated");
1096             AllCandidates.push_back(CB);
1097             if (FS->getEntrySamples() > 0 || ProfileIsCS)
1098               localNotInlinedCallSites.try_emplace(CB, FS);
1099             if (callsiteIsHot(FS, PSI))
1100               Hot = true;
1101             else if (shouldInlineColdCallee(*CB))
1102               ColdCandidates.push_back(CB);
1103           }
1104         }
1105       }
1106       if (Hot || ExternalInlineAdvisor) {
1107         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1108         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1109       } else {
1110         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1111         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1112       }
1113     }
1114     for (CallBase *I : CIS) {
1115       Function *CalledFunction = I->getCalledFunction();
1116       // Do not inline recursive calls.
1117       if (CalledFunction == &F)
1118         continue;
1119       if (I->isIndirectCall()) {
1120         if (PromotedInsns.count(I))
1121           continue;
1122         uint64_t Sum;
1123         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1124           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1125             FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
1126                                      PSI->getOrCompHotCountThreshold());
1127             continue;
1128           }
1129           if (!callsiteIsHot(FS, PSI))
1130             continue;
1131 
1132           const char *Reason = "Callee function not available";
1133           // R->getValue() != &F is to prevent promoting a recursive call.
1134           // If it is a recursive call, we do not inline it as it could bloat
1135           // the code exponentially. There is way to better handle this, e.g.
1136           // clone the caller first, and inline the cloned caller if it is
1137           // recursive. As llvm does not inline recursive calls, we will
1138           // simply ignore it instead of handling it explicitly.
1139           auto CalleeFunctionName = FS->getFuncName();
1140           auto R = SymbolMap.find(CalleeFunctionName);
1141           if (R != SymbolMap.end() && R->getValue() &&
1142               !R->getValue()->isDeclaration() &&
1143               R->getValue()->getSubprogram() &&
1144               R->getValue()->hasFnAttribute("use-sample-profile") &&
1145               R->getValue() != &F &&
1146               isLegalToPromote(*I, R->getValue(), &Reason)) {
1147             uint64_t C = FS->getEntrySamples();
1148             auto &DI =
1149                 pgo::promoteIndirectCall(*I, R->getValue(), C, Sum, false, ORE);
1150             Sum -= C;
1151             PromotedInsns.insert(I);
1152             // If profile mismatches, we should not attempt to inline DI.
1153             if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
1154                 inlineCallInstruction(cast<CallBase>(DI))) {
1155               if (ProfileIsCS)
1156                 ContextTracker->markContextSamplesInlined(FS);
1157               localNotInlinedCallSites.erase(I);
1158               LocalChanged = true;
1159               ++NumCSInlined;
1160             }
1161           } else {
1162             LLVM_DEBUG(dbgs()
1163                        << "\nFailed to promote indirect call to "
1164                        << CalleeFunctionName << " because " << Reason << "\n");
1165           }
1166         }
1167       } else if (CalledFunction && CalledFunction->getSubprogram() &&
1168                  !CalledFunction->isDeclaration()) {
1169         if (inlineCallInstruction(*I)) {
1170           if (ProfileIsCS)
1171             ContextTracker->markContextSamplesInlined(
1172                 localNotInlinedCallSites[I]);
1173           localNotInlinedCallSites.erase(I);
1174           LocalChanged = true;
1175           ++NumCSInlined;
1176         }
1177       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1178         findCalleeFunctionSamples(*I)->findInlinedFunctions(
1179             InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
1180       }
1181     }
1182     if (LocalChanged) {
1183       Changed = true;
1184     } else {
1185       break;
1186     }
1187   }
1188 
1189   // Accumulate not inlined callsite information into notInlinedSamples
1190   for (const auto &Pair : localNotInlinedCallSites) {
1191     CallBase *I = Pair.getFirst();
1192     Function *Callee = I->getCalledFunction();
1193     if (!Callee || Callee->isDeclaration())
1194       continue;
1195 
1196     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1197                                          I->getDebugLoc(), I->getParent())
1198               << "previous inlining not repeated: '"
1199               << ore::NV("Callee", Callee) << "' into '"
1200               << ore::NV("Caller", &F) << "'");
1201 
1202     ++NumCSNotInlined;
1203     const FunctionSamples *FS = Pair.getSecond();
1204     if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1205       continue;
1206     }
1207 
1208     if (ProfileMergeInlinee) {
1209       // A function call can be replicated by optimizations like callsite
1210       // splitting or jump threading and the replicates end up sharing the
1211       // sample nested callee profile instead of slicing the original inlinee's
1212       // profile. We want to do merge exactly once by filtering out callee
1213       // profiles with a non-zero head sample count.
1214       if (FS->getHeadSamples() == 0) {
1215         // Use entry samples as head samples during the merge, as inlinees
1216         // don't have head samples.
1217         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1218             FS->getEntrySamples());
1219 
1220         // Note that we have to do the merge right after processing function.
1221         // This allows OutlineFS's profile to be used for annotation during
1222         // top-down processing of functions' annotation.
1223         FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1224         OutlineFS->merge(*FS);
1225       }
1226     } else {
1227       auto pair =
1228           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1229       pair.first->second.entryCount += FS->getEntrySamples();
1230     }
1231   }
1232   return Changed;
1233 }
1234 
1235 /// Find equivalence classes for the given block.
1236 ///
1237 /// This finds all the blocks that are guaranteed to execute the same
1238 /// number of times as \p BB1. To do this, it traverses all the
1239 /// descendants of \p BB1 in the dominator or post-dominator tree.
1240 ///
1241 /// A block BB2 will be in the same equivalence class as \p BB1 if
1242 /// the following holds:
1243 ///
1244 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
1245 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
1246 ///    dominate BB1 in the post-dominator tree.
1247 ///
1248 /// 2- Both BB2 and \p BB1 must be in the same loop.
1249 ///
1250 /// For every block BB2 that meets those two requirements, we set BB2's
1251 /// equivalence class to \p BB1.
1252 ///
1253 /// \param BB1  Block to check.
1254 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
1255 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
1256 ///                 with blocks from \p BB1's dominator tree, then
1257 ///                 this is the post-dominator tree, and vice versa.
1258 template <bool IsPostDom>
1259 void SampleProfileLoader::findEquivalencesFor(
1260     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
1261     DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
1262   const BasicBlock *EC = EquivalenceClass[BB1];
1263   uint64_t Weight = BlockWeights[EC];
1264   for (const auto *BB2 : Descendants) {
1265     bool IsDomParent = DomTree->dominates(BB2, BB1);
1266     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
1267     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
1268       EquivalenceClass[BB2] = EC;
1269       // If BB2 is visited, then the entire EC should be marked as visited.
1270       if (VisitedBlocks.count(BB2)) {
1271         VisitedBlocks.insert(EC);
1272       }
1273 
1274       // If BB2 is heavier than BB1, make BB2 have the same weight
1275       // as BB1.
1276       //
1277       // Note that we don't worry about the opposite situation here
1278       // (when BB2 is lighter than BB1). We will deal with this
1279       // during the propagation phase. Right now, we just want to
1280       // make sure that BB1 has the largest weight of all the
1281       // members of its equivalence set.
1282       Weight = std::max(Weight, BlockWeights[BB2]);
1283     }
1284   }
1285   if (EC == &EC->getParent()->getEntryBlock()) {
1286     BlockWeights[EC] = Samples->getHeadSamples() + 1;
1287   } else {
1288     BlockWeights[EC] = Weight;
1289   }
1290 }
1291 
1292 /// Find equivalence classes.
1293 ///
1294 /// Since samples may be missing from blocks, we can fill in the gaps by setting
1295 /// the weights of all the blocks in the same equivalence class to the same
1296 /// weight. To compute the concept of equivalence, we use dominance and loop
1297 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
1298 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1299 ///
1300 /// \param F The function to query.
1301 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
1302   SmallVector<BasicBlock *, 8> DominatedBBs;
1303   LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
1304   // Find equivalence sets based on dominance and post-dominance information.
1305   for (auto &BB : F) {
1306     BasicBlock *BB1 = &BB;
1307 
1308     // Compute BB1's equivalence class once.
1309     if (EquivalenceClass.count(BB1)) {
1310       LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1311       continue;
1312     }
1313 
1314     // By default, blocks are in their own equivalence class.
1315     EquivalenceClass[BB1] = BB1;
1316 
1317     // Traverse all the blocks dominated by BB1. We are looking for
1318     // every basic block BB2 such that:
1319     //
1320     // 1- BB1 dominates BB2.
1321     // 2- BB2 post-dominates BB1.
1322     // 3- BB1 and BB2 are in the same loop nest.
1323     //
1324     // If all those conditions hold, it means that BB2 is executed
1325     // as many times as BB1, so they are placed in the same equivalence
1326     // class by making BB2's equivalence class be BB1.
1327     DominatedBBs.clear();
1328     DT->getDescendants(BB1, DominatedBBs);
1329     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
1330 
1331     LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1332   }
1333 
1334   // Assign weights to equivalence classes.
1335   //
1336   // All the basic blocks in the same equivalence class will execute
1337   // the same number of times. Since we know that the head block in
1338   // each equivalence class has the largest weight, assign that weight
1339   // to all the blocks in that equivalence class.
1340   LLVM_DEBUG(
1341       dbgs() << "\nAssign the same weight to all blocks in the same class\n");
1342   for (auto &BI : F) {
1343     const BasicBlock *BB = &BI;
1344     const BasicBlock *EquivBB = EquivalenceClass[BB];
1345     if (BB != EquivBB)
1346       BlockWeights[BB] = BlockWeights[EquivBB];
1347     LLVM_DEBUG(printBlockWeight(dbgs(), BB));
1348   }
1349 }
1350 
1351 /// Visit the given edge to decide if it has a valid weight.
1352 ///
1353 /// If \p E has not been visited before, we copy to \p UnknownEdge
1354 /// and increment the count of unknown edges.
1355 ///
1356 /// \param E  Edge to visit.
1357 /// \param NumUnknownEdges  Current number of unknown edges.
1358 /// \param UnknownEdge  Set if E has not been visited before.
1359 ///
1360 /// \returns E's weight, if known. Otherwise, return 0.
1361 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
1362                                         Edge *UnknownEdge) {
1363   if (!VisitedEdges.count(E)) {
1364     (*NumUnknownEdges)++;
1365     *UnknownEdge = E;
1366     return 0;
1367   }
1368 
1369   return EdgeWeights[E];
1370 }
1371 
1372 /// Propagate weights through incoming/outgoing edges.
1373 ///
1374 /// If the weight of a basic block is known, and there is only one edge
1375 /// with an unknown weight, we can calculate the weight of that edge.
1376 ///
1377 /// Similarly, if all the edges have a known count, we can calculate the
1378 /// count of the basic block, if needed.
1379 ///
1380 /// \param F  Function to process.
1381 /// \param UpdateBlockCount  Whether we should update basic block counts that
1382 ///                          has already been annotated.
1383 ///
1384 /// \returns  True if new weights were assigned to edges or blocks.
1385 bool SampleProfileLoader::propagateThroughEdges(Function &F,
1386                                                 bool UpdateBlockCount) {
1387   bool Changed = false;
1388   LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
1389   for (const auto &BI : F) {
1390     const BasicBlock *BB = &BI;
1391     const BasicBlock *EC = EquivalenceClass[BB];
1392 
1393     // Visit all the predecessor and successor edges to determine
1394     // which ones have a weight assigned already. Note that it doesn't
1395     // matter that we only keep track of a single unknown edge. The
1396     // only case we are interested in handling is when only a single
1397     // edge is unknown (see setEdgeOrBlockWeight).
1398     for (unsigned i = 0; i < 2; i++) {
1399       uint64_t TotalWeight = 0;
1400       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1401       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1402 
1403       if (i == 0) {
1404         // First, visit all predecessor edges.
1405         NumTotalEdges = Predecessors[BB].size();
1406         for (auto *Pred : Predecessors[BB]) {
1407           Edge E = std::make_pair(Pred, BB);
1408           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1409           if (E.first == E.second)
1410             SelfReferentialEdge = E;
1411         }
1412         if (NumTotalEdges == 1) {
1413           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1414         }
1415       } else {
1416         // On the second round, visit all successor edges.
1417         NumTotalEdges = Successors[BB].size();
1418         for (auto *Succ : Successors[BB]) {
1419           Edge E = std::make_pair(BB, Succ);
1420           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1421         }
1422         if (NumTotalEdges == 1) {
1423           SingleEdge = std::make_pair(BB, Successors[BB][0]);
1424         }
1425       }
1426 
1427       // After visiting all the edges, there are three cases that we
1428       // can handle immediately:
1429       //
1430       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1431       //   In this case, we simply check that the sum of all the edges
1432       //   is the same as BB's weight. If not, we change BB's weight
1433       //   to match. Additionally, if BB had not been visited before,
1434       //   we mark it visited.
1435       //
1436       // - Only one edge is unknown and BB has already been visited.
1437       //   In this case, we can compute the weight of the edge by
1438       //   subtracting the total block weight from all the known
1439       //   edge weights. If the edges weight more than BB, then the
1440       //   edge of the last remaining edge is set to zero.
1441       //
1442       // - There exists a self-referential edge and the weight of BB is
1443       //   known. In this case, this edge can be based on BB's weight.
1444       //   We add up all the other known edges and set the weight on
1445       //   the self-referential edge as we did in the previous case.
1446       //
1447       // In any other case, we must continue iterating. Eventually,
1448       // all edges will get a weight, or iteration will stop when
1449       // it reaches SampleProfileMaxPropagateIterations.
1450       if (NumUnknownEdges <= 1) {
1451         uint64_t &BBWeight = BlockWeights[EC];
1452         if (NumUnknownEdges == 0) {
1453           if (!VisitedBlocks.count(EC)) {
1454             // If we already know the weight of all edges, the weight of the
1455             // basic block can be computed. It should be no larger than the sum
1456             // of all edge weights.
1457             if (TotalWeight > BBWeight) {
1458               BBWeight = TotalWeight;
1459               Changed = true;
1460               LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
1461                                 << " known. Set weight for block: ";
1462                          printBlockWeight(dbgs(), BB););
1463             }
1464           } else if (NumTotalEdges == 1 &&
1465                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1466             // If there is only one edge for the visited basic block, use the
1467             // block weight to adjust edge weight if edge weight is smaller.
1468             EdgeWeights[SingleEdge] = BlockWeights[EC];
1469             Changed = true;
1470           }
1471         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1472           // If there is a single unknown edge and the block has been
1473           // visited, then we can compute E's weight.
1474           if (BBWeight >= TotalWeight)
1475             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1476           else
1477             EdgeWeights[UnknownEdge] = 0;
1478           const BasicBlock *OtherEC;
1479           if (i == 0)
1480             OtherEC = EquivalenceClass[UnknownEdge.first];
1481           else
1482             OtherEC = EquivalenceClass[UnknownEdge.second];
1483           // Edge weights should never exceed the BB weights it connects.
1484           if (VisitedBlocks.count(OtherEC) &&
1485               EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1486             EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1487           VisitedEdges.insert(UnknownEdge);
1488           Changed = true;
1489           LLVM_DEBUG(dbgs() << "Set weight for edge: ";
1490                      printEdgeWeight(dbgs(), UnknownEdge));
1491         }
1492       } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1493         // If a block Weights 0, all its in/out edges should weight 0.
1494         if (i == 0) {
1495           for (auto *Pred : Predecessors[BB]) {
1496             Edge E = std::make_pair(Pred, BB);
1497             EdgeWeights[E] = 0;
1498             VisitedEdges.insert(E);
1499           }
1500         } else {
1501           for (auto *Succ : Successors[BB]) {
1502             Edge E = std::make_pair(BB, Succ);
1503             EdgeWeights[E] = 0;
1504             VisitedEdges.insert(E);
1505           }
1506         }
1507       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1508         uint64_t &BBWeight = BlockWeights[BB];
1509         // We have a self-referential edge and the weight of BB is known.
1510         if (BBWeight >= TotalWeight)
1511           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1512         else
1513           EdgeWeights[SelfReferentialEdge] = 0;
1514         VisitedEdges.insert(SelfReferentialEdge);
1515         Changed = true;
1516         LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
1517                    printEdgeWeight(dbgs(), SelfReferentialEdge));
1518       }
1519       if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1520         BlockWeights[EC] = TotalWeight;
1521         VisitedBlocks.insert(EC);
1522         Changed = true;
1523       }
1524     }
1525   }
1526 
1527   return Changed;
1528 }
1529 
1530 /// Build in/out edge lists for each basic block in the CFG.
1531 ///
1532 /// We are interested in unique edges. If a block B1 has multiple
1533 /// edges to another block B2, we only add a single B1->B2 edge.
1534 void SampleProfileLoader::buildEdges(Function &F) {
1535   for (auto &BI : F) {
1536     BasicBlock *B1 = &BI;
1537 
1538     // Add predecessors for B1.
1539     SmallPtrSet<BasicBlock *, 16> Visited;
1540     if (!Predecessors[B1].empty())
1541       llvm_unreachable("Found a stale predecessors list in a basic block.");
1542     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1543       BasicBlock *B2 = *PI;
1544       if (Visited.insert(B2).second)
1545         Predecessors[B1].push_back(B2);
1546     }
1547 
1548     // Add successors for B1.
1549     Visited.clear();
1550     if (!Successors[B1].empty())
1551       llvm_unreachable("Found a stale successors list in a basic block.");
1552     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1553       BasicBlock *B2 = *SI;
1554       if (Visited.insert(B2).second)
1555         Successors[B1].push_back(B2);
1556     }
1557   }
1558 }
1559 
1560 /// Returns the sorted CallTargetMap \p M by count in descending order.
1561 static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets(
1562     const SampleRecord::CallTargetMap & M) {
1563   SmallVector<InstrProfValueData, 2> R;
1564   for (const auto &I : SampleRecord::SortCallTargets(M)) {
1565     R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1566   }
1567   return R;
1568 }
1569 
1570 /// Propagate weights into edges
1571 ///
1572 /// The following rules are applied to every block BB in the CFG:
1573 ///
1574 /// - If BB has a single predecessor/successor, then the weight
1575 ///   of that edge is the weight of the block.
1576 ///
1577 /// - If all incoming or outgoing edges are known except one, and the
1578 ///   weight of the block is already known, the weight of the unknown
1579 ///   edge will be the weight of the block minus the sum of all the known
1580 ///   edges. If the sum of all the known edges is larger than BB's weight,
1581 ///   we set the unknown edge weight to zero.
1582 ///
1583 /// - If there is a self-referential edge, and the weight of the block is
1584 ///   known, the weight for that edge is set to the weight of the block
1585 ///   minus the weight of the other incoming edges to that block (if
1586 ///   known).
1587 void SampleProfileLoader::propagateWeights(Function &F) {
1588   bool Changed = true;
1589   unsigned I = 0;
1590 
1591   // If BB weight is larger than its corresponding loop's header BB weight,
1592   // use the BB weight to replace the loop header BB weight.
1593   for (auto &BI : F) {
1594     BasicBlock *BB = &BI;
1595     Loop *L = LI->getLoopFor(BB);
1596     if (!L) {
1597       continue;
1598     }
1599     BasicBlock *Header = L->getHeader();
1600     if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1601       BlockWeights[Header] = BlockWeights[BB];
1602     }
1603   }
1604 
1605   // Before propagation starts, build, for each block, a list of
1606   // unique predecessors and successors. This is necessary to handle
1607   // identical edges in multiway branches. Since we visit all blocks and all
1608   // edges of the CFG, it is cleaner to build these lists once at the start
1609   // of the pass.
1610   buildEdges(F);
1611 
1612   // Propagate until we converge or we go past the iteration limit.
1613   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1614     Changed = propagateThroughEdges(F, false);
1615   }
1616 
1617   // The first propagation propagates BB counts from annotated BBs to unknown
1618   // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1619   // to propagate edge weights.
1620   VisitedEdges.clear();
1621   Changed = true;
1622   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1623     Changed = propagateThroughEdges(F, false);
1624   }
1625 
1626   // The 3rd propagation pass allows adjust annotated BB weights that are
1627   // obviously wrong.
1628   Changed = true;
1629   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1630     Changed = propagateThroughEdges(F, true);
1631   }
1632 
1633   // Generate MD_prof metadata for every branch instruction using the
1634   // edge weights computed during propagation.
1635   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1636   LLVMContext &Ctx = F.getContext();
1637   MDBuilder MDB(Ctx);
1638   for (auto &BI : F) {
1639     BasicBlock *BB = &BI;
1640 
1641     if (BlockWeights[BB]) {
1642       for (auto &I : BB->getInstList()) {
1643         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1644           continue;
1645         if (!cast<CallBase>(I).getCalledFunction()) {
1646           const DebugLoc &DLoc = I.getDebugLoc();
1647           if (!DLoc)
1648             continue;
1649           const DILocation *DIL = DLoc;
1650           const FunctionSamples *FS = findFunctionSamples(I);
1651           if (!FS)
1652             continue;
1653           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1654           auto T = FS->findCallTargetMapAt(CallSite);
1655           if (!T || T.get().empty())
1656             continue;
1657           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1658               GetSortedValueDataFromCallTargets(T.get());
1659           uint64_t Sum;
1660           findIndirectCallFunctionSamples(I, Sum);
1661           annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1662                             SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1663                             SortedCallTargets.size());
1664         } else if (!isa<IntrinsicInst>(&I)) {
1665           I.setMetadata(LLVMContext::MD_prof,
1666                         MDB.createBranchWeights(
1667                             {static_cast<uint32_t>(BlockWeights[BB])}));
1668         }
1669       }
1670     }
1671     Instruction *TI = BB->getTerminator();
1672     if (TI->getNumSuccessors() == 1)
1673       continue;
1674     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1675       continue;
1676 
1677     DebugLoc BranchLoc = TI->getDebugLoc();
1678     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1679                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1680                                       : Twine("<UNKNOWN LOCATION>"))
1681                       << ".\n");
1682     SmallVector<uint32_t, 4> Weights;
1683     uint32_t MaxWeight = 0;
1684     Instruction *MaxDestInst;
1685     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1686       BasicBlock *Succ = TI->getSuccessor(I);
1687       Edge E = std::make_pair(BB, Succ);
1688       uint64_t Weight = EdgeWeights[E];
1689       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1690       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1691       // if needed. Sample counts in profiles are 64-bit unsigned values,
1692       // but internally branch weights are expressed as 32-bit values.
1693       if (Weight > std::numeric_limits<uint32_t>::max()) {
1694         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1695         Weight = std::numeric_limits<uint32_t>::max();
1696       }
1697       // Weight is added by one to avoid propagation errors introduced by
1698       // 0 weights.
1699       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1700       if (Weight != 0) {
1701         if (Weight > MaxWeight) {
1702           MaxWeight = Weight;
1703           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1704         }
1705       }
1706     }
1707 
1708     uint64_t TempWeight;
1709     // Only set weights if there is at least one non-zero weight.
1710     // In any other case, let the analyzer set weights.
1711     // Do not set weights if the weights are present. In ThinLTO, the profile
1712     // annotation is done twice. If the first annotation already set the
1713     // weights, the second pass does not need to set it.
1714     if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1715       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1716       TI->setMetadata(LLVMContext::MD_prof,
1717                       MDB.createBranchWeights(Weights));
1718       ORE->emit([&]() {
1719         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1720                << "most popular destination for conditional branches at "
1721                << ore::NV("CondBranchesLoc", BranchLoc);
1722       });
1723     } else {
1724       LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1725     }
1726   }
1727 }
1728 
1729 /// Get the line number for the function header.
1730 ///
1731 /// This looks up function \p F in the current compilation unit and
1732 /// retrieves the line number where the function is defined. This is
1733 /// line 0 for all the samples read from the profile file. Every line
1734 /// number is relative to this line.
1735 ///
1736 /// \param F  Function object to query.
1737 ///
1738 /// \returns the line number where \p F is defined. If it returns 0,
1739 ///          it means that there is no debug information available for \p F.
1740 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1741   if (DISubprogram *S = F.getSubprogram())
1742     return S->getLine();
1743 
1744   if (NoWarnSampleUnused)
1745     return 0;
1746 
1747   // If the start of \p F is missing, emit a diagnostic to inform the user
1748   // about the missed opportunity.
1749   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1750       "No debug information found in function " + F.getName() +
1751           ": Function profile not used",
1752       DS_Warning));
1753   return 0;
1754 }
1755 
1756 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1757   DT.reset(new DominatorTree);
1758   DT->recalculate(F);
1759 
1760   PDT.reset(new PostDominatorTree(F));
1761 
1762   LI.reset(new LoopInfo);
1763   LI->analyze(*DT);
1764 }
1765 
1766 /// Generate branch weight metadata for all branches in \p F.
1767 ///
1768 /// Branch weights are computed out of instruction samples using a
1769 /// propagation heuristic. Propagation proceeds in 3 phases:
1770 ///
1771 /// 1- Assignment of block weights. All the basic blocks in the function
1772 ///    are initial assigned the same weight as their most frequently
1773 ///    executed instruction.
1774 ///
1775 /// 2- Creation of equivalence classes. Since samples may be missing from
1776 ///    blocks, we can fill in the gaps by setting the weights of all the
1777 ///    blocks in the same equivalence class to the same weight. To compute
1778 ///    the concept of equivalence, we use dominance and loop information.
1779 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1780 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1781 ///
1782 /// 3- Propagation of block weights into edges. This uses a simple
1783 ///    propagation heuristic. The following rules are applied to every
1784 ///    block BB in the CFG:
1785 ///
1786 ///    - If BB has a single predecessor/successor, then the weight
1787 ///      of that edge is the weight of the block.
1788 ///
1789 ///    - If all the edges are known except one, and the weight of the
1790 ///      block is already known, the weight of the unknown edge will
1791 ///      be the weight of the block minus the sum of all the known
1792 ///      edges. If the sum of all the known edges is larger than BB's weight,
1793 ///      we set the unknown edge weight to zero.
1794 ///
1795 ///    - If there is a self-referential edge, and the weight of the block is
1796 ///      known, the weight for that edge is set to the weight of the block
1797 ///      minus the weight of the other incoming edges to that block (if
1798 ///      known).
1799 ///
1800 /// Since this propagation is not guaranteed to finalize for every CFG, we
1801 /// only allow it to proceed for a limited number of iterations (controlled
1802 /// by -sample-profile-max-propagate-iterations).
1803 ///
1804 /// FIXME: Try to replace this propagation heuristic with a scheme
1805 /// that is guaranteed to finalize. A work-list approach similar to
1806 /// the standard value propagation algorithm used by SSA-CCP might
1807 /// work here.
1808 ///
1809 /// Once all the branch weights are computed, we emit the MD_prof
1810 /// metadata on BB using the computed values for each of its branches.
1811 ///
1812 /// \param F The function to query.
1813 ///
1814 /// \returns true if \p F was modified. Returns false, otherwise.
1815 bool SampleProfileLoader::emitAnnotations(Function &F) {
1816   bool Changed = false;
1817 
1818   if (FunctionSamples::ProfileIsProbeBased) {
1819     if (!ProbeManager->profileIsValid(F, *Samples)) {
1820       LLVM_DEBUG(
1821           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1822                  << F.getName());
1823       ++NumMismatchedProfile;
1824       return false;
1825     }
1826     ++NumMatchedProfile;
1827   } else {
1828     if (getFunctionLoc(F) == 0)
1829       return false;
1830 
1831     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1832                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1833   }
1834 
1835   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1836   Changed |= inlineHotFunctions(F, InlinedGUIDs);
1837 
1838   // Compute basic block weights.
1839   Changed |= computeBlockWeights(F);
1840 
1841   if (Changed) {
1842     // Add an entry count to the function using the samples gathered at the
1843     // function entry.
1844     // Sets the GUIDs that are inlined in the profiled binary. This is used
1845     // for ThinLink to make correct liveness analysis, and also make the IR
1846     // match the profiled binary before annotation.
1847     F.setEntryCount(
1848         ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1849         &InlinedGUIDs);
1850 
1851     // Compute dominance and loop info needed for propagation.
1852     computeDominanceAndLoopInfo(F);
1853 
1854     // Find equivalence classes.
1855     findEquivalenceClasses(F);
1856 
1857     // Propagate weights to all edges.
1858     propagateWeights(F);
1859   }
1860 
1861   // If coverage checking was requested, compute it now.
1862   if (SampleProfileRecordCoverage) {
1863     unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1864     unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1865     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1866     if (Coverage < SampleProfileRecordCoverage) {
1867       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1868           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1869           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1870               Twine(Coverage) + "%) were applied",
1871           DS_Warning));
1872     }
1873   }
1874 
1875   if (SampleProfileSampleCoverage) {
1876     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1877     uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1878     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1879     if (Coverage < SampleProfileSampleCoverage) {
1880       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1881           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1882           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1883               Twine(Coverage) + "%) were applied",
1884           DS_Warning));
1885     }
1886   }
1887   return Changed;
1888 }
1889 
1890 char SampleProfileLoaderLegacyPass::ID = 0;
1891 
1892 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1893                       "Sample Profile loader", false, false)
1894 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1895 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1896 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1897 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1898 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1899                     "Sample Profile loader", false, false)
1900 
1901 std::vector<Function *>
1902 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1903   std::vector<Function *> FunctionOrderList;
1904   FunctionOrderList.reserve(M.size());
1905 
1906   if (!ProfileTopDownLoad || CG == nullptr) {
1907     if (ProfileMergeInlinee) {
1908       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1909       // because the profile for a function may be used for the profile
1910       // annotation of its outline copy before the profile merging of its
1911       // non-inlined inline instances, and that is not the way how
1912       // ProfileMergeInlinee is supposed to work.
1913       ProfileMergeInlinee = false;
1914     }
1915 
1916     for (Function &F : M)
1917       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1918         FunctionOrderList.push_back(&F);
1919     return FunctionOrderList;
1920   }
1921 
1922   assert(&CG->getModule() == &M);
1923   scc_iterator<CallGraph *> CGI = scc_begin(CG);
1924   while (!CGI.isAtEnd()) {
1925     for (CallGraphNode *node : *CGI) {
1926       auto F = node->getFunction();
1927       if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1928         FunctionOrderList.push_back(F);
1929     }
1930     ++CGI;
1931   }
1932 
1933   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1934   return FunctionOrderList;
1935 }
1936 
1937 bool SampleProfileLoader::doInitialization(Module &M,
1938                                            FunctionAnalysisManager *FAM) {
1939   auto &Ctx = M.getContext();
1940 
1941   auto ReaderOrErr =
1942       SampleProfileReader::create(Filename, Ctx, RemappingFilename);
1943   if (std::error_code EC = ReaderOrErr.getError()) {
1944     std::string Msg = "Could not open profile: " + EC.message();
1945     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1946     return false;
1947   }
1948   Reader = std::move(ReaderOrErr.get());
1949   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1950   Reader->collectFuncsFrom(M);
1951   if (std::error_code EC = Reader->read()) {
1952     std::string Msg = "profile reading failed: " + EC.message();
1953     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1954     return false;
1955   }
1956 
1957   PSL = Reader->getProfileSymbolList();
1958 
1959   // While profile-sample-accurate is on, ignore symbol list.
1960   ProfAccForSymsInList =
1961       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1962   if (ProfAccForSymsInList) {
1963     NamesInProfile.clear();
1964     if (auto NameTable = Reader->getNameTable())
1965       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1966   }
1967 
1968   if (FAM && !ProfileInlineReplayFile.empty()) {
1969     ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
1970         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
1971         /*EmitRemarks=*/false);
1972     if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
1973       ExternalInlineAdvisor.reset();
1974   }
1975 
1976   // Apply tweaks if context-sensitive profile is available.
1977   if (Reader->profileIsCS()) {
1978     ProfileIsCS = true;
1979     FunctionSamples::ProfileIsCS = true;
1980 
1981     // Tracker for profiles under different context
1982     ContextTracker =
1983         std::make_unique<SampleContextTracker>(Reader->getProfiles());
1984   }
1985 
1986   // Load pseudo probe descriptors for probe-based function samples.
1987   if (Reader->profileIsProbeBased()) {
1988     ProbeManager = std::make_unique<PseudoProbeManager>(M);
1989     if (!ProbeManager->moduleIsProbed(M)) {
1990       const char *Msg =
1991           "Pseudo-probe-based profile requires SampleProfileProbePass";
1992       Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1993       return false;
1994     }
1995   }
1996 
1997   return true;
1998 }
1999 
2000 ModulePass *llvm::createSampleProfileLoaderPass() {
2001   return new SampleProfileLoaderLegacyPass();
2002 }
2003 
2004 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
2005   return new SampleProfileLoaderLegacyPass(Name);
2006 }
2007 
2008 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2009                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
2010   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
2011 
2012   PSI = _PSI;
2013   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
2014     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
2015                         ProfileSummary::PSK_Sample);
2016     PSI->refresh();
2017   }
2018   // Compute the total number of samples collected in this profile.
2019   for (const auto &I : Reader->getProfiles())
2020     TotalCollectedSamples += I.second.getTotalSamples();
2021 
2022   auto Remapper = Reader->getRemapper();
2023   // Populate the symbol map.
2024   for (const auto &N_F : M.getValueSymbolTable()) {
2025     StringRef OrigName = N_F.getKey();
2026     Function *F = dyn_cast<Function>(N_F.getValue());
2027     if (F == nullptr)
2028       continue;
2029     SymbolMap[OrigName] = F;
2030     auto pos = OrigName.find('.');
2031     if (pos != StringRef::npos) {
2032       StringRef NewName = OrigName.substr(0, pos);
2033       auto r = SymbolMap.insert(std::make_pair(NewName, F));
2034       // Failiing to insert means there is already an entry in SymbolMap,
2035       // thus there are multiple functions that are mapped to the same
2036       // stripped name. In this case of name conflicting, set the value
2037       // to nullptr to avoid confusion.
2038       if (!r.second)
2039         r.first->second = nullptr;
2040       OrigName = NewName;
2041     }
2042     // Insert the remapped names into SymbolMap.
2043     if (Remapper) {
2044       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2045         if (*MapName == OrigName)
2046           continue;
2047         SymbolMap.insert(std::make_pair(*MapName, F));
2048       }
2049     }
2050   }
2051 
2052   bool retval = false;
2053   for (auto F : buildFunctionOrder(M, CG)) {
2054     assert(!F->isDeclaration());
2055     clearFunctionData();
2056     retval |= runOnFunction(*F, AM);
2057   }
2058 
2059   // Account for cold calls not inlined....
2060   if (!ProfileIsCS)
2061     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
2062          notInlinedCallInfo)
2063       updateProfileCallee(pair.first, pair.second.entryCount);
2064 
2065   return retval;
2066 }
2067 
2068 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
2069   ACT = &getAnalysis<AssumptionCacheTracker>();
2070   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
2071   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
2072   ProfileSummaryInfo *PSI =
2073       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2074   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
2075 }
2076 
2077 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2078   DILocation2SampleMap.clear();
2079   // By default the entry count is initialized to -1, which will be treated
2080   // conservatively by getEntryCount as the same as unknown (None). This is
2081   // to avoid newly added code to be treated as cold. If we have samples
2082   // this will be overwritten in emitAnnotations.
2083   uint64_t initialEntryCount = -1;
2084 
2085   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
2086   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
2087     // initialize all the function entry counts to 0. It means all the
2088     // functions without profile will be regarded as cold.
2089     initialEntryCount = 0;
2090     // profile-sample-accurate is a user assertion which has a higher precedence
2091     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2092     ProfAccForSymsInList = false;
2093   }
2094 
2095   // PSL -- profile symbol list include all the symbols in sampled binary.
2096   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2097   // old functions without samples being cold, without having to worry
2098   // about new and hot functions being mistakenly treated as cold.
2099   if (ProfAccForSymsInList) {
2100     // Initialize the entry count to 0 for functions in the list.
2101     if (PSL->contains(F.getName()))
2102       initialEntryCount = 0;
2103 
2104     // Function in the symbol list but without sample will be regarded as
2105     // cold. To minimize the potential negative performance impact it could
2106     // have, we want to be a little conservative here saying if a function
2107     // shows up in the profile, no matter as outline function, inline instance
2108     // or call targets, treat the function as not being cold. This will handle
2109     // the cases such as most callsites of a function are inlined in sampled
2110     // binary but not inlined in current build (because of source code drift,
2111     // imprecise debug information, or the callsites are all cold individually
2112     // but not cold accumulatively...), so the outline function showing up as
2113     // cold in sampled binary will actually not be cold after current build.
2114     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2115     if (NamesInProfile.count(CanonName))
2116       initialEntryCount = -1;
2117   }
2118 
2119   // Initialize entry count when the function has no existing entry
2120   // count value.
2121   if (!F.getEntryCount().hasValue())
2122     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
2123   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
2124   if (AM) {
2125     auto &FAM =
2126         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2127             .getManager();
2128     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2129   } else {
2130     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2131     ORE = OwnedORE.get();
2132   }
2133 
2134   if (ProfileIsCS)
2135     Samples = ContextTracker->getBaseSamplesFor(F);
2136   else
2137     Samples = Reader->getSamplesFor(F);
2138 
2139   if (Samples && !Samples->empty())
2140     return emitAnnotations(F);
2141   return false;
2142 }
2143 
2144 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2145                                                ModuleAnalysisManager &AM) {
2146   FunctionAnalysisManager &FAM =
2147       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2148 
2149   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2150     return FAM.getResult<AssumptionAnalysis>(F);
2151   };
2152   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2153     return FAM.getResult<TargetIRAnalysis>(F);
2154   };
2155   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2156     return FAM.getResult<TargetLibraryAnalysis>(F);
2157   };
2158 
2159   SampleProfileLoader SampleLoader(
2160       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
2161       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2162                                        : ProfileRemappingFileName,
2163       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
2164 
2165   if (!SampleLoader.doInitialization(M, &FAM))
2166     return PreservedAnalyses::all();
2167 
2168   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2169   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2170   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2171     return PreservedAnalyses::all();
2172 
2173   return PreservedAnalyses::none();
2174 }
2175