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