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   return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL),
642                                                 DIL->getBaseDiscriminator()),
643                                    CalleeName);
644 }
645 
646 /// Returns a vector of FunctionSamples that are the indirect call targets
647 /// of \p Inst. The vector is sorted by the total number of samples. Stores
648 /// the total call count of the indirect call in \p Sum.
649 std::vector<const FunctionSamples *>
650 SampleProfileLoader::findIndirectCallFunctionSamples(
651     const Instruction &Inst, uint64_t &Sum) const {
652   const DILocation *DIL = Inst.getDebugLoc();
653   std::vector<const FunctionSamples *> R;
654 
655   if (!DIL) {
656     return R;
657   }
658 
659   const FunctionSamples *FS = findFunctionSamples(Inst);
660   if (FS == nullptr)
661     return R;
662 
663   uint32_t LineOffset = FunctionSamples::getOffset(DIL);
664   uint32_t Discriminator = DIL->getBaseDiscriminator();
665 
666   auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
667   Sum = 0;
668   if (T)
669     for (const auto &T_C : T.get())
670       Sum += T_C.second;
671   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation(
672           FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) {
673     if (M->empty())
674       return R;
675     for (const auto &NameFS : *M) {
676       Sum += NameFS.second.getEntrySamples();
677       R.push_back(&NameFS.second);
678     }
679     llvm::sort(R.begin(), R.end(),
680                [](const FunctionSamples *L, const FunctionSamples *R) {
681                  return L->getEntrySamples() > R->getEntrySamples();
682                });
683   }
684   return R;
685 }
686 
687 /// Get the FunctionSamples for an instruction.
688 ///
689 /// The FunctionSamples of an instruction \p Inst is the inlined instance
690 /// in which that instruction is coming from. We traverse the inline stack
691 /// of that instruction, and match it with the tree nodes in the profile.
692 ///
693 /// \param Inst Instruction to query.
694 ///
695 /// \returns the FunctionSamples pointer to the inlined instance.
696 const FunctionSamples *
697 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
698   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
699   const DILocation *DIL = Inst.getDebugLoc();
700   if (!DIL)
701     return Samples;
702 
703   return Samples->findFunctionSamples(DIL);
704 }
705 
706 bool SampleProfileLoader::inlineCallInstruction(Instruction *I) {
707   assert(isa<CallInst>(I) || isa<InvokeInst>(I));
708   CallSite CS(I);
709   Function *CalledFunction = CS.getCalledFunction();
710   assert(CalledFunction);
711   DebugLoc DLoc = I->getDebugLoc();
712   BasicBlock *BB = I->getParent();
713   InlineParams Params = getInlineParams();
714   Params.ComputeFullInlineCost = true;
715   // Checks if there is anything in the reachable portion of the callee at
716   // this callsite that makes this inlining potentially illegal. Need to
717   // set ComputeFullInlineCost, otherwise getInlineCost may return early
718   // when cost exceeds threshold without checking all IRs in the callee.
719   // The acutal cost does not matter because we only checks isNever() to
720   // see if it is legal to inline the callsite.
721   InlineCost Cost = getInlineCost(CS, Params, GetTTI(*CalledFunction), GetAC,
722                                   None, nullptr, nullptr);
723   if (Cost.isNever()) {
724     ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB)
725               << "incompatible inlining");
726     return false;
727   }
728   InlineFunctionInfo IFI(nullptr, &GetAC);
729   if (InlineFunction(CS, IFI)) {
730     // The call to InlineFunction erases I, so we can't pass it here.
731     ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB)
732               << "inlined hot callee '" << ore::NV("Callee", CalledFunction)
733               << "' into '" << ore::NV("Caller", BB->getParent()) << "'");
734     return true;
735   }
736   return false;
737 }
738 
739 /// Iteratively inline hot callsites of a function.
740 ///
741 /// Iteratively traverse all callsites of the function \p F, and find if
742 /// the corresponding inlined instance exists and is hot in profile. If
743 /// it is hot enough, inline the callsites and adds new callsites of the
744 /// callee into the caller. If the call is an indirect call, first promote
745 /// it to direct call. Each indirect call is limited with a single target.
746 ///
747 /// \param F function to perform iterative inlining.
748 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
749 ///     inlined in the profiled binary.
750 ///
751 /// \returns True if there is any inline happened.
752 bool SampleProfileLoader::inlineHotFunctions(
753     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
754   DenseSet<Instruction *> PromotedInsns;
755   bool Changed = false;
756   while (true) {
757     bool LocalChanged = false;
758     SmallVector<Instruction *, 10> CIS;
759     for (auto &BB : F) {
760       bool Hot = false;
761       SmallVector<Instruction *, 10> Candidates;
762       for (auto &I : BB.getInstList()) {
763         const FunctionSamples *FS = nullptr;
764         if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
765             !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) {
766           Candidates.push_back(&I);
767           if (callsiteIsHot(FS, PSI))
768             Hot = true;
769         }
770       }
771       if (Hot) {
772         CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end());
773       }
774     }
775     for (auto I : CIS) {
776       Function *CalledFunction = CallSite(I).getCalledFunction();
777       // Do not inline recursive calls.
778       if (CalledFunction == &F)
779         continue;
780       if (CallSite(I).isIndirectCall()) {
781         if (PromotedInsns.count(I))
782           continue;
783         uint64_t Sum;
784         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
785           if (IsThinLTOPreLink) {
786             FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
787                                      PSI->getOrCompHotCountThreshold());
788             continue;
789           }
790           auto CalleeFunctionName = FS->getName();
791           // If it is a recursive call, we do not inline it as it could bloat
792           // the code exponentially. There is way to better handle this, e.g.
793           // clone the caller first, and inline the cloned caller if it is
794           // recursive. As llvm does not inline recursive calls, we will
795           // simply ignore it instead of handling it explicitly.
796           if (CalleeFunctionName == F.getName())
797             continue;
798 
799           const char *Reason = "Callee function not available";
800           auto R = SymbolMap.find(CalleeFunctionName);
801           if (R != SymbolMap.end() && R->getValue() &&
802               !R->getValue()->isDeclaration() &&
803               R->getValue()->getSubprogram() &&
804               isLegalToPromote(CallSite(I), R->getValue(), &Reason)) {
805             uint64_t C = FS->getEntrySamples();
806             Instruction *DI =
807                 pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE);
808             Sum -= C;
809             PromotedInsns.insert(I);
810             // If profile mismatches, we should not attempt to inline DI.
811             if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
812                 inlineCallInstruction(DI))
813               LocalChanged = true;
814           } else {
815             LLVM_DEBUG(dbgs()
816                        << "\nFailed to promote indirect call to "
817                        << CalleeFunctionName << " because " << Reason << "\n");
818           }
819         }
820       } else if (CalledFunction && CalledFunction->getSubprogram() &&
821                  !CalledFunction->isDeclaration()) {
822         if (inlineCallInstruction(I))
823           LocalChanged = true;
824       } else if (IsThinLTOPreLink) {
825         findCalleeFunctionSamples(*I)->findInlinedFunctions(
826             InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
827       }
828     }
829     if (LocalChanged) {
830       Changed = true;
831     } else {
832       break;
833     }
834   }
835   return Changed;
836 }
837 
838 /// Find equivalence classes for the given block.
839 ///
840 /// This finds all the blocks that are guaranteed to execute the same
841 /// number of times as \p BB1. To do this, it traverses all the
842 /// descendants of \p BB1 in the dominator or post-dominator tree.
843 ///
844 /// A block BB2 will be in the same equivalence class as \p BB1 if
845 /// the following holds:
846 ///
847 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
848 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
849 ///    dominate BB1 in the post-dominator tree.
850 ///
851 /// 2- Both BB2 and \p BB1 must be in the same loop.
852 ///
853 /// For every block BB2 that meets those two requirements, we set BB2's
854 /// equivalence class to \p BB1.
855 ///
856 /// \param BB1  Block to check.
857 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
858 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
859 ///                 with blocks from \p BB1's dominator tree, then
860 ///                 this is the post-dominator tree, and vice versa.
861 template <bool IsPostDom>
862 void SampleProfileLoader::findEquivalencesFor(
863     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
864     DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
865   const BasicBlock *EC = EquivalenceClass[BB1];
866   uint64_t Weight = BlockWeights[EC];
867   for (const auto *BB2 : Descendants) {
868     bool IsDomParent = DomTree->dominates(BB2, BB1);
869     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
870     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
871       EquivalenceClass[BB2] = EC;
872       // If BB2 is visited, then the entire EC should be marked as visited.
873       if (VisitedBlocks.count(BB2)) {
874         VisitedBlocks.insert(EC);
875       }
876 
877       // If BB2 is heavier than BB1, make BB2 have the same weight
878       // as BB1.
879       //
880       // Note that we don't worry about the opposite situation here
881       // (when BB2 is lighter than BB1). We will deal with this
882       // during the propagation phase. Right now, we just want to
883       // make sure that BB1 has the largest weight of all the
884       // members of its equivalence set.
885       Weight = std::max(Weight, BlockWeights[BB2]);
886     }
887   }
888   if (EC == &EC->getParent()->getEntryBlock()) {
889     BlockWeights[EC] = Samples->getHeadSamples() + 1;
890   } else {
891     BlockWeights[EC] = Weight;
892   }
893 }
894 
895 /// Find equivalence classes.
896 ///
897 /// Since samples may be missing from blocks, we can fill in the gaps by setting
898 /// the weights of all the blocks in the same equivalence class to the same
899 /// weight. To compute the concept of equivalence, we use dominance and loop
900 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
901 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
902 ///
903 /// \param F The function to query.
904 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
905   SmallVector<BasicBlock *, 8> DominatedBBs;
906   LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
907   // Find equivalence sets based on dominance and post-dominance information.
908   for (auto &BB : F) {
909     BasicBlock *BB1 = &BB;
910 
911     // Compute BB1's equivalence class once.
912     if (EquivalenceClass.count(BB1)) {
913       LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
914       continue;
915     }
916 
917     // By default, blocks are in their own equivalence class.
918     EquivalenceClass[BB1] = BB1;
919 
920     // Traverse all the blocks dominated by BB1. We are looking for
921     // every basic block BB2 such that:
922     //
923     // 1- BB1 dominates BB2.
924     // 2- BB2 post-dominates BB1.
925     // 3- BB1 and BB2 are in the same loop nest.
926     //
927     // If all those conditions hold, it means that BB2 is executed
928     // as many times as BB1, so they are placed in the same equivalence
929     // class by making BB2's equivalence class be BB1.
930     DominatedBBs.clear();
931     DT->getDescendants(BB1, DominatedBBs);
932     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
933 
934     LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
935   }
936 
937   // Assign weights to equivalence classes.
938   //
939   // All the basic blocks in the same equivalence class will execute
940   // the same number of times. Since we know that the head block in
941   // each equivalence class has the largest weight, assign that weight
942   // to all the blocks in that equivalence class.
943   LLVM_DEBUG(
944       dbgs() << "\nAssign the same weight to all blocks in the same class\n");
945   for (auto &BI : F) {
946     const BasicBlock *BB = &BI;
947     const BasicBlock *EquivBB = EquivalenceClass[BB];
948     if (BB != EquivBB)
949       BlockWeights[BB] = BlockWeights[EquivBB];
950     LLVM_DEBUG(printBlockWeight(dbgs(), BB));
951   }
952 }
953 
954 /// Visit the given edge to decide if it has a valid weight.
955 ///
956 /// If \p E has not been visited before, we copy to \p UnknownEdge
957 /// and increment the count of unknown edges.
958 ///
959 /// \param E  Edge to visit.
960 /// \param NumUnknownEdges  Current number of unknown edges.
961 /// \param UnknownEdge  Set if E has not been visited before.
962 ///
963 /// \returns E's weight, if known. Otherwise, return 0.
964 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
965                                         Edge *UnknownEdge) {
966   if (!VisitedEdges.count(E)) {
967     (*NumUnknownEdges)++;
968     *UnknownEdge = E;
969     return 0;
970   }
971 
972   return EdgeWeights[E];
973 }
974 
975 /// Propagate weights through incoming/outgoing edges.
976 ///
977 /// If the weight of a basic block is known, and there is only one edge
978 /// with an unknown weight, we can calculate the weight of that edge.
979 ///
980 /// Similarly, if all the edges have a known count, we can calculate the
981 /// count of the basic block, if needed.
982 ///
983 /// \param F  Function to process.
984 /// \param UpdateBlockCount  Whether we should update basic block counts that
985 ///                          has already been annotated.
986 ///
987 /// \returns  True if new weights were assigned to edges or blocks.
988 bool SampleProfileLoader::propagateThroughEdges(Function &F,
989                                                 bool UpdateBlockCount) {
990   bool Changed = false;
991   LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
992   for (const auto &BI : F) {
993     const BasicBlock *BB = &BI;
994     const BasicBlock *EC = EquivalenceClass[BB];
995 
996     // Visit all the predecessor and successor edges to determine
997     // which ones have a weight assigned already. Note that it doesn't
998     // matter that we only keep track of a single unknown edge. The
999     // only case we are interested in handling is when only a single
1000     // edge is unknown (see setEdgeOrBlockWeight).
1001     for (unsigned i = 0; i < 2; i++) {
1002       uint64_t TotalWeight = 0;
1003       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1004       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1005 
1006       if (i == 0) {
1007         // First, visit all predecessor edges.
1008         NumTotalEdges = Predecessors[BB].size();
1009         for (auto *Pred : Predecessors[BB]) {
1010           Edge E = std::make_pair(Pred, BB);
1011           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1012           if (E.first == E.second)
1013             SelfReferentialEdge = E;
1014         }
1015         if (NumTotalEdges == 1) {
1016           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1017         }
1018       } else {
1019         // On the second round, visit all successor edges.
1020         NumTotalEdges = Successors[BB].size();
1021         for (auto *Succ : Successors[BB]) {
1022           Edge E = std::make_pair(BB, Succ);
1023           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1024         }
1025         if (NumTotalEdges == 1) {
1026           SingleEdge = std::make_pair(BB, Successors[BB][0]);
1027         }
1028       }
1029 
1030       // After visiting all the edges, there are three cases that we
1031       // can handle immediately:
1032       //
1033       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1034       //   In this case, we simply check that the sum of all the edges
1035       //   is the same as BB's weight. If not, we change BB's weight
1036       //   to match. Additionally, if BB had not been visited before,
1037       //   we mark it visited.
1038       //
1039       // - Only one edge is unknown and BB has already been visited.
1040       //   In this case, we can compute the weight of the edge by
1041       //   subtracting the total block weight from all the known
1042       //   edge weights. If the edges weight more than BB, then the
1043       //   edge of the last remaining edge is set to zero.
1044       //
1045       // - There exists a self-referential edge and the weight of BB is
1046       //   known. In this case, this edge can be based on BB's weight.
1047       //   We add up all the other known edges and set the weight on
1048       //   the self-referential edge as we did in the previous case.
1049       //
1050       // In any other case, we must continue iterating. Eventually,
1051       // all edges will get a weight, or iteration will stop when
1052       // it reaches SampleProfileMaxPropagateIterations.
1053       if (NumUnknownEdges <= 1) {
1054         uint64_t &BBWeight = BlockWeights[EC];
1055         if (NumUnknownEdges == 0) {
1056           if (!VisitedBlocks.count(EC)) {
1057             // If we already know the weight of all edges, the weight of the
1058             // basic block can be computed. It should be no larger than the sum
1059             // of all edge weights.
1060             if (TotalWeight > BBWeight) {
1061               BBWeight = TotalWeight;
1062               Changed = true;
1063               LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
1064                                 << " known. Set weight for block: ";
1065                          printBlockWeight(dbgs(), BB););
1066             }
1067           } else if (NumTotalEdges == 1 &&
1068                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1069             // If there is only one edge for the visited basic block, use the
1070             // block weight to adjust edge weight if edge weight is smaller.
1071             EdgeWeights[SingleEdge] = BlockWeights[EC];
1072             Changed = true;
1073           }
1074         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1075           // If there is a single unknown edge and the block has been
1076           // visited, then we can compute E's weight.
1077           if (BBWeight >= TotalWeight)
1078             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1079           else
1080             EdgeWeights[UnknownEdge] = 0;
1081           const BasicBlock *OtherEC;
1082           if (i == 0)
1083             OtherEC = EquivalenceClass[UnknownEdge.first];
1084           else
1085             OtherEC = EquivalenceClass[UnknownEdge.second];
1086           // Edge weights should never exceed the BB weights it connects.
1087           if (VisitedBlocks.count(OtherEC) &&
1088               EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1089             EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1090           VisitedEdges.insert(UnknownEdge);
1091           Changed = true;
1092           LLVM_DEBUG(dbgs() << "Set weight for edge: ";
1093                      printEdgeWeight(dbgs(), UnknownEdge));
1094         }
1095       } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1096         // If a block Weights 0, all its in/out edges should weight 0.
1097         if (i == 0) {
1098           for (auto *Pred : Predecessors[BB]) {
1099             Edge E = std::make_pair(Pred, BB);
1100             EdgeWeights[E] = 0;
1101             VisitedEdges.insert(E);
1102           }
1103         } else {
1104           for (auto *Succ : Successors[BB]) {
1105             Edge E = std::make_pair(BB, Succ);
1106             EdgeWeights[E] = 0;
1107             VisitedEdges.insert(E);
1108           }
1109         }
1110       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1111         uint64_t &BBWeight = BlockWeights[BB];
1112         // We have a self-referential edge and the weight of BB is known.
1113         if (BBWeight >= TotalWeight)
1114           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1115         else
1116           EdgeWeights[SelfReferentialEdge] = 0;
1117         VisitedEdges.insert(SelfReferentialEdge);
1118         Changed = true;
1119         LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
1120                    printEdgeWeight(dbgs(), SelfReferentialEdge));
1121       }
1122       if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1123         BlockWeights[EC] = TotalWeight;
1124         VisitedBlocks.insert(EC);
1125         Changed = true;
1126       }
1127     }
1128   }
1129 
1130   return Changed;
1131 }
1132 
1133 /// Build in/out edge lists for each basic block in the CFG.
1134 ///
1135 /// We are interested in unique edges. If a block B1 has multiple
1136 /// edges to another block B2, we only add a single B1->B2 edge.
1137 void SampleProfileLoader::buildEdges(Function &F) {
1138   for (auto &BI : F) {
1139     BasicBlock *B1 = &BI;
1140 
1141     // Add predecessors for B1.
1142     SmallPtrSet<BasicBlock *, 16> Visited;
1143     if (!Predecessors[B1].empty())
1144       llvm_unreachable("Found a stale predecessors list in a basic block.");
1145     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1146       BasicBlock *B2 = *PI;
1147       if (Visited.insert(B2).second)
1148         Predecessors[B1].push_back(B2);
1149     }
1150 
1151     // Add successors for B1.
1152     Visited.clear();
1153     if (!Successors[B1].empty())
1154       llvm_unreachable("Found a stale successors list in a basic block.");
1155     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1156       BasicBlock *B2 = *SI;
1157       if (Visited.insert(B2).second)
1158         Successors[B1].push_back(B2);
1159     }
1160   }
1161 }
1162 
1163 /// Returns the sorted CallTargetMap \p M by count in descending order.
1164 static SmallVector<InstrProfValueData, 2> SortCallTargets(
1165     const SampleRecord::CallTargetMap &M) {
1166   SmallVector<InstrProfValueData, 2> R;
1167   for (auto I = M.begin(); I != M.end(); ++I)
1168     R.push_back({Function::getGUID(I->getKey()), I->getValue()});
1169   llvm::sort(R.begin(), R.end(),
1170              [](const InstrProfValueData &L, const InstrProfValueData &R) {
1171                if (L.Count == R.Count)
1172                  return L.Value > R.Value;
1173                else
1174                  return L.Count > R.Count;
1175              });
1176   return R;
1177 }
1178 
1179 /// Propagate weights into edges
1180 ///
1181 /// The following rules are applied to every block BB in the CFG:
1182 ///
1183 /// - If BB has a single predecessor/successor, then the weight
1184 ///   of that edge is the weight of the block.
1185 ///
1186 /// - If all incoming or outgoing edges are known except one, and the
1187 ///   weight of the block is already known, the weight of the unknown
1188 ///   edge will be the weight of the block minus the sum of all the known
1189 ///   edges. If the sum of all the known edges is larger than BB's weight,
1190 ///   we set the unknown edge weight to zero.
1191 ///
1192 /// - If there is a self-referential edge, and the weight of the block is
1193 ///   known, the weight for that edge is set to the weight of the block
1194 ///   minus the weight of the other incoming edges to that block (if
1195 ///   known).
1196 void SampleProfileLoader::propagateWeights(Function &F) {
1197   bool Changed = true;
1198   unsigned I = 0;
1199 
1200   // If BB weight is larger than its corresponding loop's header BB weight,
1201   // use the BB weight to replace the loop header BB weight.
1202   for (auto &BI : F) {
1203     BasicBlock *BB = &BI;
1204     Loop *L = LI->getLoopFor(BB);
1205     if (!L) {
1206       continue;
1207     }
1208     BasicBlock *Header = L->getHeader();
1209     if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1210       BlockWeights[Header] = BlockWeights[BB];
1211     }
1212   }
1213 
1214   // Before propagation starts, build, for each block, a list of
1215   // unique predecessors and successors. This is necessary to handle
1216   // identical edges in multiway branches. Since we visit all blocks and all
1217   // edges of the CFG, it is cleaner to build these lists once at the start
1218   // of the pass.
1219   buildEdges(F);
1220 
1221   // Propagate until we converge or we go past the iteration limit.
1222   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1223     Changed = propagateThroughEdges(F, false);
1224   }
1225 
1226   // The first propagation propagates BB counts from annotated BBs to unknown
1227   // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1228   // to propagate edge weights.
1229   VisitedEdges.clear();
1230   Changed = true;
1231   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1232     Changed = propagateThroughEdges(F, false);
1233   }
1234 
1235   // The 3rd propagation pass allows adjust annotated BB weights that are
1236   // obviously wrong.
1237   Changed = true;
1238   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1239     Changed = propagateThroughEdges(F, true);
1240   }
1241 
1242   // Generate MD_prof metadata for every branch instruction using the
1243   // edge weights computed during propagation.
1244   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1245   LLVMContext &Ctx = F.getContext();
1246   MDBuilder MDB(Ctx);
1247   for (auto &BI : F) {
1248     BasicBlock *BB = &BI;
1249 
1250     if (BlockWeights[BB]) {
1251       for (auto &I : BB->getInstList()) {
1252         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1253           continue;
1254         CallSite CS(&I);
1255         if (!CS.getCalledFunction()) {
1256           const DebugLoc &DLoc = I.getDebugLoc();
1257           if (!DLoc)
1258             continue;
1259           const DILocation *DIL = DLoc;
1260           uint32_t LineOffset = FunctionSamples::getOffset(DIL);
1261           uint32_t Discriminator = DIL->getBaseDiscriminator();
1262 
1263           const FunctionSamples *FS = findFunctionSamples(I);
1264           if (!FS)
1265             continue;
1266           auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
1267           if (!T || T.get().empty())
1268             continue;
1269           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1270               SortCallTargets(T.get());
1271           uint64_t Sum;
1272           findIndirectCallFunctionSamples(I, Sum);
1273           annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1274                             SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1275                             SortedCallTargets.size());
1276         } else if (!dyn_cast<IntrinsicInst>(&I)) {
1277           SmallVector<uint32_t, 1> Weights;
1278           Weights.push_back(BlockWeights[BB]);
1279           I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1280         }
1281       }
1282     }
1283     TerminatorInst *TI = BB->getTerminator();
1284     if (TI->getNumSuccessors() == 1)
1285       continue;
1286     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1287       continue;
1288 
1289     DebugLoc BranchLoc = TI->getDebugLoc();
1290     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1291                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1292                                       : Twine("<UNKNOWN LOCATION>"))
1293                       << ".\n");
1294     SmallVector<uint32_t, 4> Weights;
1295     uint32_t MaxWeight = 0;
1296     Instruction *MaxDestInst;
1297     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1298       BasicBlock *Succ = TI->getSuccessor(I);
1299       Edge E = std::make_pair(BB, Succ);
1300       uint64_t Weight = EdgeWeights[E];
1301       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1302       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1303       // if needed. Sample counts in profiles are 64-bit unsigned values,
1304       // but internally branch weights are expressed as 32-bit values.
1305       if (Weight > std::numeric_limits<uint32_t>::max()) {
1306         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1307         Weight = std::numeric_limits<uint32_t>::max();
1308       }
1309       // Weight is added by one to avoid propagation errors introduced by
1310       // 0 weights.
1311       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1312       if (Weight != 0) {
1313         if (Weight > MaxWeight) {
1314           MaxWeight = Weight;
1315           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1316         }
1317       }
1318     }
1319 
1320     uint64_t TempWeight;
1321     // Only set weights if there is at least one non-zero weight.
1322     // In any other case, let the analyzer set weights.
1323     // Do not set weights if the weights are present. In ThinLTO, the profile
1324     // annotation is done twice. If the first annotation already set the
1325     // weights, the second pass does not need to set it.
1326     if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1327       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1328       TI->setMetadata(LLVMContext::MD_prof,
1329                       MDB.createBranchWeights(Weights));
1330       ORE->emit([&]() {
1331         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1332                << "most popular destination for conditional branches at "
1333                << ore::NV("CondBranchesLoc", BranchLoc);
1334       });
1335     } else {
1336       LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1337     }
1338   }
1339 }
1340 
1341 /// Get the line number for the function header.
1342 ///
1343 /// This looks up function \p F in the current compilation unit and
1344 /// retrieves the line number where the function is defined. This is
1345 /// line 0 for all the samples read from the profile file. Every line
1346 /// number is relative to this line.
1347 ///
1348 /// \param F  Function object to query.
1349 ///
1350 /// \returns the line number where \p F is defined. If it returns 0,
1351 ///          it means that there is no debug information available for \p F.
1352 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1353   if (DISubprogram *S = F.getSubprogram())
1354     return S->getLine();
1355 
1356   // If the start of \p F is missing, emit a diagnostic to inform the user
1357   // about the missed opportunity.
1358   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1359       "No debug information found in function " + F.getName() +
1360           ": Function profile not used",
1361       DS_Warning));
1362   return 0;
1363 }
1364 
1365 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1366   DT.reset(new DominatorTree);
1367   DT->recalculate(F);
1368 
1369   PDT.reset(new PostDominatorTree(F));
1370 
1371   LI.reset(new LoopInfo);
1372   LI->analyze(*DT);
1373 }
1374 
1375 /// Generate branch weight metadata for all branches in \p F.
1376 ///
1377 /// Branch weights are computed out of instruction samples using a
1378 /// propagation heuristic. Propagation proceeds in 3 phases:
1379 ///
1380 /// 1- Assignment of block weights. All the basic blocks in the function
1381 ///    are initial assigned the same weight as their most frequently
1382 ///    executed instruction.
1383 ///
1384 /// 2- Creation of equivalence classes. Since samples may be missing from
1385 ///    blocks, we can fill in the gaps by setting the weights of all the
1386 ///    blocks in the same equivalence class to the same weight. To compute
1387 ///    the concept of equivalence, we use dominance and loop information.
1388 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1389 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1390 ///
1391 /// 3- Propagation of block weights into edges. This uses a simple
1392 ///    propagation heuristic. The following rules are applied to every
1393 ///    block BB in the CFG:
1394 ///
1395 ///    - If BB has a single predecessor/successor, then the weight
1396 ///      of that edge is the weight of the block.
1397 ///
1398 ///    - If all the edges are known except one, and the weight of the
1399 ///      block is already known, the weight of the unknown edge will
1400 ///      be the weight of the block minus the sum of all the known
1401 ///      edges. If the sum of all the known edges is larger than BB's weight,
1402 ///      we set the unknown edge weight to zero.
1403 ///
1404 ///    - If there is a self-referential edge, and the weight of the block is
1405 ///      known, the weight for that edge is set to the weight of the block
1406 ///      minus the weight of the other incoming edges to that block (if
1407 ///      known).
1408 ///
1409 /// Since this propagation is not guaranteed to finalize for every CFG, we
1410 /// only allow it to proceed for a limited number of iterations (controlled
1411 /// by -sample-profile-max-propagate-iterations).
1412 ///
1413 /// FIXME: Try to replace this propagation heuristic with a scheme
1414 /// that is guaranteed to finalize. A work-list approach similar to
1415 /// the standard value propagation algorithm used by SSA-CCP might
1416 /// work here.
1417 ///
1418 /// Once all the branch weights are computed, we emit the MD_prof
1419 /// metadata on BB using the computed values for each of its branches.
1420 ///
1421 /// \param F The function to query.
1422 ///
1423 /// \returns true if \p F was modified. Returns false, otherwise.
1424 bool SampleProfileLoader::emitAnnotations(Function &F) {
1425   bool Changed = false;
1426 
1427   if (getFunctionLoc(F) == 0)
1428     return false;
1429 
1430   LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1431                     << F.getName() << ": " << getFunctionLoc(F) << "\n");
1432 
1433   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1434   Changed |= inlineHotFunctions(F, InlinedGUIDs);
1435 
1436   // Compute basic block weights.
1437   Changed |= computeBlockWeights(F);
1438 
1439   if (Changed) {
1440     // Add an entry count to the function using the samples gathered at the
1441     // function entry.
1442     // Sets the GUIDs that are inlined in the profiled binary. This is used
1443     // for ThinLink to make correct liveness analysis, and also make the IR
1444     // match the profiled binary before annotation.
1445     F.setEntryCount(
1446         ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1447         &InlinedGUIDs);
1448 
1449     // Compute dominance and loop info needed for propagation.
1450     computeDominanceAndLoopInfo(F);
1451 
1452     // Find equivalence classes.
1453     findEquivalenceClasses(F);
1454 
1455     // Propagate weights to all edges.
1456     propagateWeights(F);
1457   }
1458 
1459   // If coverage checking was requested, compute it now.
1460   if (SampleProfileRecordCoverage) {
1461     unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1462     unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1463     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1464     if (Coverage < SampleProfileRecordCoverage) {
1465       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1466           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1467           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1468               Twine(Coverage) + "%) were applied",
1469           DS_Warning));
1470     }
1471   }
1472 
1473   if (SampleProfileSampleCoverage) {
1474     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1475     uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1476     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1477     if (Coverage < SampleProfileSampleCoverage) {
1478       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1479           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1480           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1481               Twine(Coverage) + "%) were applied",
1482           DS_Warning));
1483     }
1484   }
1485   return Changed;
1486 }
1487 
1488 char SampleProfileLoaderLegacyPass::ID = 0;
1489 
1490 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1491                       "Sample Profile loader", false, false)
1492 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1493 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1494 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1495 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1496                     "Sample Profile loader", false, false)
1497 
1498 bool SampleProfileLoader::doInitialization(Module &M) {
1499   auto &Ctx = M.getContext();
1500   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1501   if (std::error_code EC = ReaderOrErr.getError()) {
1502     std::string Msg = "Could not open profile: " + EC.message();
1503     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1504     return false;
1505   }
1506   Reader = std::move(ReaderOrErr.get());
1507   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1508   return true;
1509 }
1510 
1511 ModulePass *llvm::createSampleProfileLoaderPass() {
1512   return new SampleProfileLoaderLegacyPass(SampleProfileFile);
1513 }
1514 
1515 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1516   return new SampleProfileLoaderLegacyPass(Name);
1517 }
1518 
1519 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1520                                       ProfileSummaryInfo *_PSI) {
1521   if (!ProfileIsValid)
1522     return false;
1523 
1524   PSI = _PSI;
1525   if (M.getProfileSummary() == nullptr)
1526     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
1527 
1528   // Compute the total number of samples collected in this profile.
1529   for (const auto &I : Reader->getProfiles())
1530     TotalCollectedSamples += I.second.getTotalSamples();
1531 
1532   // Populate the symbol map.
1533   for (const auto &N_F : M.getValueSymbolTable()) {
1534     StringRef OrigName = N_F.getKey();
1535     Function *F = dyn_cast<Function>(N_F.getValue());
1536     if (F == nullptr)
1537       continue;
1538     SymbolMap[OrigName] = F;
1539     auto pos = OrigName.find('.');
1540     if (pos != StringRef::npos) {
1541       StringRef NewName = OrigName.substr(0, pos);
1542       auto r = SymbolMap.insert(std::make_pair(NewName, F));
1543       // Failiing to insert means there is already an entry in SymbolMap,
1544       // thus there are multiple functions that are mapped to the same
1545       // stripped name. In this case of name conflicting, set the value
1546       // to nullptr to avoid confusion.
1547       if (!r.second)
1548         r.first->second = nullptr;
1549     }
1550   }
1551 
1552   bool retval = false;
1553   for (auto &F : M)
1554     if (!F.isDeclaration()) {
1555       clearFunctionData();
1556       retval |= runOnFunction(F, AM);
1557     }
1558   return retval;
1559 }
1560 
1561 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1562   ACT = &getAnalysis<AssumptionCacheTracker>();
1563   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1564   ProfileSummaryInfo *PSI =
1565       getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1566   return SampleLoader.runOnModule(M, nullptr, PSI);
1567 }
1568 
1569 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1570   // Initialize the entry count to -1, which will be treated conservatively
1571   // by getEntryCount as the same as unknown (None). If we have samples this
1572   // will be overwritten in emitAnnotations.
1573   F.setEntryCount(ProfileCount(-1, Function::PCT_Real));
1574   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1575   if (AM) {
1576     auto &FAM =
1577         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1578             .getManager();
1579     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1580   } else {
1581     OwnedORE = make_unique<OptimizationRemarkEmitter>(&F);
1582     ORE = OwnedORE.get();
1583   }
1584   Samples = Reader->getSamplesFor(F);
1585   if (Samples && !Samples->empty())
1586     return emitAnnotations(F);
1587   return false;
1588 }
1589 
1590 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1591                                                ModuleAnalysisManager &AM) {
1592   FunctionAnalysisManager &FAM =
1593       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1594 
1595   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1596     return FAM.getResult<AssumptionAnalysis>(F);
1597   };
1598   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1599     return FAM.getResult<TargetIRAnalysis>(F);
1600   };
1601 
1602   SampleProfileLoader SampleLoader(
1603       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1604       IsThinLTOPreLink, GetAssumptionCache, GetTTI);
1605 
1606   SampleLoader.doInitialization(M);
1607 
1608   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1609   if (!SampleLoader.runOnModule(M, &AM, PSI))
1610     return PreservedAnalyses::all();
1611 
1612   return PreservedAnalyses::none();
1613 }
1614