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