1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 // This pass generates branch weight annotations on the IR:
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.
23 //===----------------------------------------------------------------------===//
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"
53 using namespace sampleprof;
55 #define DEBUG_TYPE "sample-profile"
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 "
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 "
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>>
97 /// \brief Sample profile pass.
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 {
104 // Class identification, replacement for typeinfo
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());
114 bool doInitialization(Module &M) override;
116 void dump() { Reader->dump(); }
118 const char *getPassName() const override { return "Sample profile pass"; }
120 bool runOnModule(Module &M) override;
122 void getAnalysisUsage(AnalysisUsage &AU) const override {
123 AU.setPreservesCFG();
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();
152 /// \brief Map basic blocks to their computed weights.
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;
158 /// \brief Map edges to their computed weights.
160 /// Edge weights are computed by propagating basic block weights in
161 /// SampleProfile::propagateWeights.
162 EdgeWeightMap EdgeWeights;
164 /// \brief Set of visited blocks during propagation.
165 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
167 /// \brief Set of visited edges during propagation.
168 SmallSet<Edge, 128> VisitedEdges;
170 /// \brief Equivalence classes for block weights.
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;
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;
183 /// \brief Predecessors for each basic block in the CFG.
184 BlockEdgeMap Predecessors;
186 /// \brief Successors for each basic block in the CFG.
187 BlockEdgeMap Successors;
189 /// \brief Profile reader object.
190 std::unique_ptr<SampleProfileReader> Reader;
192 /// \brief Samples collected for the body of this function.
193 FunctionSamples *Samples;
195 /// \brief Name of the profile file to load.
198 /// \brief Flag indicating whether the profile input loaded successfully.
201 /// \brief Total number of samples collected in this profile.
203 /// This is the sum of all the samples collected in all the functions executed
205 uint64_t TotalCollectedSamples;
208 class SampleCoverageTracker {
210 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
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;
220 SampleCoverage.clear();
221 TotalUsedSamples = 0;
225 typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
226 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
227 FunctionSamplesCoverageMap;
229 /// Coverage map for sampling records.
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).
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;
240 /// Number of samples used from the profile.
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
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;
254 SampleCoverageTracker CoverageTracker;
256 /// Return true if the given callsite is hot wrt to its caller.
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.
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.
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) {
273 return false; // The callsite was not inlined in the original binary.
275 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
276 if (ParentTotalSamples == 0)
277 return false; // Avoid division by zero.
279 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
280 if (CallsiteTotalSamples == 0)
281 return false; // Callsite is trivially cold.
283 double PercentSamples =
284 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
285 return PercentSamples >= SampleProfileHotThreshold;
290 /// Mark as used the sample record for the given function samples at
291 /// (LineOffset, Discriminator).
293 /// \returns true if this is the first time we mark the given record.
294 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
296 uint32_t Discriminator,
298 LineLocation Loc(LineOffset, Discriminator);
299 unsigned &Count = SampleCoverage[FS][Loc];
300 bool FirstTime = (++Count == 1);
302 TotalUsedSamples += Samples;
306 /// Return the number of sample records that were applied from this profile.
308 /// This count does not include records from cold inlined callsites.
310 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
311 auto I = SampleCoverage.find(FS);
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;
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);
329 /// Return the number of sample records in the body of this profile.
331 /// This count does not include records from cold inlined callsites.
333 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
334 unsigned Count = FS->getBodySamples().size();
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);
346 /// Return the number of samples collected in the body of this profile.
348 /// This count does not include samples from cold inlined callsites.
350 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
352 for (const auto &I : FS->getBodySamples())
353 Total += I.second.getSamples();
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);
365 /// Return the fraction of sample records used in this profile.
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;
377 /// Clear all the per-function data used to load samples and propagate weights.
378 void SampleProfileLoader::clearFunctionData() {
379 BlockWeights.clear();
381 VisitedBlocks.clear();
382 VisitedEdges.clear();
383 EquivalenceClass.clear();
387 Predecessors.clear();
389 CoverageTracker.clear();
392 /// \brief Returns the offset of lineno \p L to head_lineno \p H
395 /// \param H Header lineno of the function
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;
403 /// \brief Print the weight of edge \p E on stream \p OS.
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";
412 /// \brief Print the equivalence class of block \p BB on stream \p OS.
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";
423 /// \brief Print the weight of block \p BB on stream \p OS.
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";
434 /// \brief Get the weight for an instruction.
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.
442 /// \param Inst Instruction to query.
444 /// \returns the weight of \p Inst.
446 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
447 DebugLoc DLoc = Inst.getDebugLoc();
449 return std::error_code();
451 const FunctionSamples *FS = findFunctionSamples(Inst);
453 return std::error_code();
455 const DILocation *DIL = DLoc;
456 unsigned Lineno = DLoc.getLine();
457 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
459 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
460 uint32_t Discriminator = DIL->getDiscriminator();
461 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
464 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
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: " +
472 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
474 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
475 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
476 << DIL->getDiscriminator() << " - weight: " << R.get()
482 /// \brief Compute the weight of a basic block.
484 /// The weight of basic block \p BB is the maximum weight of all the
485 /// instructions in BB.
487 /// \param BB The basic block to query.
489 /// \returns the weight for \p BB.
491 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
494 for (auto &I : BB->getInstList()) {
495 const ErrorOr<uint64_t> &R = getInstWeight(I);
496 if (R && R.get() >= Weight) {
504 return std::error_code();
507 /// \brief Compute and store the weights of every basic block.
509 /// This populates the BlockWeights map by computing
510 /// the weights of every basic block in the CFG.
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);
519 BlockWeights[&BB] = Weight.get();
520 VisitedBlocks.insert(&BB);
523 DEBUG(printBlockWeight(dbgs(), &BB));
529 /// \brief Get the FunctionSamples for a call instruction.
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.
538 /// \param Inst Call instruction to query.
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();
547 DISubprogram *SP = DIL->getScope()->getSubprogram();
551 Function *CalleeFunc = Inst.getCalledFunction();
556 StringRef CalleeName = CalleeFunc->getName();
557 const FunctionSamples *FS = findFunctionSamples(Inst);
561 return FS->findFunctionSamplesAt(
562 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
563 DIL->getDiscriminator(), CalleeName));
566 /// \brief Get the FunctionSamples for an instruction.
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.
572 /// \param Inst Instruction to query.
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();
582 StringRef CalleeName;
583 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
584 DIL = DIL->getInlinedAt()) {
585 DISubprogram *SP = DIL->getScope()->getSubprogram();
588 if (!CalleeName.empty()) {
589 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
590 DIL->getDiscriminator(), CalleeName));
592 CalleeName = SP->getLinkageName();
596 const FunctionSamples *FS = Samples;
597 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
598 FS = FS->findFunctionSamplesAt(S[i]);
603 /// \brief Emit an inline hint if \p F is globally hot or cold.
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.
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.
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
619 /// \returns True if either attribute was applied to \p F.
620 bool SampleProfileLoader::emitInlineHints(Function &F) {
621 if (TotalCollectedSamples == 0)
624 uint64_t FunctionSamples = Samples->getTotalSamples();
625 double SamplesPercent =
626 (double)FunctionSamples / (double)TotalCollectedSamples * 100.0;
628 // If the function collected more samples than the hot threshold, mark
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)) + "%)"));
641 // If the function collected fewer samples than the cold threshold, mark
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)) + "%)"));
657 /// \brief Iteratively inline hot callsites of a function.
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.
664 /// TODO: investigate the possibility of not invoking InlineFunction directly.
666 /// \param F function to perform iterative inlining.
668 /// \returns True if there is any inline happened.
669 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
670 bool Changed = false;
671 LLVMContext &Ctx = F.getContext();
673 bool LocalChanged = false;
674 SmallVector<CallInst *, 10> CIS;
676 for (auto &I : BB.getInstList()) {
677 CallInst *CI = dyn_cast<CallInst>(&I);
678 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
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)) {
689 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
690 Twine("inlined hot callee '") +
691 CalledFunction->getName() + "' with " +
692 Twine(NumSamples) + " samples into '" +
705 /// \brief Find equivalence classes for the given block.
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.
711 /// A block BB2 will be in the same equivalence class as \p BB1 if
712 /// the following holds:
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.
718 /// 2- Both BB2 and \p BB1 must be in the same loop.
720 /// For every block BB2 that meets those two requirements, we set BB2's
721 /// equivalence class to \p BB1.
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;
739 // If BB2 is heavier than BB1, make BB2 have the same weight
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]);
750 BlockWeights[EC] = Weight;
753 /// \brief Find equivalence classes.
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.
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.
767 BasicBlock *BB1 = &BB;
769 // Compute BB1's equivalence class once.
770 if (EquivalenceClass.count(BB1)) {
771 DEBUG(printBlockEquivalence(dbgs(), BB1));
775 // By default, blocks are in their own equivalence class.
776 EquivalenceClass[BB1] = BB1;
778 // Traverse all the blocks dominated by BB1. We are looking for
779 // every basic block BB2 such that:
781 // 1- BB1 dominates BB2.
782 // 2- BB2 post-dominates BB1.
783 // 3- BB1 and BB2 are in the same loop nest.
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());
792 DEBUG(printBlockEquivalence(dbgs(), BB1));
795 // Assign weights to equivalence classes.
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");
803 const BasicBlock *BB = &BI;
804 const BasicBlock *EquivBB = EquivalenceClass[BB];
806 BlockWeights[BB] = BlockWeights[EquivBB];
807 DEBUG(printBlockWeight(dbgs(), BB));
811 /// \brief Visit the given edge to decide if it has a valid weight.
813 /// If \p E has not been visited before, we copy to \p UnknownEdge
814 /// and increment the count of unknown edges.
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.
820 /// \returns E's weight, if known. Otherwise, return 0.
821 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
823 if (!VisitedEdges.count(E)) {
824 (*NumUnknownEdges)++;
829 return EdgeWeights[E];
832 /// \brief Propagate weights through incoming/outgoing edges.
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.
837 /// Similarly, if all the edges have a known count, we can calculate the
838 /// count of the basic block, if needed.
840 /// \param F Function to process.
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];
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;
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;
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);
876 // After visiting all the edges, there are three cases that we
877 // can handle immediately:
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.
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.
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.
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;
908 DEBUG(dbgs() << "All edge weights for " << BB->getName()
909 << " known. Set weight for block: ";
910 printBlockWeight(dbgs(), BB););
912 if (VisitedBlocks.insert(EC).second)
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;
920 EdgeWeights[UnknownEdge] = 0;
921 VisitedEdges.insert(UnknownEdge);
923 DEBUG(dbgs() << "Set weight for edge: ";
924 printEdgeWeight(dbgs(), UnknownEdge));
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;
932 EdgeWeights[SelfReferentialEdge] = 0;
933 VisitedEdges.insert(SelfReferentialEdge);
935 DEBUG(dbgs() << "Set self-referential edge weight to: ";
936 printEdgeWeight(dbgs(), SelfReferentialEdge));
944 /// \brief Build in/out edge lists for each basic block in the CFG.
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) {
950 BasicBlock *B1 = &BI;
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);
962 // Add successors for B1.
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);
974 /// \brief Propagate weights into edges
976 /// The following rules are applied to every block BB in the CFG:
978 /// - If BB has a single predecessor/successor, then the weight
979 /// of that edge is the weight of the block.
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.
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
991 void SampleProfileLoader::propagateWeights(Function &F) {
995 // Add an entry count to the function using the samples gathered
996 // at the function entry.
997 F.setEntryCount(Samples->getHeadSamples());
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
1006 // Propagate until we converge or we go past the iteration limit.
1007 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1008 Changed = propagateThroughEdges(F);
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();
1016 for (auto &BI : F) {
1017 BasicBlock *BB = &BI;
1018 TerminatorInst *TI = BB->getTerminator();
1019 if (TI->getNumSuccessors() == 1)
1021 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
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();
1041 Weights.push_back(static_cast<uint32_t>(Weight));
1043 if (Weight > MaxWeight) {
1045 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
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>")));
1065 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1070 /// \brief Get the line number for the function header.
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.
1077 /// \param F Function object to query.
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();
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",
1094 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1095 DT.reset(new DominatorTree);
1098 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1099 PDT->recalculate(F);
1101 LI.reset(new LoopInfo);
1105 /// \brief Generate branch weight metadata for all branches in \p F.
1107 /// Branch weights are computed out of instruction samples using a
1108 /// propagation heuristic. Propagation proceeds in 3 phases:
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.
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.
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:
1125 /// - If BB has a single predecessor/successor, then the weight
1126 /// of that edge is the weight of the block.
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.
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
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).
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
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.
1151 /// \param F The function to query.
1153 /// \returns true if \p F was modified. Returns false, otherwise.
1154 bool SampleProfileLoader::emitAnnotations(Function &F) {
1155 bool Changed = false;
1157 if (getFunctionLoc(F) == 0)
1160 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1161 << ": " << getFunctionLoc(F) << "\n");
1163 Changed |= emitInlineHints(F);
1165 Changed |= inlineHotFunctions(F);
1167 // Compute basic block weights.
1168 Changed |= computeBlockWeights(F);
1171 // Compute dominance and loop info needed for propagation.
1172 computeDominanceAndLoopInfo(F);
1174 // Find equivalence classes.
1175 findEquivalenceClasses(F);
1177 // Propagate weights to all edges.
1178 propagateWeights(F);
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",
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",
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)
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));
1225 Reader = std::move(ReaderOrErr.get());
1226 ProfileIsValid = (Reader->read() == sampleprof_error::success);
1230 ModulePass *llvm::createSampleProfileLoaderPass() {
1231 return new SampleProfileLoader(SampleProfileFile);
1234 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1235 return new SampleProfileLoader(Name);
1238 bool SampleProfileLoader::runOnModule(Module &M) {
1239 if (!ProfileIsValid)
1242 // Compute the total number of samples collected in this profile.
1243 for (const auto &I : Reader->getProfiles())
1244 TotalCollectedSamples += I.second.getTotalSamples();
1246 bool retval = false;
1248 if (!F.isDeclaration()) {
1249 clearFunctionData();
1250 retval |= runOnFunction(F);
1255 bool SampleProfileLoader::runOnFunction(Function &F) {
1256 Samples = Reader->getSamplesFor(F);
1257 if (!Samples->empty())
1258 return emitAnnotations(F);