5cb71f71e707d0897f696f8b9ed244f81fbd8a8d
[oota-llvm.git] / lib / Transforms / IPO / SampleProfile.cpp
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/raw_ostream.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include <cctype>
51
52 using namespace llvm;
53 using namespace sampleprof;
54
55 #define DEBUG_TYPE "sample-profile"
56
57 // Command line option to specify the file to read samples from. This is
58 // mainly used for debugging.
59 static cl::opt<std::string> SampleProfileFile(
60     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
61     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
62 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
63     "sample-profile-max-propagate-iterations", cl::init(100),
64     cl::desc("Maximum number of iterations to go through when propagating "
65              "sample block/edge weights through the CFG."));
66 static cl::opt<unsigned> SampleProfileRecordCoverage(
67     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
68     cl::desc("Emit a warning if less than N% of records in the input profile "
69              "are matched to the IR."));
70 static cl::opt<unsigned> SampleProfileSampleCoverage(
71     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
72     cl::desc("Emit a warning if less than N% of samples in the input profile "
73              "are matched to the IR."));
74 static cl::opt<double> SampleProfileHotThreshold(
75     "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
76     cl::desc("Inlined functions that account for more than N% of all samples "
77              "collected in the parent function, will be inlined again."));
78 static cl::opt<double> SampleProfileGlobalHotThreshold(
79     "sample-profile-global-hot-threshold", cl::init(30), cl::value_desc("N"),
80     cl::desc("Top-level functions that account for more than N% of all samples "
81              "collected in the profile, will be marked as hot for the inliner "
82              "to consider."));
83 static cl::opt<double> SampleProfileGlobalColdThreshold(
84     "sample-profile-global-cold-threshold", cl::init(0.5), cl::value_desc("N"),
85     cl::desc("Top-level functions that account for less than N% of all samples "
86              "collected in the profile, will be marked as cold for the inliner "
87              "to consider."));
88
89 namespace {
90 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
91 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
92 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
93 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
94 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
95     BlockEdgeMap;
96
97 /// \brief Sample profile pass.
98 ///
99 /// This pass reads profile data from the file specified by
100 /// -sample-profile-file and annotates every affected function with the
101 /// profile information found in that file.
102 class SampleProfileLoader : public ModulePass {
103 public:
104   // Class identification, replacement for typeinfo
105   static char ID;
106
107   SampleProfileLoader(StringRef Name = SampleProfileFile)
108       : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
109         Samples(nullptr), Filename(Name), ProfileIsValid(false),
110         TotalCollectedSamples(0) {
111     initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
112   }
113
114   bool doInitialization(Module &M) override;
115
116   void dump() { Reader->dump(); }
117
118   const char *getPassName() const override { return "Sample profile pass"; }
119
120   bool runOnModule(Module &M) override;
121
122   void getAnalysisUsage(AnalysisUsage &AU) const override {
123     AU.setPreservesCFG();
124   }
125
126 protected:
127   bool runOnFunction(Function &F);
128   unsigned getFunctionLoc(Function &F);
129   bool emitAnnotations(Function &F);
130   ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
131   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
132   const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
133   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
134   bool inlineHotFunctions(Function &F);
135   bool emitInlineHints(Function &F);
136   void printEdgeWeight(raw_ostream &OS, Edge E);
137   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
138   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
139   bool computeBlockWeights(Function &F);
140   void findEquivalenceClasses(Function &F);
141   void findEquivalencesFor(BasicBlock *BB1,
142                            SmallVector<BasicBlock *, 8> 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 *, 128> VisitedBlocks;
166
167   /// \brief Set of visited edges during propagation.
168   SmallSet<Edge, 128> 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 DenseMap<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     emitOptimizationRemark(
633         F.getContext(), DEBUG_TYPE, F, DebugLoc(),
634         Twine("Applied inline hint to globally hot function '" + F.getName() +
635               "' with " + Twine(std::to_string(SamplesPercent)) +
636               "% of samples (threshold: " +
637               Twine(std::to_string(SampleProfileGlobalHotThreshold)) + "%)"));
638     return true;
639   }
640
641   // If the function collected fewer samples than the cold threshold, mark
642   // it globally cold.
643   if (SamplesPercent <= SampleProfileGlobalColdThreshold) {
644     F.addFnAttr(llvm::Attribute::Cold);
645     emitOptimizationRemark(
646         F.getContext(), DEBUG_TYPE, F, DebugLoc(),
647         Twine("Applied cold hint to globally cold function '" + F.getName() +
648               "' with " + Twine(std::to_string(SamplesPercent)) +
649               "% of samples (threshold: " +
650               Twine(std::to_string(SampleProfileGlobalColdThreshold)) + "%)"));
651     return true;
652   }
653
654   return false;
655 }
656
657 /// \brief Iteratively inline hot callsites of a function.
658 ///
659 /// Iteratively traverse all callsites of the function \p F, and find if
660 /// the corresponding inlined instance exists and is hot in profile. If
661 /// it is hot enough, inline the callsites and adds new callsites of the
662 /// callee into the caller.
663 ///
664 /// TODO: investigate the possibility of not invoking InlineFunction directly.
665 ///
666 /// \param F function to perform iterative inlining.
667 ///
668 /// \returns True if there is any inline happened.
669 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
670   bool Changed = false;
671   LLVMContext &Ctx = F.getContext();
672   while (true) {
673     bool LocalChanged = false;
674     SmallVector<CallInst *, 10> CIS;
675     for (auto &BB : F) {
676       for (auto &I : BB.getInstList()) {
677         CallInst *CI = dyn_cast<CallInst>(&I);
678         if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
679           CIS.push_back(CI);
680       }
681     }
682     for (auto CI : CIS) {
683       InlineFunctionInfo IFI;
684       Function *CalledFunction = CI->getCalledFunction();
685       DebugLoc DLoc = CI->getDebugLoc();
686       uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
687       if (InlineFunction(CI, IFI)) {
688         LocalChanged = true;
689         emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
690                                Twine("inlined hot callee '") +
691                                    CalledFunction->getName() + "' with " +
692                                    Twine(NumSamples) + " samples into '" +
693                                    F.getName() + "'");
694       }
695     }
696     if (LocalChanged) {
697       Changed = true;
698     } else {
699       break;
700     }
701   }
702   return Changed;
703 }
704
705 /// \brief Find equivalence classes for the given block.
706 ///
707 /// This finds all the blocks that are guaranteed to execute the same
708 /// number of times as \p BB1. To do this, it traverses all the
709 /// descendants of \p BB1 in the dominator or post-dominator tree.
710 ///
711 /// A block BB2 will be in the same equivalence class as \p BB1 if
712 /// the following holds:
713 ///
714 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
715 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
716 ///    dominate BB1 in the post-dominator tree.
717 ///
718 /// 2- Both BB2 and \p BB1 must be in the same loop.
719 ///
720 /// For every block BB2 that meets those two requirements, we set BB2's
721 /// equivalence class to \p BB1.
722 ///
723 /// \param BB1  Block to check.
724 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
725 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
726 ///                 with blocks from \p BB1's dominator tree, then
727 ///                 this is the post-dominator tree, and vice versa.
728 void SampleProfileLoader::findEquivalencesFor(
729     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
730     DominatorTreeBase<BasicBlock> *DomTree) {
731   const BasicBlock *EC = EquivalenceClass[BB1];
732   uint64_t Weight = BlockWeights[EC];
733   for (const auto *BB2 : Descendants) {
734     bool IsDomParent = DomTree->dominates(BB2, BB1);
735     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
736     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
737       EquivalenceClass[BB2] = EC;
738
739       // If BB2 is heavier than BB1, make BB2 have the same weight
740       // as BB1.
741       //
742       // Note that we don't worry about the opposite situation here
743       // (when BB2 is lighter than BB1). We will deal with this
744       // during the propagation phase. Right now, we just want to
745       // make sure that BB1 has the largest weight of all the
746       // members of its equivalence set.
747       Weight = std::max(Weight, BlockWeights[BB2]);
748     }
749   }
750   BlockWeights[EC] = Weight;
751 }
752
753 /// \brief Find equivalence classes.
754 ///
755 /// Since samples may be missing from blocks, we can fill in the gaps by setting
756 /// the weights of all the blocks in the same equivalence class to the same
757 /// weight. To compute the concept of equivalence, we use dominance and loop
758 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
759 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
760 ///
761 /// \param F The function to query.
762 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
763   SmallVector<BasicBlock *, 8> DominatedBBs;
764   DEBUG(dbgs() << "\nBlock equivalence classes\n");
765   // Find equivalence sets based on dominance and post-dominance information.
766   for (auto &BB : F) {
767     BasicBlock *BB1 = &BB;
768
769     // Compute BB1's equivalence class once.
770     if (EquivalenceClass.count(BB1)) {
771       DEBUG(printBlockEquivalence(dbgs(), BB1));
772       continue;
773     }
774
775     // By default, blocks are in their own equivalence class.
776     EquivalenceClass[BB1] = BB1;
777
778     // Traverse all the blocks dominated by BB1. We are looking for
779     // every basic block BB2 such that:
780     //
781     // 1- BB1 dominates BB2.
782     // 2- BB2 post-dominates BB1.
783     // 3- BB1 and BB2 are in the same loop nest.
784     //
785     // If all those conditions hold, it means that BB2 is executed
786     // as many times as BB1, so they are placed in the same equivalence
787     // class by making BB2's equivalence class be BB1.
788     DominatedBBs.clear();
789     DT->getDescendants(BB1, DominatedBBs);
790     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
791
792     DEBUG(printBlockEquivalence(dbgs(), BB1));
793   }
794
795   // Assign weights to equivalence classes.
796   //
797   // All the basic blocks in the same equivalence class will execute
798   // the same number of times. Since we know that the head block in
799   // each equivalence class has the largest weight, assign that weight
800   // to all the blocks in that equivalence class.
801   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
802   for (auto &BI : F) {
803     const BasicBlock *BB = &BI;
804     const BasicBlock *EquivBB = EquivalenceClass[BB];
805     if (BB != EquivBB)
806       BlockWeights[BB] = BlockWeights[EquivBB];
807     DEBUG(printBlockWeight(dbgs(), BB));
808   }
809 }
810
811 /// \brief Visit the given edge to decide if it has a valid weight.
812 ///
813 /// If \p E has not been visited before, we copy to \p UnknownEdge
814 /// and increment the count of unknown edges.
815 ///
816 /// \param E  Edge to visit.
817 /// \param NumUnknownEdges  Current number of unknown edges.
818 /// \param UnknownEdge  Set if E has not been visited before.
819 ///
820 /// \returns E's weight, if known. Otherwise, return 0.
821 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
822                                         Edge *UnknownEdge) {
823   if (!VisitedEdges.count(E)) {
824     (*NumUnknownEdges)++;
825     *UnknownEdge = E;
826     return 0;
827   }
828
829   return EdgeWeights[E];
830 }
831
832 /// \brief Propagate weights through incoming/outgoing edges.
833 ///
834 /// If the weight of a basic block is known, and there is only one edge
835 /// with an unknown weight, we can calculate the weight of that edge.
836 ///
837 /// Similarly, if all the edges have a known count, we can calculate the
838 /// count of the basic block, if needed.
839 ///
840 /// \param F  Function to process.
841 ///
842 /// \returns  True if new weights were assigned to edges or blocks.
843 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
844   bool Changed = false;
845   DEBUG(dbgs() << "\nPropagation through edges\n");
846   for (const auto &BI : F) {
847     const BasicBlock *BB = &BI;
848     const BasicBlock *EC = EquivalenceClass[BB];
849
850     // Visit all the predecessor and successor edges to determine
851     // which ones have a weight assigned already. Note that it doesn't
852     // matter that we only keep track of a single unknown edge. The
853     // only case we are interested in handling is when only a single
854     // edge is unknown (see setEdgeOrBlockWeight).
855     for (unsigned i = 0; i < 2; i++) {
856       uint64_t TotalWeight = 0;
857       unsigned NumUnknownEdges = 0;
858       Edge UnknownEdge, SelfReferentialEdge;
859
860       if (i == 0) {
861         // First, visit all predecessor edges.
862         for (auto *Pred : Predecessors[BB]) {
863           Edge E = std::make_pair(Pred, BB);
864           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
865           if (E.first == E.second)
866             SelfReferentialEdge = E;
867         }
868       } else {
869         // On the second round, visit all successor edges.
870         for (auto *Succ : Successors[BB]) {
871           Edge E = std::make_pair(BB, Succ);
872           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
873         }
874       }
875
876       // After visiting all the edges, there are three cases that we
877       // can handle immediately:
878       //
879       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
880       //   In this case, we simply check that the sum of all the edges
881       //   is the same as BB's weight. If not, we change BB's weight
882       //   to match. Additionally, if BB had not been visited before,
883       //   we mark it visited.
884       //
885       // - Only one edge is unknown and BB has already been visited.
886       //   In this case, we can compute the weight of the edge by
887       //   subtracting the total block weight from all the known
888       //   edge weights. If the edges weight more than BB, then the
889       //   edge of the last remaining edge is set to zero.
890       //
891       // - There exists a self-referential edge and the weight of BB is
892       //   known. In this case, this edge can be based on BB's weight.
893       //   We add up all the other known edges and set the weight on
894       //   the self-referential edge as we did in the previous case.
895       //
896       // In any other case, we must continue iterating. Eventually,
897       // all edges will get a weight, or iteration will stop when
898       // it reaches SampleProfileMaxPropagateIterations.
899       if (NumUnknownEdges <= 1) {
900         uint64_t &BBWeight = BlockWeights[EC];
901         if (NumUnknownEdges == 0) {
902           // If we already know the weight of all edges, the weight of the
903           // basic block can be computed. It should be no larger than the sum
904           // of all edge weights.
905           if (TotalWeight > BBWeight) {
906             BBWeight = TotalWeight;
907             Changed = true;
908             DEBUG(dbgs() << "All edge weights for " << BB->getName()
909                          << " known. Set weight for block: ";
910                   printBlockWeight(dbgs(), BB););
911           }
912           if (VisitedBlocks.insert(EC).second)
913             Changed = true;
914         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
915           // If there is a single unknown edge and the block has been
916           // visited, then we can compute E's weight.
917           if (BBWeight >= TotalWeight)
918             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
919           else
920             EdgeWeights[UnknownEdge] = 0;
921           VisitedEdges.insert(UnknownEdge);
922           Changed = true;
923           DEBUG(dbgs() << "Set weight for edge: ";
924                 printEdgeWeight(dbgs(), UnknownEdge));
925         }
926       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
927         uint64_t &BBWeight = BlockWeights[BB];
928         // We have a self-referential edge and the weight of BB is known.
929         if (BBWeight >= TotalWeight)
930           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
931         else
932           EdgeWeights[SelfReferentialEdge] = 0;
933         VisitedEdges.insert(SelfReferentialEdge);
934         Changed = true;
935         DEBUG(dbgs() << "Set self-referential edge weight to: ";
936               printEdgeWeight(dbgs(), SelfReferentialEdge));
937       }
938     }
939   }
940
941   return Changed;
942 }
943
944 /// \brief Build in/out edge lists for each basic block in the CFG.
945 ///
946 /// We are interested in unique edges. If a block B1 has multiple
947 /// edges to another block B2, we only add a single B1->B2 edge.
948 void SampleProfileLoader::buildEdges(Function &F) {
949   for (auto &BI : F) {
950     BasicBlock *B1 = &BI;
951
952     // Add predecessors for B1.
953     SmallPtrSet<BasicBlock *, 16> Visited;
954     if (!Predecessors[B1].empty())
955       llvm_unreachable("Found a stale predecessors list in a basic block.");
956     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
957       BasicBlock *B2 = *PI;
958       if (Visited.insert(B2).second)
959         Predecessors[B1].push_back(B2);
960     }
961
962     // Add successors for B1.
963     Visited.clear();
964     if (!Successors[B1].empty())
965       llvm_unreachable("Found a stale successors list in a basic block.");
966     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
967       BasicBlock *B2 = *SI;
968       if (Visited.insert(B2).second)
969         Successors[B1].push_back(B2);
970     }
971   }
972 }
973
974 /// \brief Propagate weights into edges
975 ///
976 /// The following rules are applied to every block BB in the CFG:
977 ///
978 /// - If BB has a single predecessor/successor, then the weight
979 ///   of that edge is the weight of the block.
980 ///
981 /// - If all incoming or outgoing edges are known except one, and the
982 ///   weight of the block is already known, the weight of the unknown
983 ///   edge will be the weight of the block minus the sum of all the known
984 ///   edges. If the sum of all the known edges is larger than BB's weight,
985 ///   we set the unknown edge weight to zero.
986 ///
987 /// - If there is a self-referential edge, and the weight of the block is
988 ///   known, the weight for that edge is set to the weight of the block
989 ///   minus the weight of the other incoming edges to that block (if
990 ///   known).
991 void SampleProfileLoader::propagateWeights(Function &F) {
992   bool Changed = true;
993   unsigned I = 0;
994
995   // Add an entry count to the function using the samples gathered
996   // at the function entry.
997   F.setEntryCount(Samples->getHeadSamples());
998
999   // Before propagation starts, build, for each block, a list of
1000   // unique predecessors and successors. This is necessary to handle
1001   // identical edges in multiway branches. Since we visit all blocks and all
1002   // edges of the CFG, it is cleaner to build these lists once at the start
1003   // of the pass.
1004   buildEdges(F);
1005
1006   // Propagate until we converge or we go past the iteration limit.
1007   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1008     Changed = propagateThroughEdges(F);
1009   }
1010
1011   // Generate MD_prof metadata for every branch instruction using the
1012   // edge weights computed during propagation.
1013   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1014   LLVMContext &Ctx = F.getContext();
1015   MDBuilder MDB(Ctx);
1016   for (auto &BI : F) {
1017     BasicBlock *BB = &BI;
1018     TerminatorInst *TI = BB->getTerminator();
1019     if (TI->getNumSuccessors() == 1)
1020       continue;
1021     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1022       continue;
1023
1024     DEBUG(dbgs() << "\nGetting weights for branch at line "
1025                  << TI->getDebugLoc().getLine() << ".\n");
1026     SmallVector<uint32_t, 4> Weights;
1027     uint32_t MaxWeight = 0;
1028     DebugLoc MaxDestLoc;
1029     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1030       BasicBlock *Succ = TI->getSuccessor(I);
1031       Edge E = std::make_pair(BB, Succ);
1032       uint64_t Weight = EdgeWeights[E];
1033       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1034       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1035       // if needed. Sample counts in profiles are 64-bit unsigned values,
1036       // but internally branch weights are expressed as 32-bit values.
1037       if (Weight > std::numeric_limits<uint32_t>::max()) {
1038         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1039         Weight = std::numeric_limits<uint32_t>::max();
1040       }
1041       Weights.push_back(static_cast<uint32_t>(Weight));
1042       if (Weight != 0) {
1043         if (Weight > MaxWeight) {
1044           MaxWeight = Weight;
1045           MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1046         }
1047       }
1048     }
1049
1050     // Only set weights if there is at least one non-zero weight.
1051     // In any other case, let the analyzer set weights.
1052     if (MaxWeight > 0) {
1053       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1054       TI->setMetadata(llvm::LLVMContext::MD_prof,
1055                       MDB.createBranchWeights(Weights));
1056       DebugLoc BranchLoc = TI->getDebugLoc();
1057       emitOptimizationRemark(
1058           Ctx, DEBUG_TYPE, F, MaxDestLoc,
1059           Twine("most popular destination for conditional branches at ") +
1060               ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1061                                    Twine(BranchLoc.getLine()) + ":" +
1062                                    Twine(BranchLoc.getCol()))
1063                            : Twine("<UNKNOWN LOCATION>")));
1064     } else {
1065       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1066     }
1067   }
1068 }
1069
1070 /// \brief Get the line number for the function header.
1071 ///
1072 /// This looks up function \p F in the current compilation unit and
1073 /// retrieves the line number where the function is defined. This is
1074 /// line 0 for all the samples read from the profile file. Every line
1075 /// number is relative to this line.
1076 ///
1077 /// \param F  Function object to query.
1078 ///
1079 /// \returns the line number where \p F is defined. If it returns 0,
1080 ///          it means that there is no debug information available for \p F.
1081 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1082   if (DISubprogram *S = getDISubprogram(&F))
1083     return S->getLine();
1084
1085   // If the start of \p F is missing, emit a diagnostic to inform the user
1086   // about the missed opportunity.
1087   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1088       "No debug information found in function " + F.getName() +
1089           ": Function profile not used",
1090       DS_Warning));
1091   return 0;
1092 }
1093
1094 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1095   DT.reset(new DominatorTree);
1096   DT->recalculate(F);
1097
1098   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1099   PDT->recalculate(F);
1100
1101   LI.reset(new LoopInfo);
1102   LI->analyze(*DT);
1103 }
1104
1105 /// \brief Generate branch weight metadata for all branches in \p F.
1106 ///
1107 /// Branch weights are computed out of instruction samples using a
1108 /// propagation heuristic. Propagation proceeds in 3 phases:
1109 ///
1110 /// 1- Assignment of block weights. All the basic blocks in the function
1111 ///    are initial assigned the same weight as their most frequently
1112 ///    executed instruction.
1113 ///
1114 /// 2- Creation of equivalence classes. Since samples may be missing from
1115 ///    blocks, we can fill in the gaps by setting the weights of all the
1116 ///    blocks in the same equivalence class to the same weight. To compute
1117 ///    the concept of equivalence, we use dominance and loop information.
1118 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1119 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1120 ///
1121 /// 3- Propagation of block weights into edges. This uses a simple
1122 ///    propagation heuristic. The following rules are applied to every
1123 ///    block BB in the CFG:
1124 ///
1125 ///    - If BB has a single predecessor/successor, then the weight
1126 ///      of that edge is the weight of the block.
1127 ///
1128 ///    - If all the edges are known except one, and the weight of the
1129 ///      block is already known, the weight of the unknown edge will
1130 ///      be the weight of the block minus the sum of all the known
1131 ///      edges. If the sum of all the known edges is larger than BB's weight,
1132 ///      we set the unknown edge weight to zero.
1133 ///
1134 ///    - If there is a self-referential edge, and the weight of the block is
1135 ///      known, the weight for that edge is set to the weight of the block
1136 ///      minus the weight of the other incoming edges to that block (if
1137 ///      known).
1138 ///
1139 /// Since this propagation is not guaranteed to finalize for every CFG, we
1140 /// only allow it to proceed for a limited number of iterations (controlled
1141 /// by -sample-profile-max-propagate-iterations).
1142 ///
1143 /// FIXME: Try to replace this propagation heuristic with a scheme
1144 /// that is guaranteed to finalize. A work-list approach similar to
1145 /// the standard value propagation algorithm used by SSA-CCP might
1146 /// work here.
1147 ///
1148 /// Once all the branch weights are computed, we emit the MD_prof
1149 /// metadata on BB using the computed values for each of its branches.
1150 ///
1151 /// \param F The function to query.
1152 ///
1153 /// \returns true if \p F was modified. Returns false, otherwise.
1154 bool SampleProfileLoader::emitAnnotations(Function &F) {
1155   bool Changed = false;
1156
1157   if (getFunctionLoc(F) == 0)
1158     return false;
1159
1160   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1161                << ": " << getFunctionLoc(F) << "\n");
1162
1163   Changed |= emitInlineHints(F);
1164
1165   Changed |= inlineHotFunctions(F);
1166
1167   // Compute basic block weights.
1168   Changed |= computeBlockWeights(F);
1169
1170   if (Changed) {
1171     // Compute dominance and loop info needed for propagation.
1172     computeDominanceAndLoopInfo(F);
1173
1174     // Find equivalence classes.
1175     findEquivalenceClasses(F);
1176
1177     // Propagate weights to all edges.
1178     propagateWeights(F);
1179   }
1180
1181   // If coverage checking was requested, compute it now.
1182   if (SampleProfileRecordCoverage) {
1183     unsigned Used = CoverageTracker.countUsedRecords(Samples);
1184     unsigned Total = CoverageTracker.countBodyRecords(Samples);
1185     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1186     if (Coverage < SampleProfileRecordCoverage) {
1187       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1188           getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1189           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1190               Twine(Coverage) + "%) were applied",
1191           DS_Warning));
1192     }
1193   }
1194
1195   if (SampleProfileSampleCoverage) {
1196     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1197     uint64_t Total = CoverageTracker.countBodySamples(Samples);
1198     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1199     if (Coverage < SampleProfileSampleCoverage) {
1200       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1201           getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1202           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1203               Twine(Coverage) + "%) were applied",
1204           DS_Warning));
1205     }
1206   }
1207   return Changed;
1208 }
1209
1210 char SampleProfileLoader::ID = 0;
1211 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1212                       "Sample Profile loader", false, false)
1213 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1214 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1215                     "Sample Profile loader", false, false)
1216
1217 bool SampleProfileLoader::doInitialization(Module &M) {
1218   auto &Ctx = M.getContext();
1219   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1220   if (std::error_code EC = ReaderOrErr.getError()) {
1221     std::string Msg = "Could not open profile: " + EC.message();
1222     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1223     return false;
1224   }
1225   Reader = std::move(ReaderOrErr.get());
1226   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1227   return true;
1228 }
1229
1230 ModulePass *llvm::createSampleProfileLoaderPass() {
1231   return new SampleProfileLoader(SampleProfileFile);
1232 }
1233
1234 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1235   return new SampleProfileLoader(Name);
1236 }
1237
1238 bool SampleProfileLoader::runOnModule(Module &M) {
1239   if (!ProfileIsValid)
1240     return false;
1241
1242   // Compute the total number of samples collected in this profile.
1243   for (const auto &I : Reader->getProfiles())
1244     TotalCollectedSamples += I.second.getTotalSamples();
1245
1246   bool retval = false;
1247   for (auto &F : M)
1248     if (!F.isDeclaration()) {
1249       clearFunctionData();
1250       retval |= runOnFunction(F);
1251     }
1252   return retval;
1253 }
1254
1255 bool SampleProfileLoader::runOnFunction(Function &F) {
1256   Samples = Reader->getSamplesFor(F);
1257   if (!Samples->empty())
1258     return emitAnnotations(F);
1259   return false;
1260 }