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