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