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