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/SampleProfile.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Analysis/AssumptionCache.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/PostDominators.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/DiagnosticInfo.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InstIterator.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/Pass.h"
46 #include "llvm/ProfileData/SampleProfReader.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorOr.h"
50 #include "llvm/Support/Format.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include <cctype>
55 
56 using namespace llvm;
57 using namespace sampleprof;
58 
59 #define DEBUG_TYPE "sample-profile"
60 
61 // Command line option to specify the file to read samples from. This is
62 // mainly used for debugging.
63 static cl::opt<std::string> SampleProfileFile(
64     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
65     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
66 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
67     "sample-profile-max-propagate-iterations", cl::init(100),
68     cl::desc("Maximum number of iterations to go through when propagating "
69              "sample block/edge weights through the CFG."));
70 static cl::opt<unsigned> SampleProfileRecordCoverage(
71     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
72     cl::desc("Emit a warning if less than N% of records in the input profile "
73              "are matched to the IR."));
74 static cl::opt<unsigned> SampleProfileSampleCoverage(
75     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
76     cl::desc("Emit a warning if less than N% of samples in the input profile "
77              "are matched to the IR."));
78 static cl::opt<double> SampleProfileHotThreshold(
79     "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
80     cl::desc("Inlined functions that account for more than N% of all samples "
81              "collected in the parent function, will be inlined again."));
82 static cl::opt<double> SampleProfileGlobalHotThreshold(
83     "sample-profile-global-hot-threshold", cl::init(30), cl::value_desc("N"),
84     cl::desc("Top-level functions that account for more than N% of all samples "
85              "collected in the profile, will be marked as hot for the inliner "
86              "to consider."));
87 static cl::opt<double> SampleProfileGlobalColdThreshold(
88     "sample-profile-global-cold-threshold", cl::init(0.5), cl::value_desc("N"),
89     cl::desc("Top-level functions that account for less than N% of all samples "
90              "collected in the profile, will be marked as cold for the inliner "
91              "to consider."));
92 
93 namespace {
94 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
95 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
96 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
97 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
98 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
99     BlockEdgeMap;
100 
101 /// \brief Sample profile pass.
102 ///
103 /// This pass reads profile data from the file specified by
104 /// -sample-profile-file and annotates every affected function with the
105 /// profile information found in that file.
106 class SampleProfileLoader {
107 public:
108   SampleProfileLoader(StringRef Name = SampleProfileFile)
109       : DT(nullptr), PDT(nullptr), LI(nullptr), ACT(nullptr), Reader(),
110         Samples(nullptr), Filename(Name), ProfileIsValid(false),
111         TotalCollectedSamples(0) {}
112 
113   bool doInitialization(Module &M);
114   bool runOnModule(Module &M);
115   void setACT(AssumptionCacheTracker *A) { ACT = A; }
116 
117   void dump() { Reader->dump(); }
118 
119 protected:
120   bool runOnFunction(Function &F);
121   unsigned getFunctionLoc(Function &F);
122   bool emitAnnotations(Function &F);
123   ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
124   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
125   const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
126   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
127   bool inlineHotFunctions(Function &F);
128   bool emitInlineHints(Function &F);
129   void printEdgeWeight(raw_ostream &OS, Edge E);
130   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
131   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
132   bool computeBlockWeights(Function &F);
133   void findEquivalenceClasses(Function &F);
134   void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
135                            DominatorTreeBase<BasicBlock> *DomTree);
136   void propagateWeights(Function &F);
137   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
138   void buildEdges(Function &F);
139   bool propagateThroughEdges(Function &F);
140   void computeDominanceAndLoopInfo(Function &F);
141   unsigned getOffset(unsigned L, unsigned H) const;
142   void clearFunctionData();
143 
144   /// \brief Map basic blocks to their computed weights.
145   ///
146   /// The weight of a basic block is defined to be the maximum
147   /// of all the instruction weights in that block.
148   BlockWeightMap BlockWeights;
149 
150   /// \brief Map edges to their computed weights.
151   ///
152   /// Edge weights are computed by propagating basic block weights in
153   /// SampleProfile::propagateWeights.
154   EdgeWeightMap EdgeWeights;
155 
156   /// \brief Set of visited blocks during propagation.
157   SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
158 
159   /// \brief Set of visited edges during propagation.
160   SmallSet<Edge, 32> VisitedEdges;
161 
162   /// \brief Equivalence classes for block weights.
163   ///
164   /// Two blocks BB1 and BB2 are in the same equivalence class if they
165   /// dominate and post-dominate each other, and they are in the same loop
166   /// nest. When this happens, the two blocks are guaranteed to execute
167   /// the same number of times.
168   EquivalenceClassMap EquivalenceClass;
169 
170   /// \brief Dominance, post-dominance and loop information.
171   std::unique_ptr<DominatorTree> DT;
172   std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
173   std::unique_ptr<LoopInfo> LI;
174 
175   AssumptionCacheTracker *ACT;
176 
177   /// \brief Predecessors for each basic block in the CFG.
178   BlockEdgeMap Predecessors;
179 
180   /// \brief Successors for each basic block in the CFG.
181   BlockEdgeMap Successors;
182 
183   /// \brief Profile reader object.
184   std::unique_ptr<SampleProfileReader> Reader;
185 
186   /// \brief Samples collected for the body of this function.
187   FunctionSamples *Samples;
188 
189   /// \brief Name of the profile file to load.
190   StringRef Filename;
191 
192   /// \brief Flag indicating whether the profile input loaded successfully.
193   bool ProfileIsValid;
194 
195   /// \brief Total number of samples collected in this profile.
196   ///
197   /// This is the sum of all the samples collected in all the functions executed
198   /// at runtime.
199   uint64_t TotalCollectedSamples;
200 };
201 
202 class SampleProfileLoaderLegacyPass : public ModulePass {
203 public:
204   // Class identification, replacement for typeinfo
205   static char ID;
206 
207   SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
208       : ModulePass(ID), SampleLoader(Name) {
209     initializeSampleProfileLoaderLegacyPassPass(
210         *PassRegistry::getPassRegistry());
211   }
212 
213   void dump() { SampleLoader.dump(); }
214 
215   bool doInitialization(Module &M) override {
216     return SampleLoader.doInitialization(M);
217   }
218   const char *getPassName() const override { return "Sample profile pass"; }
219   bool runOnModule(Module &M) override;
220 
221   void getAnalysisUsage(AnalysisUsage &AU) const override {
222     AU.addRequired<AssumptionCacheTracker>();
223   }
224 private:
225   SampleProfileLoader SampleLoader;
226 };
227 
228 class SampleCoverageTracker {
229 public:
230   SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
231 
232   bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
233                        uint32_t Discriminator, uint64_t Samples);
234   unsigned computeCoverage(unsigned Used, unsigned Total) const;
235   unsigned countUsedRecords(const FunctionSamples *FS) const;
236   unsigned countBodyRecords(const FunctionSamples *FS) const;
237   uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
238   uint64_t countBodySamples(const FunctionSamples *FS) const;
239   void clear() {
240     SampleCoverage.clear();
241     TotalUsedSamples = 0;
242   }
243 
244 private:
245   typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
246   typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
247       FunctionSamplesCoverageMap;
248 
249   /// Coverage map for sampling records.
250   ///
251   /// This map keeps a record of sampling records that have been matched to
252   /// an IR instruction. This is used to detect some form of staleness in
253   /// profiles (see flag -sample-profile-check-coverage).
254   ///
255   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
256   /// another map that counts how many times the sample record at the
257   /// given location has been used.
258   FunctionSamplesCoverageMap SampleCoverage;
259 
260   /// Number of samples used from the profile.
261   ///
262   /// When a sampling record is used for the first time, the samples from
263   /// that record are added to this accumulator.  Coverage is later computed
264   /// based on the total number of samples available in this function and
265   /// its callsites.
266   ///
267   /// Note that this accumulator tracks samples used from a single function
268   /// and all the inlined callsites. Strictly, we should have a map of counters
269   /// keyed by FunctionSamples pointers, but these stats are cleared after
270   /// every function, so we just need to keep a single counter.
271   uint64_t TotalUsedSamples;
272 };
273 
274 SampleCoverageTracker CoverageTracker;
275 
276 /// Return true if the given callsite is hot wrt to its caller.
277 ///
278 /// Functions that were inlined in the original binary will be represented
279 /// in the inline stack in the sample profile. If the profile shows that
280 /// the original inline decision was "good" (i.e., the callsite is executed
281 /// frequently), then we will recreate the inline decision and apply the
282 /// profile from the inlined callsite.
283 ///
284 /// To decide whether an inlined callsite is hot, we compute the fraction
285 /// of samples used by the callsite with respect to the total number of samples
286 /// collected in the caller.
287 ///
288 /// If that fraction is larger than the default given by
289 /// SampleProfileHotThreshold, the callsite will be inlined again.
290 bool callsiteIsHot(const FunctionSamples *CallerFS,
291                    const FunctionSamples *CallsiteFS) {
292   if (!CallsiteFS)
293     return false; // The callsite was not inlined in the original binary.
294 
295   uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
296   if (ParentTotalSamples == 0)
297     return false; // Avoid division by zero.
298 
299   uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
300   if (CallsiteTotalSamples == 0)
301     return false; // Callsite is trivially cold.
302 
303   double PercentSamples =
304       (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
305   return PercentSamples >= SampleProfileHotThreshold;
306 }
307 }
308 
309 /// Mark as used the sample record for the given function samples at
310 /// (LineOffset, Discriminator).
311 ///
312 /// \returns true if this is the first time we mark the given record.
313 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
314                                             uint32_t LineOffset,
315                                             uint32_t Discriminator,
316                                             uint64_t Samples) {
317   LineLocation Loc(LineOffset, Discriminator);
318   unsigned &Count = SampleCoverage[FS][Loc];
319   bool FirstTime = (++Count == 1);
320   if (FirstTime)
321     TotalUsedSamples += Samples;
322   return FirstTime;
323 }
324 
325 /// Return the number of sample records that were applied from this profile.
326 ///
327 /// This count does not include records from cold inlined callsites.
328 unsigned
329 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
330   auto I = SampleCoverage.find(FS);
331 
332   // The size of the coverage map for FS represents the number of records
333   // that were marked used at least once.
334   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
335 
336   // If there are inlined callsites in this function, count the samples found
337   // in the respective bodies. However, do not bother counting callees with 0
338   // total samples, these are callees that were never invoked at runtime.
339   for (const auto &I : FS->getCallsiteSamples()) {
340     const FunctionSamples *CalleeSamples = &I.second;
341     if (callsiteIsHot(FS, CalleeSamples))
342       Count += countUsedRecords(CalleeSamples);
343   }
344 
345   return Count;
346 }
347 
348 /// Return the number of sample records in the body of this profile.
349 ///
350 /// This count does not include records from cold inlined callsites.
351 unsigned
352 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
353   unsigned Count = FS->getBodySamples().size();
354 
355   // Only count records in hot callsites.
356   for (const auto &I : FS->getCallsiteSamples()) {
357     const FunctionSamples *CalleeSamples = &I.second;
358     if (callsiteIsHot(FS, CalleeSamples))
359       Count += countBodyRecords(CalleeSamples);
360   }
361 
362   return Count;
363 }
364 
365 /// Return the number of samples collected in the body of this profile.
366 ///
367 /// This count does not include samples from cold inlined callsites.
368 uint64_t
369 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
370   uint64_t Total = 0;
371   for (const auto &I : FS->getBodySamples())
372     Total += I.second.getSamples();
373 
374   // Only count samples in hot callsites.
375   for (const auto &I : FS->getCallsiteSamples()) {
376     const FunctionSamples *CalleeSamples = &I.second;
377     if (callsiteIsHot(FS, CalleeSamples))
378       Total += countBodySamples(CalleeSamples);
379   }
380 
381   return Total;
382 }
383 
384 /// Return the fraction of sample records used in this profile.
385 ///
386 /// The returned value is an unsigned integer in the range 0-100 indicating
387 /// the percentage of sample records that were used while applying this
388 /// profile to the associated function.
389 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
390                                                 unsigned Total) const {
391   assert(Used <= Total &&
392          "number of used records cannot exceed the total number of records");
393   return Total > 0 ? Used * 100 / Total : 100;
394 }
395 
396 /// Clear all the per-function data used to load samples and propagate weights.
397 void SampleProfileLoader::clearFunctionData() {
398   BlockWeights.clear();
399   EdgeWeights.clear();
400   VisitedBlocks.clear();
401   VisitedEdges.clear();
402   EquivalenceClass.clear();
403   DT = nullptr;
404   PDT = nullptr;
405   LI = nullptr;
406   Predecessors.clear();
407   Successors.clear();
408   CoverageTracker.clear();
409 }
410 
411 /// \brief Returns the offset of lineno \p L to head_lineno \p H
412 ///
413 /// \param L  Lineno
414 /// \param H  Header lineno of the function
415 ///
416 /// \returns offset to the header lineno. 16 bits are used to represent offset.
417 /// We assume that a single function will not exceed 65535 LOC.
418 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
419   return (L - H) & 0xffff;
420 }
421 
422 /// \brief Print the weight of edge \p E on stream \p OS.
423 ///
424 /// \param OS  Stream to emit the output to.
425 /// \param E  Edge to print.
426 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
427   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
428      << "]: " << EdgeWeights[E] << "\n";
429 }
430 
431 /// \brief Print the equivalence class of block \p BB on stream \p OS.
432 ///
433 /// \param OS  Stream to emit the output to.
434 /// \param BB  Block to print.
435 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
436                                                 const BasicBlock *BB) {
437   const BasicBlock *Equiv = EquivalenceClass[BB];
438   OS << "equivalence[" << BB->getName()
439      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
440 }
441 
442 /// \brief Print the weight of block \p BB on stream \p OS.
443 ///
444 /// \param OS  Stream to emit the output to.
445 /// \param BB  Block to print.
446 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
447                                            const BasicBlock *BB) const {
448   const auto &I = BlockWeights.find(BB);
449   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
450   OS << "weight[" << BB->getName() << "]: " << W << "\n";
451 }
452 
453 /// \brief Get the weight for an instruction.
454 ///
455 /// The "weight" of an instruction \p Inst is the number of samples
456 /// collected on that instruction at runtime. To retrieve it, we
457 /// need to compute the line number of \p Inst relative to the start of its
458 /// function. We use HeaderLineno to compute the offset. We then
459 /// look up the samples collected for \p Inst using BodySamples.
460 ///
461 /// \param Inst Instruction to query.
462 ///
463 /// \returns the weight of \p Inst.
464 ErrorOr<uint64_t>
465 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
466   const DebugLoc &DLoc = Inst.getDebugLoc();
467   if (!DLoc)
468     return std::error_code();
469 
470   const FunctionSamples *FS = findFunctionSamples(Inst);
471   if (!FS)
472     return std::error_code();
473 
474   // Ignore all dbg_value intrinsics.
475   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
476   if (II && II->getIntrinsicID() == Intrinsic::dbg_value)
477     return std::error_code();
478 
479   const DILocation *DIL = DLoc;
480   unsigned Lineno = DLoc.getLine();
481   unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
482 
483   uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
484   uint32_t Discriminator = DIL->getDiscriminator();
485   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
486   if (R) {
487     bool FirstMark =
488         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
489     if (FirstMark) {
490       const Function *F = Inst.getParent()->getParent();
491       LLVMContext &Ctx = F->getContext();
492       emitOptimizationRemark(
493           Ctx, DEBUG_TYPE, *F, DLoc,
494           Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
495               Twine(LineOffset) +
496               ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
497     }
498     DEBUG(dbgs() << "    " << Lineno << "." << DIL->getDiscriminator() << ":"
499                  << Inst << " (line offset: " << Lineno - HeaderLineno << "."
500                  << DIL->getDiscriminator() << " - weight: " << R.get()
501                  << ")\n");
502   } else {
503     // If a call instruction is inlined in profile, but not inlined here,
504     // it means that the inlined callsite has no sample, thus the call
505     // instruction should have 0 count.
506     const CallInst *CI = dyn_cast<CallInst>(&Inst);
507     if (CI && findCalleeFunctionSamples(*CI))
508       R = 0;
509   }
510   return R;
511 }
512 
513 /// \brief Compute the weight of a basic block.
514 ///
515 /// The weight of basic block \p BB is the maximum weight of all the
516 /// instructions in BB.
517 ///
518 /// \param BB The basic block to query.
519 ///
520 /// \returns the weight for \p BB.
521 ErrorOr<uint64_t>
522 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
523   DenseMap<uint64_t, uint64_t> CM;
524   for (auto &I : BB->getInstList()) {
525     const ErrorOr<uint64_t> &R = getInstWeight(I);
526     if (R) CM[R.get()]++;
527   }
528   if (CM.size() == 0) return std::error_code();
529   uint64_t W = 0, C = 0;
530   for (const auto &C_W : CM) {
531     if (C_W.second == W) {
532       C = std::max(C, C_W.first);
533     } else if (C_W.second > W) {
534       C = C_W.first;
535       W = C_W.second;
536     }
537   }
538   return C;
539 }
540 
541 /// \brief Compute and store the weights of every basic block.
542 ///
543 /// This populates the BlockWeights map by computing
544 /// the weights of every basic block in the CFG.
545 ///
546 /// \param F The function to query.
547 bool SampleProfileLoader::computeBlockWeights(Function &F) {
548   bool Changed = false;
549   DEBUG(dbgs() << "Block weights\n");
550   for (const auto &BB : F) {
551     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
552     if (Weight) {
553       BlockWeights[&BB] = Weight.get();
554       VisitedBlocks.insert(&BB);
555       Changed = true;
556     }
557     DEBUG(printBlockWeight(dbgs(), &BB));
558   }
559 
560   return Changed;
561 }
562 
563 /// \brief Get the FunctionSamples for a call instruction.
564 ///
565 /// The FunctionSamples of a call instruction \p Inst is the inlined
566 /// instance in which that call instruction is calling to. It contains
567 /// all samples that resides in the inlined instance. We first find the
568 /// inlined instance in which the call instruction is from, then we
569 /// traverse its children to find the callsite with the matching
570 /// location and callee function name.
571 ///
572 /// \param Inst Call instruction to query.
573 ///
574 /// \returns The FunctionSamples pointer to the inlined instance.
575 const FunctionSamples *
576 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
577   const DILocation *DIL = Inst.getDebugLoc();
578   if (!DIL) {
579     return nullptr;
580   }
581   DISubprogram *SP = DIL->getScope()->getSubprogram();
582   if (!SP)
583     return nullptr;
584 
585   const FunctionSamples *FS = findFunctionSamples(Inst);
586   if (FS == nullptr)
587     return nullptr;
588 
589   return FS->findFunctionSamplesAt(LineLocation(
590       getOffset(DIL->getLine(), SP->getLine()), DIL->getDiscriminator()));
591 }
592 
593 /// \brief Get the FunctionSamples for an instruction.
594 ///
595 /// The FunctionSamples of an instruction \p Inst is the inlined instance
596 /// in which that instruction is coming from. We traverse the inline stack
597 /// of that instruction, and match it with the tree nodes in the profile.
598 ///
599 /// \param Inst Instruction to query.
600 ///
601 /// \returns the FunctionSamples pointer to the inlined instance.
602 const FunctionSamples *
603 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
604   SmallVector<LineLocation, 10> S;
605   const DILocation *DIL = Inst.getDebugLoc();
606   if (!DIL) {
607     return Samples;
608   }
609   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
610     DISubprogram *SP = DIL->getScope()->getSubprogram();
611     if (!SP)
612       return nullptr;
613     S.push_back(LineLocation(getOffset(DIL->getLine(), SP->getLine()),
614                              DIL->getDiscriminator()));
615   }
616   if (S.size() == 0)
617     return Samples;
618   const FunctionSamples *FS = Samples;
619   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
620     FS = FS->findFunctionSamplesAt(S[i]);
621   }
622   return FS;
623 }
624 
625 /// \brief Emit an inline hint if \p F is globally hot or cold.
626 ///
627 /// If \p F consumes a significant fraction of samples (indicated by
628 /// SampleProfileGlobalHotThreshold), apply the InlineHint attribute for the
629 /// inliner to consider the function hot.
630 ///
631 /// If \p F consumes a small fraction of samples (indicated by
632 /// SampleProfileGlobalColdThreshold), apply the Cold attribute for the inliner
633 /// to consider the function cold.
634 ///
635 /// FIXME - This setting of inline hints is sub-optimal. Instead of marking a
636 /// function globally hot or cold, we should be annotating individual callsites.
637 /// This is not currently possible, but work on the inliner will eventually
638 /// provide this ability. See http://reviews.llvm.org/D15003 for details and
639 /// discussion.
640 ///
641 /// \returns True if either attribute was applied to \p F.
642 bool SampleProfileLoader::emitInlineHints(Function &F) {
643   if (TotalCollectedSamples == 0)
644     return false;
645 
646   uint64_t FunctionSamples = Samples->getTotalSamples();
647   double SamplesPercent =
648       (double)FunctionSamples / (double)TotalCollectedSamples * 100.0;
649 
650   // If the function collected more samples than the hot threshold, mark
651   // it globally hot.
652   if (SamplesPercent >= SampleProfileGlobalHotThreshold) {
653     F.addFnAttr(llvm::Attribute::InlineHint);
654     std::string Msg;
655     raw_string_ostream S(Msg);
656     S << "Applied inline hint to globally hot function '" << F.getName()
657       << "' with " << format("%.2f", SamplesPercent)
658       << "% of samples (threshold: "
659       << format("%.2f", SampleProfileGlobalHotThreshold.getValue()) << "%)";
660     S.flush();
661     emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
662     return true;
663   }
664 
665   // If the function collected fewer samples than the cold threshold, mark
666   // it globally cold.
667   if (SamplesPercent <= SampleProfileGlobalColdThreshold) {
668     F.addFnAttr(llvm::Attribute::Cold);
669     std::string Msg;
670     raw_string_ostream S(Msg);
671     S << "Applied cold hint to globally cold function '" << F.getName()
672       << "' with " << format("%.2f", SamplesPercent)
673       << "% of samples (threshold: "
674       << format("%.2f", SampleProfileGlobalColdThreshold.getValue()) << "%)";
675     S.flush();
676     emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
677     return true;
678   }
679 
680   return false;
681 }
682 
683 /// \brief Iteratively inline hot callsites of a function.
684 ///
685 /// Iteratively traverse all callsites of the function \p F, and find if
686 /// the corresponding inlined instance exists and is hot in profile. If
687 /// it is hot enough, inline the callsites and adds new callsites of the
688 /// callee into the caller.
689 ///
690 /// TODO: investigate the possibility of not invoking InlineFunction directly.
691 ///
692 /// \param F function to perform iterative inlining.
693 ///
694 /// \returns True if there is any inline happened.
695 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
696   bool Changed = false;
697   LLVMContext &Ctx = F.getContext();
698   while (true) {
699     bool LocalChanged = false;
700     SmallVector<CallInst *, 10> CIS;
701     for (auto &BB : F) {
702       for (auto &I : BB.getInstList()) {
703         CallInst *CI = dyn_cast<CallInst>(&I);
704         if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
705           CIS.push_back(CI);
706       }
707     }
708     for (auto CI : CIS) {
709       InlineFunctionInfo IFI(nullptr, ACT);
710       Function *CalledFunction = CI->getCalledFunction();
711       DebugLoc DLoc = CI->getDebugLoc();
712       uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
713       if (InlineFunction(CI, IFI)) {
714         LocalChanged = true;
715         emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
716                                Twine("inlined hot callee '") +
717                                    CalledFunction->getName() + "' with " +
718                                    Twine(NumSamples) + " samples into '" +
719                                    F.getName() + "'");
720       }
721     }
722     if (LocalChanged) {
723       Changed = true;
724     } else {
725       break;
726     }
727   }
728   return Changed;
729 }
730 
731 /// \brief Find equivalence classes for the given block.
732 ///
733 /// This finds all the blocks that are guaranteed to execute the same
734 /// number of times as \p BB1. To do this, it traverses all the
735 /// descendants of \p BB1 in the dominator or post-dominator tree.
736 ///
737 /// A block BB2 will be in the same equivalence class as \p BB1 if
738 /// the following holds:
739 ///
740 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
741 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
742 ///    dominate BB1 in the post-dominator tree.
743 ///
744 /// 2- Both BB2 and \p BB1 must be in the same loop.
745 ///
746 /// For every block BB2 that meets those two requirements, we set BB2's
747 /// equivalence class to \p BB1.
748 ///
749 /// \param BB1  Block to check.
750 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
751 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
752 ///                 with blocks from \p BB1's dominator tree, then
753 ///                 this is the post-dominator tree, and vice versa.
754 void SampleProfileLoader::findEquivalencesFor(
755     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
756     DominatorTreeBase<BasicBlock> *DomTree) {
757   const BasicBlock *EC = EquivalenceClass[BB1];
758   uint64_t Weight = BlockWeights[EC];
759   for (const auto *BB2 : Descendants) {
760     bool IsDomParent = DomTree->dominates(BB2, BB1);
761     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
762     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
763       EquivalenceClass[BB2] = EC;
764 
765       // If BB2 is heavier than BB1, make BB2 have the same weight
766       // as BB1.
767       //
768       // Note that we don't worry about the opposite situation here
769       // (when BB2 is lighter than BB1). We will deal with this
770       // during the propagation phase. Right now, we just want to
771       // make sure that BB1 has the largest weight of all the
772       // members of its equivalence set.
773       Weight = std::max(Weight, BlockWeights[BB2]);
774     }
775   }
776   BlockWeights[EC] = Weight;
777 }
778 
779 /// \brief Find equivalence classes.
780 ///
781 /// Since samples may be missing from blocks, we can fill in the gaps by setting
782 /// the weights of all the blocks in the same equivalence class to the same
783 /// weight. To compute the concept of equivalence, we use dominance and loop
784 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
785 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
786 ///
787 /// \param F The function to query.
788 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
789   SmallVector<BasicBlock *, 8> DominatedBBs;
790   DEBUG(dbgs() << "\nBlock equivalence classes\n");
791   // Find equivalence sets based on dominance and post-dominance information.
792   for (auto &BB : F) {
793     BasicBlock *BB1 = &BB;
794 
795     // Compute BB1's equivalence class once.
796     if (EquivalenceClass.count(BB1)) {
797       DEBUG(printBlockEquivalence(dbgs(), BB1));
798       continue;
799     }
800 
801     // By default, blocks are in their own equivalence class.
802     EquivalenceClass[BB1] = BB1;
803 
804     // Traverse all the blocks dominated by BB1. We are looking for
805     // every basic block BB2 such that:
806     //
807     // 1- BB1 dominates BB2.
808     // 2- BB2 post-dominates BB1.
809     // 3- BB1 and BB2 are in the same loop nest.
810     //
811     // If all those conditions hold, it means that BB2 is executed
812     // as many times as BB1, so they are placed in the same equivalence
813     // class by making BB2's equivalence class be BB1.
814     DominatedBBs.clear();
815     DT->getDescendants(BB1, DominatedBBs);
816     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
817 
818     DEBUG(printBlockEquivalence(dbgs(), BB1));
819   }
820 
821   // Assign weights to equivalence classes.
822   //
823   // All the basic blocks in the same equivalence class will execute
824   // the same number of times. Since we know that the head block in
825   // each equivalence class has the largest weight, assign that weight
826   // to all the blocks in that equivalence class.
827   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
828   for (auto &BI : F) {
829     const BasicBlock *BB = &BI;
830     const BasicBlock *EquivBB = EquivalenceClass[BB];
831     if (BB != EquivBB)
832       BlockWeights[BB] = BlockWeights[EquivBB];
833     DEBUG(printBlockWeight(dbgs(), BB));
834   }
835 }
836 
837 /// \brief Visit the given edge to decide if it has a valid weight.
838 ///
839 /// If \p E has not been visited before, we copy to \p UnknownEdge
840 /// and increment the count of unknown edges.
841 ///
842 /// \param E  Edge to visit.
843 /// \param NumUnknownEdges  Current number of unknown edges.
844 /// \param UnknownEdge  Set if E has not been visited before.
845 ///
846 /// \returns E's weight, if known. Otherwise, return 0.
847 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
848                                         Edge *UnknownEdge) {
849   if (!VisitedEdges.count(E)) {
850     (*NumUnknownEdges)++;
851     *UnknownEdge = E;
852     return 0;
853   }
854 
855   return EdgeWeights[E];
856 }
857 
858 /// \brief Propagate weights through incoming/outgoing edges.
859 ///
860 /// If the weight of a basic block is known, and there is only one edge
861 /// with an unknown weight, we can calculate the weight of that edge.
862 ///
863 /// Similarly, if all the edges have a known count, we can calculate the
864 /// count of the basic block, if needed.
865 ///
866 /// \param F  Function to process.
867 ///
868 /// \returns  True if new weights were assigned to edges or blocks.
869 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
870   bool Changed = false;
871   DEBUG(dbgs() << "\nPropagation through edges\n");
872   for (const auto &BI : F) {
873     const BasicBlock *BB = &BI;
874     const BasicBlock *EC = EquivalenceClass[BB];
875 
876     // Visit all the predecessor and successor edges to determine
877     // which ones have a weight assigned already. Note that it doesn't
878     // matter that we only keep track of a single unknown edge. The
879     // only case we are interested in handling is when only a single
880     // edge is unknown (see setEdgeOrBlockWeight).
881     for (unsigned i = 0; i < 2; i++) {
882       uint64_t TotalWeight = 0;
883       unsigned NumUnknownEdges = 0;
884       Edge UnknownEdge, SelfReferentialEdge;
885 
886       if (i == 0) {
887         // First, visit all predecessor edges.
888         for (auto *Pred : Predecessors[BB]) {
889           Edge E = std::make_pair(Pred, BB);
890           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
891           if (E.first == E.second)
892             SelfReferentialEdge = E;
893         }
894       } else {
895         // On the second round, visit all successor edges.
896         for (auto *Succ : Successors[BB]) {
897           Edge E = std::make_pair(BB, Succ);
898           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
899         }
900       }
901 
902       // After visiting all the edges, there are three cases that we
903       // can handle immediately:
904       //
905       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
906       //   In this case, we simply check that the sum of all the edges
907       //   is the same as BB's weight. If not, we change BB's weight
908       //   to match. Additionally, if BB had not been visited before,
909       //   we mark it visited.
910       //
911       // - Only one edge is unknown and BB has already been visited.
912       //   In this case, we can compute the weight of the edge by
913       //   subtracting the total block weight from all the known
914       //   edge weights. If the edges weight more than BB, then the
915       //   edge of the last remaining edge is set to zero.
916       //
917       // - There exists a self-referential edge and the weight of BB is
918       //   known. In this case, this edge can be based on BB's weight.
919       //   We add up all the other known edges and set the weight on
920       //   the self-referential edge as we did in the previous case.
921       //
922       // In any other case, we must continue iterating. Eventually,
923       // all edges will get a weight, or iteration will stop when
924       // it reaches SampleProfileMaxPropagateIterations.
925       if (NumUnknownEdges <= 1) {
926         uint64_t &BBWeight = BlockWeights[EC];
927         if (NumUnknownEdges == 0) {
928           // If we already know the weight of all edges, the weight of the
929           // basic block can be computed. It should be no larger than the sum
930           // of all edge weights.
931           if (TotalWeight > BBWeight) {
932             BBWeight = TotalWeight;
933             Changed = true;
934             DEBUG(dbgs() << "All edge weights for " << BB->getName()
935                          << " known. Set weight for block: ";
936                   printBlockWeight(dbgs(), BB););
937           }
938           if (VisitedBlocks.insert(EC).second)
939             Changed = true;
940         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
941           // If there is a single unknown edge and the block has been
942           // visited, then we can compute E's weight.
943           if (BBWeight >= TotalWeight)
944             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
945           else
946             EdgeWeights[UnknownEdge] = 0;
947           VisitedEdges.insert(UnknownEdge);
948           Changed = true;
949           DEBUG(dbgs() << "Set weight for edge: ";
950                 printEdgeWeight(dbgs(), UnknownEdge));
951         }
952       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
953         uint64_t &BBWeight = BlockWeights[BB];
954         // We have a self-referential edge and the weight of BB is known.
955         if (BBWeight >= TotalWeight)
956           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
957         else
958           EdgeWeights[SelfReferentialEdge] = 0;
959         VisitedEdges.insert(SelfReferentialEdge);
960         Changed = true;
961         DEBUG(dbgs() << "Set self-referential edge weight to: ";
962               printEdgeWeight(dbgs(), SelfReferentialEdge));
963       }
964     }
965   }
966 
967   return Changed;
968 }
969 
970 /// \brief Build in/out edge lists for each basic block in the CFG.
971 ///
972 /// We are interested in unique edges. If a block B1 has multiple
973 /// edges to another block B2, we only add a single B1->B2 edge.
974 void SampleProfileLoader::buildEdges(Function &F) {
975   for (auto &BI : F) {
976     BasicBlock *B1 = &BI;
977 
978     // Add predecessors for B1.
979     SmallPtrSet<BasicBlock *, 16> Visited;
980     if (!Predecessors[B1].empty())
981       llvm_unreachable("Found a stale predecessors list in a basic block.");
982     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
983       BasicBlock *B2 = *PI;
984       if (Visited.insert(B2).second)
985         Predecessors[B1].push_back(B2);
986     }
987 
988     // Add successors for B1.
989     Visited.clear();
990     if (!Successors[B1].empty())
991       llvm_unreachable("Found a stale successors list in a basic block.");
992     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
993       BasicBlock *B2 = *SI;
994       if (Visited.insert(B2).second)
995         Successors[B1].push_back(B2);
996     }
997   }
998 }
999 
1000 /// \brief Propagate weights into edges
1001 ///
1002 /// The following rules are applied to every block BB in the CFG:
1003 ///
1004 /// - If BB has a single predecessor/successor, then the weight
1005 ///   of that edge is the weight of the block.
1006 ///
1007 /// - If all incoming or outgoing edges are known except one, and the
1008 ///   weight of the block is already known, the weight of the unknown
1009 ///   edge will be the weight of the block minus the sum of all the known
1010 ///   edges. If the sum of all the known edges is larger than BB's weight,
1011 ///   we set the unknown edge weight to zero.
1012 ///
1013 /// - If there is a self-referential edge, and the weight of the block is
1014 ///   known, the weight for that edge is set to the weight of the block
1015 ///   minus the weight of the other incoming edges to that block (if
1016 ///   known).
1017 void SampleProfileLoader::propagateWeights(Function &F) {
1018   bool Changed = true;
1019   unsigned I = 0;
1020 
1021   // Add an entry count to the function using the samples gathered
1022   // at the function entry.
1023   F.setEntryCount(Samples->getHeadSamples());
1024 
1025   // Before propagation starts, build, for each block, a list of
1026   // unique predecessors and successors. This is necessary to handle
1027   // identical edges in multiway branches. Since we visit all blocks and all
1028   // edges of the CFG, it is cleaner to build these lists once at the start
1029   // of the pass.
1030   buildEdges(F);
1031 
1032   // Propagate until we converge or we go past the iteration limit.
1033   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1034     Changed = propagateThroughEdges(F);
1035   }
1036 
1037   // Generate MD_prof metadata for every branch instruction using the
1038   // edge weights computed during propagation.
1039   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1040   LLVMContext &Ctx = F.getContext();
1041   MDBuilder MDB(Ctx);
1042   for (auto &BI : F) {
1043     BasicBlock *BB = &BI;
1044     TerminatorInst *TI = BB->getTerminator();
1045     if (TI->getNumSuccessors() == 1)
1046       continue;
1047     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1048       continue;
1049 
1050     DEBUG(dbgs() << "\nGetting weights for branch at line "
1051                  << TI->getDebugLoc().getLine() << ".\n");
1052     SmallVector<uint32_t, 4> Weights;
1053     uint32_t MaxWeight = 0;
1054     DebugLoc MaxDestLoc;
1055     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1056       BasicBlock *Succ = TI->getSuccessor(I);
1057       Edge E = std::make_pair(BB, Succ);
1058       uint64_t Weight = EdgeWeights[E];
1059       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1060       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1061       // if needed. Sample counts in profiles are 64-bit unsigned values,
1062       // but internally branch weights are expressed as 32-bit values.
1063       if (Weight > std::numeric_limits<uint32_t>::max()) {
1064         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1065         Weight = std::numeric_limits<uint32_t>::max();
1066       }
1067       Weights.push_back(static_cast<uint32_t>(Weight));
1068       if (Weight != 0) {
1069         if (Weight > MaxWeight) {
1070           MaxWeight = Weight;
1071           MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1072         }
1073       }
1074     }
1075 
1076     // Only set weights if there is at least one non-zero weight.
1077     // In any other case, let the analyzer set weights.
1078     if (MaxWeight > 0) {
1079       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1080       TI->setMetadata(llvm::LLVMContext::MD_prof,
1081                       MDB.createBranchWeights(Weights));
1082       DebugLoc BranchLoc = TI->getDebugLoc();
1083       emitOptimizationRemark(
1084           Ctx, DEBUG_TYPE, F, MaxDestLoc,
1085           Twine("most popular destination for conditional branches at ") +
1086               ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1087                                    Twine(BranchLoc.getLine()) + ":" +
1088                                    Twine(BranchLoc.getCol()))
1089                            : Twine("<UNKNOWN LOCATION>")));
1090     } else {
1091       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1092     }
1093   }
1094 }
1095 
1096 /// \brief Get the line number for the function header.
1097 ///
1098 /// This looks up function \p F in the current compilation unit and
1099 /// retrieves the line number where the function is defined. This is
1100 /// line 0 for all the samples read from the profile file. Every line
1101 /// number is relative to this line.
1102 ///
1103 /// \param F  Function object to query.
1104 ///
1105 /// \returns the line number where \p F is defined. If it returns 0,
1106 ///          it means that there is no debug information available for \p F.
1107 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1108   if (DISubprogram *S = F.getSubprogram())
1109     return S->getLine();
1110 
1111   // If the start of \p F is missing, emit a diagnostic to inform the user
1112   // about the missed opportunity.
1113   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1114       "No debug information found in function " + F.getName() +
1115           ": Function profile not used",
1116       DS_Warning));
1117   return 0;
1118 }
1119 
1120 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1121   DT.reset(new DominatorTree);
1122   DT->recalculate(F);
1123 
1124   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1125   PDT->recalculate(F);
1126 
1127   LI.reset(new LoopInfo);
1128   LI->analyze(*DT);
1129 }
1130 
1131 /// \brief Generate branch weight metadata for all branches in \p F.
1132 ///
1133 /// Branch weights are computed out of instruction samples using a
1134 /// propagation heuristic. Propagation proceeds in 3 phases:
1135 ///
1136 /// 1- Assignment of block weights. All the basic blocks in the function
1137 ///    are initial assigned the same weight as their most frequently
1138 ///    executed instruction.
1139 ///
1140 /// 2- Creation of equivalence classes. Since samples may be missing from
1141 ///    blocks, we can fill in the gaps by setting the weights of all the
1142 ///    blocks in the same equivalence class to the same weight. To compute
1143 ///    the concept of equivalence, we use dominance and loop information.
1144 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1145 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1146 ///
1147 /// 3- Propagation of block weights into edges. This uses a simple
1148 ///    propagation heuristic. The following rules are applied to every
1149 ///    block BB in the CFG:
1150 ///
1151 ///    - If BB has a single predecessor/successor, then the weight
1152 ///      of that edge is the weight of the block.
1153 ///
1154 ///    - If all the edges are known except one, and the weight of the
1155 ///      block is already known, the weight of the unknown edge will
1156 ///      be the weight of the block minus the sum of all the known
1157 ///      edges. If the sum of all the known edges is larger than BB's weight,
1158 ///      we set the unknown edge weight to zero.
1159 ///
1160 ///    - If there is a self-referential edge, and the weight of the block is
1161 ///      known, the weight for that edge is set to the weight of the block
1162 ///      minus the weight of the other incoming edges to that block (if
1163 ///      known).
1164 ///
1165 /// Since this propagation is not guaranteed to finalize for every CFG, we
1166 /// only allow it to proceed for a limited number of iterations (controlled
1167 /// by -sample-profile-max-propagate-iterations).
1168 ///
1169 /// FIXME: Try to replace this propagation heuristic with a scheme
1170 /// that is guaranteed to finalize. A work-list approach similar to
1171 /// the standard value propagation algorithm used by SSA-CCP might
1172 /// work here.
1173 ///
1174 /// Once all the branch weights are computed, we emit the MD_prof
1175 /// metadata on BB using the computed values for each of its branches.
1176 ///
1177 /// \param F The function to query.
1178 ///
1179 /// \returns true if \p F was modified. Returns false, otherwise.
1180 bool SampleProfileLoader::emitAnnotations(Function &F) {
1181   bool Changed = false;
1182 
1183   if (getFunctionLoc(F) == 0)
1184     return false;
1185 
1186   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1187                << ": " << getFunctionLoc(F) << "\n");
1188 
1189   Changed |= emitInlineHints(F);
1190 
1191   Changed |= inlineHotFunctions(F);
1192 
1193   // Compute basic block weights.
1194   Changed |= computeBlockWeights(F);
1195 
1196   if (Changed) {
1197     // Compute dominance and loop info needed for propagation.
1198     computeDominanceAndLoopInfo(F);
1199 
1200     // Find equivalence classes.
1201     findEquivalenceClasses(F);
1202 
1203     // Propagate weights to all edges.
1204     propagateWeights(F);
1205   }
1206 
1207   // If coverage checking was requested, compute it now.
1208   if (SampleProfileRecordCoverage) {
1209     unsigned Used = CoverageTracker.countUsedRecords(Samples);
1210     unsigned Total = CoverageTracker.countBodyRecords(Samples);
1211     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1212     if (Coverage < SampleProfileRecordCoverage) {
1213       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1214           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1215           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1216               Twine(Coverage) + "%) were applied",
1217           DS_Warning));
1218     }
1219   }
1220 
1221   if (SampleProfileSampleCoverage) {
1222     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1223     uint64_t Total = CoverageTracker.countBodySamples(Samples);
1224     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1225     if (Coverage < SampleProfileSampleCoverage) {
1226       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1227           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1228           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1229               Twine(Coverage) + "%) were applied",
1230           DS_Warning));
1231     }
1232   }
1233   return Changed;
1234 }
1235 
1236 char SampleProfileLoaderLegacyPass::ID = 0;
1237 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1238                 "Sample Profile loader", false, false)
1239 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1240 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1241                 "Sample Profile loader", false, false)
1242 
1243 bool SampleProfileLoader::doInitialization(Module &M) {
1244   auto &Ctx = M.getContext();
1245   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1246   if (std::error_code EC = ReaderOrErr.getError()) {
1247     std::string Msg = "Could not open profile: " + EC.message();
1248     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1249     return false;
1250   }
1251   Reader = std::move(ReaderOrErr.get());
1252   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1253   return true;
1254 }
1255 
1256 ModulePass *llvm::createSampleProfileLoaderPass() {
1257   return new SampleProfileLoaderLegacyPass(SampleProfileFile);
1258 }
1259 
1260 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1261   return new SampleProfileLoaderLegacyPass(Name);
1262 }
1263 
1264 bool SampleProfileLoader::runOnModule(Module &M) {
1265   if (!ProfileIsValid)
1266     return false;
1267 
1268   // Compute the total number of samples collected in this profile.
1269   for (const auto &I : Reader->getProfiles())
1270     TotalCollectedSamples += I.second.getTotalSamples();
1271 
1272   bool retval = false;
1273   for (auto &F : M)
1274     if (!F.isDeclaration()) {
1275       clearFunctionData();
1276       retval |= runOnFunction(F);
1277     }
1278   return retval;
1279 }
1280 
1281 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1282   // FIXME: pass in AssumptionCache correctly for the new pass manager.
1283   SampleLoader.setACT(&getAnalysis<AssumptionCacheTracker>());
1284   return SampleLoader.runOnModule(M);
1285 }
1286 
1287 bool SampleProfileLoader::runOnFunction(Function &F) {
1288   F.setEntryCount(0);
1289   Samples = Reader->getSamplesFor(F);
1290   if (!Samples->empty())
1291     return emitAnnotations(F);
1292   return false;
1293 }
1294 
1295 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1296                                                AnalysisManager<Module> &AM) {
1297 
1298   SampleProfileLoader SampleLoader(SampleProfileFile);
1299 
1300   SampleLoader.doInitialization(M);
1301 
1302   if (!SampleLoader.runOnModule(M))
1303     return PreservedAnalyses::all();
1304 
1305   return PreservedAnalyses::none();
1306 }
1307