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