blob: 6c0ce76be6dd36985783b624a4dd41beb1434544 [file] [log] [blame]
Diego Novillo8d6568b2013-11-13 12:22:21 +00001//===- 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
Diego Novillo8d6568b2013-11-13 12:22:21 +000025#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000026#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000027#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000028#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000029#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000030#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000031#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000033#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000035#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000036#include "llvm/IR/InstIterator.h"
Dehao Chena8bae822016-04-20 23:36:23 +000037#include "llvm/IR/IntrinsicInst.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000038#include "llvm/IR/Instructions.h"
39#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000041#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000042#include "llvm/IR/Module.h"
43#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000044#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000047#include "llvm/Support/ErrorOr.h"
Diego Novillo7ff0a172015-11-29 18:23:26 +000048#include "llvm/Support/Format.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000049#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000050#include "llvm/Transforms/IPO.h"
Dehao Chen57d1dda2016-03-03 18:09:32 +000051#include "llvm/Transforms/Utils/Cloning.h"
Logan Chien61c6df02014-02-22 06:34:10 +000052#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000053
54using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000055using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000056
Chandler Carruth964daaa2014-04-22 02:55:47 +000057#define DEBUG_TYPE "sample-profile"
58
Diego Novillo8d6568b2013-11-13 12:22:21 +000059// Command line option to specify the file to read samples from. This is
60// mainly used for debugging.
61static cl::opt<std::string> SampleProfileFile(
62 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
63 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000064static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
65 "sample-profile-max-propagate-iterations", cl::init(100),
66 cl::desc("Maximum number of iterations to go through when propagating "
67 "sample block/edge weights through the CFG."));
Diego Novillo243ea6a2015-11-23 20:12:21 +000068static cl::opt<unsigned> SampleProfileRecordCoverage(
69 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
70 cl::desc("Emit a warning if less than N% of records in the input profile "
71 "are matched to the IR."));
72static cl::opt<unsigned> SampleProfileSampleCoverage(
73 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +000074 cl::desc("Emit a warning if less than N% of samples in the input profile "
75 "are matched to the IR."));
Diego Novillob5792402015-11-27 23:14:49 +000076static cl::opt<double> SampleProfileHotThreshold(
77 "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
Diego Novillo0b6985a2015-11-24 22:38:37 +000078 cl::desc("Inlined functions that account for more than N% of all samples "
79 "collected in the parent function, will be inlined again."));
Diego Novillo84f06cc2015-11-27 23:14:51 +000080static cl::opt<double> SampleProfileGlobalHotThreshold(
81 "sample-profile-global-hot-threshold", cl::init(30), cl::value_desc("N"),
82 cl::desc("Top-level functions that account for more than N% of all samples "
83 "collected in the profile, will be marked as hot for the inliner "
84 "to consider."));
85static cl::opt<double> SampleProfileGlobalColdThreshold(
86 "sample-profile-global-cold-threshold", cl::init(0.5), cl::value_desc("N"),
87 cl::desc("Top-level functions that account for less than N% of all samples "
88 "collected in the profile, will be marked as cold for the inliner "
89 "to consider."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000090
91namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000092typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000093typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
94typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000095typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000096typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
97 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000098
Diego Novillode1ab262014-09-09 12:40:50 +000099/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000100///
Diego Novillode1ab262014-09-09 12:40:50 +0000101/// This pass reads profile data from the file specified by
102/// -sample-profile-file and annotates every affected function with the
103/// profile information found in that file.
Xinliang David Lie897edb2016-05-27 22:30:44 +0000104class SampleProfileLoader {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000105public:
Diego Novillode1ab262014-09-09 12:40:50 +0000106 SampleProfileLoader(StringRef Name = SampleProfileFile)
Xinliang David Lie897edb2016-05-27 22:30:44 +0000107 : DT(nullptr), PDT(nullptr), LI(nullptr), Reader(), Samples(nullptr),
108 Filename(Name), ProfileIsValid(false), TotalCollectedSamples(0) {}
Diego Novillode1ab262014-09-09 12:40:50 +0000109
Xinliang David Lie897edb2016-05-27 22:30:44 +0000110 bool doInitialization(Module &M);
111 bool runOnModule(Module &M);
Diego Novillode1ab262014-09-09 12:40:50 +0000112
113 void dump() { Reader->dump(); }
114
Diego Novillode1ab262014-09-09 12:40:50 +0000115protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000116 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000117 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000118 bool emitAnnotations(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000119 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
120 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
Dehao Chen67226882015-09-30 00:42:46 +0000121 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
122 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
123 bool inlineHotFunctions(Function &F);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000124 bool emitInlineHints(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000125 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000126 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
127 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000128 bool computeBlockWeights(Function &F);
129 void findEquivalenceClasses(Function &F);
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000130 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000131 DominatorTreeBase<BasicBlock> *DomTree);
132 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000133 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000134 void buildEdges(Function &F);
135 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000136 void computeDominanceAndLoopInfo(Function &F);
Dehao Chen10042412015-10-21 01:22:27 +0000137 unsigned getOffset(unsigned L, unsigned H) const;
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000138 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000139
Diego Novilloc0dd1032013-11-26 20:37:33 +0000140 /// \brief Map basic blocks to their computed weights.
141 ///
142 /// The weight of a basic block is defined to be the maximum
143 /// of all the instruction weights in that block.
144 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000145
146 /// \brief Map edges to their computed weights.
147 ///
148 /// Edge weights are computed by propagating basic block weights in
149 /// SampleProfile::propagateWeights.
150 EdgeWeightMap EdgeWeights;
151
152 /// \brief Set of visited blocks during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000153 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000154
155 /// \brief Set of visited edges during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000156 SmallSet<Edge, 32> VisitedEdges;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000157
158 /// \brief Equivalence classes for block weights.
159 ///
160 /// Two blocks BB1 and BB2 are in the same equivalence class if they
161 /// dominate and post-dominate each other, and they are in the same loop
162 /// nest. When this happens, the two blocks are guaranteed to execute
163 /// the same number of times.
164 EquivalenceClassMap EquivalenceClass;
165
166 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000167 std::unique_ptr<DominatorTree> DT;
168 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
169 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000170
171 /// \brief Predecessors for each basic block in the CFG.
172 BlockEdgeMap Predecessors;
173
174 /// \brief Successors for each basic block in the CFG.
175 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000176
Diego Novillo8d6568b2013-11-13 12:22:21 +0000177 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000178 std::unique_ptr<SampleProfileReader> Reader;
179
180 /// \brief Samples collected for the body of this function.
181 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000182
183 /// \brief Name of the profile file to load.
184 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000185
Alp Toker16f98b22014-04-09 14:47:27 +0000186 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000187 bool ProfileIsValid;
Diego Novillo84f06cc2015-11-27 23:14:51 +0000188
189 /// \brief Total number of samples collected in this profile.
190 ///
191 /// This is the sum of all the samples collected in all the functions executed
192 /// at runtime.
193 uint64_t TotalCollectedSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000194};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000195
Xinliang David Lie897edb2016-05-27 22:30:44 +0000196class SampleProfileLoaderLegacyPass : public ModulePass {
197public:
198 // Class identification, replacement for typeinfo
199 static char ID;
200
201 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
202 : ModulePass(ID), SampleLoader(Name) {
203 initializeSampleProfileLoaderLegacyPassPass(
204 *PassRegistry::getPassRegistry());
205 }
206
207 void dump() { SampleLoader.dump(); }
208
209 bool doInitialization(Module &M) override {
210 return SampleLoader.doInitialization(M);
211 }
212 const char *getPassName() const override { return "Sample profile pass"; }
213 bool runOnModule(Module &M) override;
214
215private:
216 SampleProfileLoader SampleLoader;
217};
218
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000219class SampleCoverageTracker {
220public:
Diego Novillo243ea6a2015-11-23 20:12:21 +0000221 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000222
Diego Novillo243ea6a2015-11-23 20:12:21 +0000223 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
224 uint32_t Discriminator, uint64_t Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +0000225 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000226 unsigned countUsedRecords(const FunctionSamples *FS) const;
227 unsigned countBodyRecords(const FunctionSamples *FS) const;
228 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
229 uint64_t countBodySamples(const FunctionSamples *FS) const;
230 void clear() {
231 SampleCoverage.clear();
232 TotalUsedSamples = 0;
233 }
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000234
235private:
Diego Novillo10cf1242015-12-11 23:21:38 +0000236 typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000237 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
238 FunctionSamplesCoverageMap;
239
240 /// Coverage map for sampling records.
241 ///
242 /// This map keeps a record of sampling records that have been matched to
243 /// an IR instruction. This is used to detect some form of staleness in
244 /// profiles (see flag -sample-profile-check-coverage).
245 ///
246 /// Each entry in the map corresponds to a FunctionSamples instance. This is
247 /// another map that counts how many times the sample record at the
248 /// given location has been used.
249 FunctionSamplesCoverageMap SampleCoverage;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000250
251 /// Number of samples used from the profile.
252 ///
253 /// When a sampling record is used for the first time, the samples from
254 /// that record are added to this accumulator. Coverage is later computed
255 /// based on the total number of samples available in this function and
256 /// its callsites.
257 ///
258 /// Note that this accumulator tracks samples used from a single function
259 /// and all the inlined callsites. Strictly, we should have a map of counters
260 /// keyed by FunctionSamples pointers, but these stats are cleared after
261 /// every function, so we just need to keep a single counter.
262 uint64_t TotalUsedSamples;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000263};
264
265SampleCoverageTracker CoverageTracker;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000266
267/// Return true if the given callsite is hot wrt to its caller.
268///
269/// Functions that were inlined in the original binary will be represented
270/// in the inline stack in the sample profile. If the profile shows that
271/// the original inline decision was "good" (i.e., the callsite is executed
272/// frequently), then we will recreate the inline decision and apply the
273/// profile from the inlined callsite.
274///
275/// To decide whether an inlined callsite is hot, we compute the fraction
276/// of samples used by the callsite with respect to the total number of samples
277/// collected in the caller.
278///
279/// If that fraction is larger than the default given by
280/// SampleProfileHotThreshold, the callsite will be inlined again.
281bool callsiteIsHot(const FunctionSamples *CallerFS,
282 const FunctionSamples *CallsiteFS) {
283 if (!CallsiteFS)
284 return false; // The callsite was not inlined in the original binary.
285
286 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
287 if (ParentTotalSamples == 0)
288 return false; // Avoid division by zero.
289
290 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
291 if (CallsiteTotalSamples == 0)
292 return false; // Callsite is trivially cold.
293
Diego Novillob5792402015-11-27 23:14:49 +0000294 double PercentSamples =
295 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000296 return PercentSamples >= SampleProfileHotThreshold;
297}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000298}
299
300/// Mark as used the sample record for the given function samples at
301/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000302///
303/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000304bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000305 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000306 uint32_t Discriminator,
307 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000308 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000309 unsigned &Count = SampleCoverage[FS][Loc];
310 bool FirstTime = (++Count == 1);
311 if (FirstTime)
312 TotalUsedSamples += Samples;
313 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000314}
315
316/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000317///
318/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000319unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000320SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
321 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000322
Diego Novillo243ea6a2015-11-23 20:12:21 +0000323 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000324 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000325 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000326
327 // If there are inlined callsites in this function, count the samples found
328 // in the respective bodies. However, do not bother counting callees with 0
329 // total samples, these are callees that were never invoked at runtime.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000330 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000331 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000332 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000333 Count += countUsedRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000334 }
335
Diego Novillof9ed08e2015-10-31 21:53:58 +0000336 return Count;
337}
338
339/// Return the number of sample records in the body of this profile.
340///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000341/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000342unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000343SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
344 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000345
Diego Novillo0b6985a2015-11-24 22:38:37 +0000346 // Only count records in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000347 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000348 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000349 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000350 Count += countBodyRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000351 }
352
Diego Novillof9ed08e2015-10-31 21:53:58 +0000353 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000354}
355
Diego Novillo243ea6a2015-11-23 20:12:21 +0000356/// Return the number of samples collected in the body of this profile.
357///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000358/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000359uint64_t
360SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
361 uint64_t Total = 0;
362 for (const auto &I : FS->getBodySamples())
363 Total += I.second.getSamples();
364
Diego Novillo0b6985a2015-11-24 22:38:37 +0000365 // Only count samples in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000366 for (const auto &I : FS->getCallsiteSamples()) {
367 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000368 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000369 Total += countBodySamples(CalleeSamples);
370 }
371
372 return Total;
373}
374
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000375/// Return the fraction of sample records used in this profile.
376///
377/// The returned value is an unsigned integer in the range 0-100 indicating
378/// the percentage of sample records that were used while applying this
379/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000380unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
381 unsigned Total) const {
382 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000383 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000384 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000385}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000386
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000387/// Clear all the per-function data used to load samples and propagate weights.
388void SampleProfileLoader::clearFunctionData() {
389 BlockWeights.clear();
390 EdgeWeights.clear();
391 VisitedBlocks.clear();
392 VisitedEdges.clear();
393 EquivalenceClass.clear();
394 DT = nullptr;
395 PDT = nullptr;
396 LI = nullptr;
397 Predecessors.clear();
398 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000399 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000400}
401
Dehao Chen10042412015-10-21 01:22:27 +0000402/// \brief Returns the offset of lineno \p L to head_lineno \p H
403///
404/// \param L Lineno
405/// \param H Header lineno of the function
406///
407/// \returns offset to the header lineno. 16 bits are used to represent offset.
408/// We assume that a single function will not exceed 65535 LOC.
409unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
410 return (L - H) & 0xffff;
411}
412
Diego Novillo0accb3d2014-01-10 23:23:46 +0000413/// \brief Print the weight of edge \p E on stream \p OS.
414///
415/// \param OS Stream to emit the output to.
416/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000417void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000418 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
419 << "]: " << EdgeWeights[E] << "\n";
420}
421
422/// \brief Print the equivalence class of block \p BB on stream \p OS.
423///
424/// \param OS Stream to emit the output to.
425/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000426void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000427 const BasicBlock *BB) {
428 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000429 OS << "equivalence[" << BB->getName()
430 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
431}
432
433/// \brief Print the weight of block \p BB on stream \p OS.
434///
435/// \param OS Stream to emit the output to.
436/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000437void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
438 const BasicBlock *BB) const {
439 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000440 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000441 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000442}
443
Diego Novillo0accb3d2014-01-10 23:23:46 +0000444/// \brief Get the weight for an instruction.
445///
446/// The "weight" of an instruction \p Inst is the number of samples
447/// collected on that instruction at runtime. To retrieve it, we
448/// need to compute the line number of \p Inst relative to the start of its
449/// function. We use HeaderLineno to compute the offset. We then
450/// look up the samples collected for \p Inst using BodySamples.
451///
452/// \param Inst Instruction to query.
453///
Dehao Chen8e7df832015-09-29 18:28:15 +0000454/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000455ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000456SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000457 const DebugLoc &DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000458 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000459 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000460
Dehao Chen67226882015-09-30 00:42:46 +0000461 const FunctionSamples *FS = findFunctionSamples(Inst);
462 if (!FS)
463 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000464
Dehao Chena8bae822016-04-20 23:36:23 +0000465 // Ignore all dbg_value intrinsics.
466 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
467 if (II && II->getIntrinsicID() == Intrinsic::dbg_value)
468 return std::error_code();
469
Dehao Chen41dc5a62015-10-09 16:50:16 +0000470 const DILocation *DIL = DLoc;
471 unsigned Lineno = DLoc.getLine();
472 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000473
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000474 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
475 uint32_t Discriminator = DIL->getDiscriminator();
476 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
477 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000478 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000479 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000480 if (FirstMark) {
481 const Function *F = Inst.getParent()->getParent();
482 LLVMContext &Ctx = F->getContext();
Diego Novillodf544a02015-11-20 15:39:42 +0000483 emitOptimizationRemark(
484 Ctx, DEBUG_TYPE, *F, DLoc,
485 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
486 Twine(LineOffset) +
487 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000488 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000489 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
490 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
491 << DIL->getDiscriminator() << " - weight: " << R.get()
492 << ")\n");
Dehao Chena8bae822016-04-20 23:36:23 +0000493 } else {
494 // If a call instruction is inlined in profile, but not inlined here,
495 // it means that the inlined callsite has no sample, thus the call
496 // instruction should have 0 count.
497 const CallInst *CI = dyn_cast<CallInst>(&Inst);
498 if (CI && findCalleeFunctionSamples(*CI))
499 R = 0;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000500 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000501 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000502}
503
504/// \brief Compute the weight of a basic block.
505///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000506/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000507/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000508///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000509/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000510///
Dehao Chen8e7df832015-09-29 18:28:15 +0000511/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000512ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000513SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
Dehao Chen5d6d4842016-04-26 04:59:11 +0000514 DenseMap<uint64_t, uint64_t> CM;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000515 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000516 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen5d6d4842016-04-26 04:59:11 +0000517 if (R) CM[R.get()]++;
518 }
519 if (CM.size() == 0) return std::error_code();
520 uint64_t W = 0, C = 0;
521 for (const auto &C_W : CM) {
522 if (C_W.second == W) {
523 C = std::max(C, C_W.first);
524 } else if (C_W.second > W) {
525 C = C_W.first;
526 W = C_W.second;
Dehao Chen8e7df832015-09-29 18:28:15 +0000527 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000528 }
Dehao Chen5d6d4842016-04-26 04:59:11 +0000529 return C;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000530}
531
532/// \brief Compute and store the weights of every basic block.
533///
534/// This populates the BlockWeights map by computing
535/// the weights of every basic block in the CFG.
536///
537/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000538bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000539 bool Changed = false;
540 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000541 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000542 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000543 if (Weight) {
544 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000545 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000546 Changed = true;
547 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000548 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000549 }
550
551 return Changed;
552}
553
Dehao Chen67226882015-09-30 00:42:46 +0000554/// \brief Get the FunctionSamples for a call instruction.
555///
556/// The FunctionSamples of a call instruction \p Inst is the inlined
557/// instance in which that call instruction is calling to. It contains
558/// all samples that resides in the inlined instance. We first find the
559/// inlined instance in which the call instruction is from, then we
560/// traverse its children to find the callsite with the matching
561/// location and callee function name.
562///
563/// \param Inst Call instruction to query.
564///
565/// \returns The FunctionSamples pointer to the inlined instance.
566const FunctionSamples *
567SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
568 const DILocation *DIL = Inst.getDebugLoc();
569 if (!DIL) {
570 return nullptr;
571 }
572 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000573 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000574 return nullptr;
575
Dehao Chen67226882015-09-30 00:42:46 +0000576 const FunctionSamples *FS = findFunctionSamples(Inst);
577 if (FS == nullptr)
578 return nullptr;
579
Dehao Chen57d1dda2016-03-03 18:09:32 +0000580 return FS->findFunctionSamplesAt(LineLocation(
581 getOffset(DIL->getLine(), SP->getLine()), DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000582}
583
584/// \brief Get the FunctionSamples for an instruction.
585///
586/// The FunctionSamples of an instruction \p Inst is the inlined instance
587/// in which that instruction is coming from. We traverse the inline stack
588/// of that instruction, and match it with the tree nodes in the profile.
589///
590/// \param Inst Instruction to query.
591///
592/// \returns the FunctionSamples pointer to the inlined instance.
593const FunctionSamples *
594SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
Dehao Chen57d1dda2016-03-03 18:09:32 +0000595 SmallVector<LineLocation, 10> S;
Dehao Chen67226882015-09-30 00:42:46 +0000596 const DILocation *DIL = Inst.getDebugLoc();
597 if (!DIL) {
598 return Samples;
599 }
Dehao Chen21aefae2016-04-29 17:19:10 +0000600 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
Dehao Chen67226882015-09-30 00:42:46 +0000601 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000602 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000603 return nullptr;
Dehao Chen21aefae2016-04-29 17:19:10 +0000604 S.push_back(LineLocation(getOffset(DIL->getLine(), SP->getLine()),
605 DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000606 }
607 if (S.size() == 0)
608 return Samples;
609 const FunctionSamples *FS = Samples;
610 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
611 FS = FS->findFunctionSamplesAt(S[i]);
612 }
613 return FS;
614}
615
Diego Novillo84f06cc2015-11-27 23:14:51 +0000616/// \brief Emit an inline hint if \p F is globally hot or cold.
617///
618/// If \p F consumes a significant fraction of samples (indicated by
619/// SampleProfileGlobalHotThreshold), apply the InlineHint attribute for the
620/// inliner to consider the function hot.
621///
622/// If \p F consumes a small fraction of samples (indicated by
623/// SampleProfileGlobalColdThreshold), apply the Cold attribute for the inliner
624/// to consider the function cold.
625///
626/// FIXME - This setting of inline hints is sub-optimal. Instead of marking a
627/// function globally hot or cold, we should be annotating individual callsites.
628/// This is not currently possible, but work on the inliner will eventually
629/// provide this ability. See http://reviews.llvm.org/D15003 for details and
630/// discussion.
631///
632/// \returns True if either attribute was applied to \p F.
633bool SampleProfileLoader::emitInlineHints(Function &F) {
634 if (TotalCollectedSamples == 0)
635 return false;
636
637 uint64_t FunctionSamples = Samples->getTotalSamples();
638 double SamplesPercent =
639 (double)FunctionSamples / (double)TotalCollectedSamples * 100.0;
640
641 // If the function collected more samples than the hot threshold, mark
642 // it globally hot.
643 if (SamplesPercent >= SampleProfileGlobalHotThreshold) {
644 F.addFnAttr(llvm::Attribute::InlineHint);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000645 std::string Msg;
646 raw_string_ostream S(Msg);
647 S << "Applied inline hint to globally hot function '" << F.getName()
648 << "' with " << format("%.2f", SamplesPercent)
649 << "% of samples (threshold: "
650 << format("%.2f", SampleProfileGlobalHotThreshold.getValue()) << "%)";
651 S.flush();
652 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000653 return true;
654 }
655
656 // If the function collected fewer samples than the cold threshold, mark
657 // it globally cold.
658 if (SamplesPercent <= SampleProfileGlobalColdThreshold) {
659 F.addFnAttr(llvm::Attribute::Cold);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000660 std::string Msg;
661 raw_string_ostream S(Msg);
662 S << "Applied cold hint to globally cold function '" << F.getName()
663 << "' with " << format("%.2f", SamplesPercent)
664 << "% of samples (threshold: "
665 << format("%.2f", SampleProfileGlobalColdThreshold.getValue()) << "%)";
666 S.flush();
667 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000668 return true;
669 }
670
671 return false;
672}
673
Dehao Chen67226882015-09-30 00:42:46 +0000674/// \brief Iteratively inline hot callsites of a function.
675///
676/// Iteratively traverse all callsites of the function \p F, and find if
677/// the corresponding inlined instance exists and is hot in profile. If
678/// it is hot enough, inline the callsites and adds new callsites of the
679/// callee into the caller.
680///
681/// TODO: investigate the possibility of not invoking InlineFunction directly.
682///
683/// \param F function to perform iterative inlining.
684///
685/// \returns True if there is any inline happened.
686bool SampleProfileLoader::inlineHotFunctions(Function &F) {
687 bool Changed = false;
Diego Novillo7963ea12015-10-26 18:52:53 +0000688 LLVMContext &Ctx = F.getContext();
Dehao Chen67226882015-09-30 00:42:46 +0000689 while (true) {
690 bool LocalChanged = false;
691 SmallVector<CallInst *, 10> CIS;
692 for (auto &BB : F) {
693 for (auto &I : BB.getInstList()) {
694 CallInst *CI = dyn_cast<CallInst>(&I);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000695 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
696 CIS.push_back(CI);
Dehao Chen67226882015-09-30 00:42:46 +0000697 }
698 }
699 for (auto CI : CIS) {
700 InlineFunctionInfo IFI;
Diego Novillo7963ea12015-10-26 18:52:53 +0000701 Function *CalledFunction = CI->getCalledFunction();
702 DebugLoc DLoc = CI->getDebugLoc();
703 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
704 if (InlineFunction(CI, IFI)) {
Dehao Chen67226882015-09-30 00:42:46 +0000705 LocalChanged = true;
Diego Novillo7963ea12015-10-26 18:52:53 +0000706 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
707 Twine("inlined hot callee '") +
708 CalledFunction->getName() + "' with " +
709 Twine(NumSamples) + " samples into '" +
710 F.getName() + "'");
711 }
Dehao Chen67226882015-09-30 00:42:46 +0000712 }
713 if (LocalChanged) {
714 Changed = true;
715 } else {
716 break;
717 }
718 }
719 return Changed;
720}
721
Diego Novillo0accb3d2014-01-10 23:23:46 +0000722/// \brief Find equivalence classes for the given block.
723///
724/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000725/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000726/// descendants of \p BB1 in the dominator or post-dominator tree.
727///
728/// A block BB2 will be in the same equivalence class as \p BB1 if
729/// the following holds:
730///
731/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
732/// is a descendant of \p BB1 in the dominator tree, then BB2 should
733/// dominate BB1 in the post-dominator tree.
734///
735/// 2- Both BB2 and \p BB1 must be in the same loop.
736///
737/// For every block BB2 that meets those two requirements, we set BB2's
738/// equivalence class to \p BB1.
739///
740/// \param BB1 Block to check.
741/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
742/// \param DomTree Opposite dominator tree. If \p Descendants is filled
743/// with blocks from \p BB1's dominator tree, then
744/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000745void SampleProfileLoader::findEquivalencesFor(
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000746 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000747 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000748 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000749 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000750 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000751 bool IsDomParent = DomTree->dominates(BB2, BB1);
752 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000753 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
754 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000755
756 // If BB2 is heavier than BB1, make BB2 have the same weight
757 // as BB1.
758 //
759 // Note that we don't worry about the opposite situation here
760 // (when BB2 is lighter than BB1). We will deal with this
761 // during the propagation phase. Right now, we just want to
762 // make sure that BB1 has the largest weight of all the
763 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000764 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000765 }
766 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000767 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000768}
769
770/// \brief Find equivalence classes.
771///
772/// Since samples may be missing from blocks, we can fill in the gaps by setting
773/// the weights of all the blocks in the same equivalence class to the same
774/// weight. To compute the concept of equivalence, we use dominance and loop
775/// information. Two blocks B1 and B2 are in the same equivalence class if B1
776/// dominates B2, B2 post-dominates B1 and both are in the same loop.
777///
778/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000779void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000780 SmallVector<BasicBlock *, 8> DominatedBBs;
781 DEBUG(dbgs() << "\nBlock equivalence classes\n");
782 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000783 for (auto &BB : F) {
784 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000785
786 // Compute BB1's equivalence class once.
787 if (EquivalenceClass.count(BB1)) {
788 DEBUG(printBlockEquivalence(dbgs(), BB1));
789 continue;
790 }
791
792 // By default, blocks are in their own equivalence class.
793 EquivalenceClass[BB1] = BB1;
794
795 // Traverse all the blocks dominated by BB1. We are looking for
796 // every basic block BB2 such that:
797 //
798 // 1- BB1 dominates BB2.
799 // 2- BB2 post-dominates BB1.
800 // 3- BB1 and BB2 are in the same loop nest.
801 //
802 // If all those conditions hold, it means that BB2 is executed
803 // as many times as BB1, so they are placed in the same equivalence
804 // class by making BB2's equivalence class be BB1.
805 DominatedBBs.clear();
806 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000807 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000808
Diego Novillo0accb3d2014-01-10 23:23:46 +0000809 DEBUG(printBlockEquivalence(dbgs(), BB1));
810 }
811
812 // Assign weights to equivalence classes.
813 //
814 // All the basic blocks in the same equivalence class will execute
815 // the same number of times. Since we know that the head block in
816 // each equivalence class has the largest weight, assign that weight
817 // to all the blocks in that equivalence class.
818 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000819 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000820 const BasicBlock *BB = &BI;
821 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000822 if (BB != EquivBB)
823 BlockWeights[BB] = BlockWeights[EquivBB];
824 DEBUG(printBlockWeight(dbgs(), BB));
825 }
826}
827
828/// \brief Visit the given edge to decide if it has a valid weight.
829///
830/// If \p E has not been visited before, we copy to \p UnknownEdge
831/// and increment the count of unknown edges.
832///
833/// \param E Edge to visit.
834/// \param NumUnknownEdges Current number of unknown edges.
835/// \param UnknownEdge Set if E has not been visited before.
836///
837/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000838uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000839 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000840 if (!VisitedEdges.count(E)) {
841 (*NumUnknownEdges)++;
842 *UnknownEdge = E;
843 return 0;
844 }
845
846 return EdgeWeights[E];
847}
848
849/// \brief Propagate weights through incoming/outgoing edges.
850///
851/// If the weight of a basic block is known, and there is only one edge
852/// with an unknown weight, we can calculate the weight of that edge.
853///
854/// Similarly, if all the edges have a known count, we can calculate the
855/// count of the basic block, if needed.
856///
857/// \param F Function to process.
858///
859/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000860bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000861 bool Changed = false;
862 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000863 for (const auto &BI : F) {
864 const BasicBlock *BB = &BI;
865 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000866
867 // Visit all the predecessor and successor edges to determine
868 // which ones have a weight assigned already. Note that it doesn't
869 // matter that we only keep track of a single unknown edge. The
870 // only case we are interested in handling is when only a single
871 // edge is unknown (see setEdgeOrBlockWeight).
872 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000873 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000874 unsigned NumUnknownEdges = 0;
875 Edge UnknownEdge, SelfReferentialEdge;
876
877 if (i == 0) {
878 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000879 for (auto *Pred : Predecessors[BB]) {
880 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000881 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
882 if (E.first == E.second)
883 SelfReferentialEdge = E;
884 }
885 } else {
886 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000887 for (auto *Succ : Successors[BB]) {
888 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000889 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
890 }
891 }
892
893 // After visiting all the edges, there are three cases that we
894 // can handle immediately:
895 //
896 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
897 // In this case, we simply check that the sum of all the edges
898 // is the same as BB's weight. If not, we change BB's weight
899 // to match. Additionally, if BB had not been visited before,
900 // we mark it visited.
901 //
902 // - Only one edge is unknown and BB has already been visited.
903 // In this case, we can compute the weight of the edge by
904 // subtracting the total block weight from all the known
905 // edge weights. If the edges weight more than BB, then the
906 // edge of the last remaining edge is set to zero.
907 //
908 // - There exists a self-referential edge and the weight of BB is
909 // known. In this case, this edge can be based on BB's weight.
910 // We add up all the other known edges and set the weight on
911 // the self-referential edge as we did in the previous case.
912 //
913 // In any other case, we must continue iterating. Eventually,
914 // all edges will get a weight, or iteration will stop when
915 // it reaches SampleProfileMaxPropagateIterations.
916 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000917 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000918 if (NumUnknownEdges == 0) {
919 // If we already know the weight of all edges, the weight of the
920 // basic block can be computed. It should be no larger than the sum
921 // of all edge weights.
922 if (TotalWeight > BBWeight) {
923 BBWeight = TotalWeight;
924 Changed = true;
925 DEBUG(dbgs() << "All edge weights for " << BB->getName()
926 << " known. Set weight for block: ";
927 printBlockWeight(dbgs(), BB););
928 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000929 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000930 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000931 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000932 // If there is a single unknown edge and the block has been
933 // visited, then we can compute E's weight.
934 if (BBWeight >= TotalWeight)
935 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
936 else
937 EdgeWeights[UnknownEdge] = 0;
938 VisitedEdges.insert(UnknownEdge);
939 Changed = true;
940 DEBUG(dbgs() << "Set weight for edge: ";
941 printEdgeWeight(dbgs(), UnknownEdge));
942 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000943 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000944 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000945 // We have a self-referential edge and the weight of BB is known.
946 if (BBWeight >= TotalWeight)
947 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
948 else
949 EdgeWeights[SelfReferentialEdge] = 0;
950 VisitedEdges.insert(SelfReferentialEdge);
951 Changed = true;
952 DEBUG(dbgs() << "Set self-referential edge weight to: ";
953 printEdgeWeight(dbgs(), SelfReferentialEdge));
954 }
955 }
956 }
957
958 return Changed;
959}
960
961/// \brief Build in/out edge lists for each basic block in the CFG.
962///
963/// We are interested in unique edges. If a block B1 has multiple
964/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000965void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000966 for (auto &BI : F) {
967 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000968
969 // Add predecessors for B1.
970 SmallPtrSet<BasicBlock *, 16> Visited;
971 if (!Predecessors[B1].empty())
972 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000973 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
974 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000975 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000976 Predecessors[B1].push_back(B2);
977 }
978
979 // Add successors for B1.
980 Visited.clear();
981 if (!Successors[B1].empty())
982 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000983 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
984 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000985 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000986 Successors[B1].push_back(B2);
987 }
988 }
989}
990
991/// \brief Propagate weights into edges
992///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000993/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000994///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000995/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000996/// of that edge is the weight of the block.
997///
998/// - If all incoming or outgoing edges are known except one, and the
999/// weight of the block is already known, the weight of the unknown
1000/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001001/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001002/// we set the unknown edge weight to zero.
1003///
1004/// - If there is a self-referential edge, and the weight of the block is
1005/// known, the weight for that edge is set to the weight of the block
1006/// minus the weight of the other incoming edges to that block (if
1007/// known).
Diego Novillode1ab262014-09-09 12:40:50 +00001008void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001009 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +00001010 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001011
Diego Novilloffc84e32015-05-13 17:04:29 +00001012 // Add an entry count to the function using the samples gathered
1013 // at the function entry.
1014 F.setEntryCount(Samples->getHeadSamples());
1015
Diego Novillo0accb3d2014-01-10 23:23:46 +00001016 // Before propagation starts, build, for each block, a list of
1017 // unique predecessors and successors. This is necessary to handle
1018 // identical edges in multiway branches. Since we visit all blocks and all
1019 // edges of the CFG, it is cleaner to build these lists once at the start
1020 // of the pass.
1021 buildEdges(F);
1022
1023 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +00001024 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001025 Changed = propagateThroughEdges(F);
1026 }
1027
1028 // Generate MD_prof metadata for every branch instruction using the
1029 // edge weights computed during propagation.
1030 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +00001031 LLVMContext &Ctx = F.getContext();
1032 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001033 for (auto &BI : F) {
1034 BasicBlock *BB = &BI;
1035 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001036 if (TI->getNumSuccessors() == 1)
1037 continue;
1038 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1039 continue;
1040
1041 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +00001042 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +00001043 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +00001044 uint32_t MaxWeight = 0;
Diego Novillo7963ea12015-10-26 18:52:53 +00001045 DebugLoc MaxDestLoc;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001046 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1047 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001048 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +00001049 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001050 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +00001051 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1052 // if needed. Sample counts in profiles are 64-bit unsigned values,
1053 // but internally branch weights are expressed as 32-bit values.
1054 if (Weight > std::numeric_limits<uint32_t>::max()) {
1055 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1056 Weight = std::numeric_limits<uint32_t>::max();
1057 }
1058 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo7963ea12015-10-26 18:52:53 +00001059 if (Weight != 0) {
1060 if (Weight > MaxWeight) {
1061 MaxWeight = Weight;
Diego Novillo7963ea12015-10-26 18:52:53 +00001062 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1063 }
1064 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001065 }
1066
1067 // Only set weights if there is at least one non-zero weight.
1068 // In any other case, let the analyzer set weights.
Diego Novillo7963ea12015-10-26 18:52:53 +00001069 if (MaxWeight > 0) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001070 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1071 TI->setMetadata(llvm::LLVMContext::MD_prof,
1072 MDB.createBranchWeights(Weights));
Diego Novillo7963ea12015-10-26 18:52:53 +00001073 DebugLoc BranchLoc = TI->getDebugLoc();
1074 emitOptimizationRemark(
1075 Ctx, DEBUG_TYPE, F, MaxDestLoc,
1076 Twine("most popular destination for conditional branches at ") +
Diego Novilloc04270d2015-10-27 17:37:00 +00001077 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1078 Twine(BranchLoc.getLine()) + ":" +
1079 Twine(BranchLoc.getCol()))
1080 : Twine("<UNKNOWN LOCATION>")));
Diego Novillo0accb3d2014-01-10 23:23:46 +00001081 } else {
1082 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1083 }
1084 }
1085}
1086
1087/// \brief Get the line number for the function header.
1088///
1089/// This looks up function \p F in the current compilation unit and
1090/// retrieves the line number where the function is defined. This is
1091/// line 0 for all the samples read from the profile file. Every line
1092/// number is relative to this line.
1093///
1094/// \param F Function object to query.
1095///
Diego Novilloa32aa322014-03-14 21:58:59 +00001096/// \returns the line number where \p F is defined. If it returns 0,
1097/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001098unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Pete Cooperadebb932016-03-11 02:14:16 +00001099 if (DISubprogram *S = F.getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001100 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001101
Diego Novilloaa555072015-10-27 18:41:46 +00001102 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001103 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001104 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001105 "No debug information found in function " + F.getName() +
1106 ": Function profile not used",
1107 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001108 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001109}
1110
Diego Novillo7732ae42015-08-26 20:00:27 +00001111void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1112 DT.reset(new DominatorTree);
1113 DT->recalculate(F);
1114
1115 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1116 PDT->recalculate(F);
1117
1118 LI.reset(new LoopInfo);
1119 LI->analyze(*DT);
1120}
1121
Diego Novillo0accb3d2014-01-10 23:23:46 +00001122/// \brief Generate branch weight metadata for all branches in \p F.
1123///
1124/// Branch weights are computed out of instruction samples using a
1125/// propagation heuristic. Propagation proceeds in 3 phases:
1126///
1127/// 1- Assignment of block weights. All the basic blocks in the function
1128/// are initial assigned the same weight as their most frequently
1129/// executed instruction.
1130///
1131/// 2- Creation of equivalence classes. Since samples may be missing from
1132/// blocks, we can fill in the gaps by setting the weights of all the
1133/// blocks in the same equivalence class to the same weight. To compute
1134/// the concept of equivalence, we use dominance and loop information.
1135/// Two blocks B1 and B2 are in the same equivalence class if B1
1136/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1137///
1138/// 3- Propagation of block weights into edges. This uses a simple
1139/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001140/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001141///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001142/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001143/// of that edge is the weight of the block.
1144///
1145/// - If all the edges are known except one, and the weight of the
1146/// block is already known, the weight of the unknown edge will
1147/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001148/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001149/// we set the unknown edge weight to zero.
1150///
1151/// - If there is a self-referential edge, and the weight of the block is
1152/// known, the weight for that edge is set to the weight of the block
1153/// minus the weight of the other incoming edges to that block (if
1154/// known).
1155///
1156/// Since this propagation is not guaranteed to finalize for every CFG, we
1157/// only allow it to proceed for a limited number of iterations (controlled
1158/// by -sample-profile-max-propagate-iterations).
1159///
1160/// FIXME: Try to replace this propagation heuristic with a scheme
1161/// that is guaranteed to finalize. A work-list approach similar to
1162/// the standard value propagation algorithm used by SSA-CCP might
1163/// work here.
1164///
1165/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001166/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001167///
1168/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001169///
1170/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001171bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001172 bool Changed = false;
1173
Dehao Chen41dc5a62015-10-09 16:50:16 +00001174 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001175 return false;
1176
Diego Novillo0accb3d2014-01-10 23:23:46 +00001177 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001178 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001179
Diego Novillo84f06cc2015-11-27 23:14:51 +00001180 Changed |= emitInlineHints(F);
1181
Dehao Chen67226882015-09-30 00:42:46 +00001182 Changed |= inlineHotFunctions(F);
1183
Diego Novillo0accb3d2014-01-10 23:23:46 +00001184 // Compute basic block weights.
1185 Changed |= computeBlockWeights(F);
1186
1187 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001188 // Compute dominance and loop info needed for propagation.
1189 computeDominanceAndLoopInfo(F);
1190
Diego Novillo0accb3d2014-01-10 23:23:46 +00001191 // Find equivalence classes.
1192 findEquivalenceClasses(F);
1193
1194 // Propagate weights to all edges.
1195 propagateWeights(F);
1196 }
1197
Diego Novillof9ed08e2015-10-31 21:53:58 +00001198 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001199 if (SampleProfileRecordCoverage) {
1200 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1201 unsigned Total = CoverageTracker.countBodyRecords(Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001202 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001203 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001204 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001205 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001206 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1207 Twine(Coverage) + "%) were applied",
1208 DS_Warning));
1209 }
1210 }
1211
Diego Novillo243ea6a2015-11-23 20:12:21 +00001212 if (SampleProfileSampleCoverage) {
1213 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1214 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1215 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1216 if (Coverage < SampleProfileSampleCoverage) {
1217 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001218 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillo243ea6a2015-11-23 20:12:21 +00001219 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1220 Twine(Coverage) + "%) were applied",
1221 DS_Warning));
1222 }
1223 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001224 return Changed;
1225}
1226
Xinliang David Lie897edb2016-05-27 22:30:44 +00001227char SampleProfileLoaderLegacyPass::ID = 0;
1228INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
Diego Novillo0accb3d2014-01-10 23:23:46 +00001229 "Sample Profile loader", false, false)
Xinliang David Lie897edb2016-05-27 22:30:44 +00001230INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
Diego Novillo0accb3d2014-01-10 23:23:46 +00001231 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001232
1233bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001234 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001235 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001236 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001237 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001238 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001239 return false;
1240 }
Diego Novillofcd55602014-11-03 00:51:45 +00001241 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001242 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001243 return true;
1244}
1245
Diego Novillo4d711132015-08-25 15:25:11 +00001246ModulePass *llvm::createSampleProfileLoaderPass() {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001247 return new SampleProfileLoaderLegacyPass(SampleProfileFile);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001248}
1249
Diego Novillo4d711132015-08-25 15:25:11 +00001250ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001251 return new SampleProfileLoaderLegacyPass(Name);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001252}
1253
Diego Novillo4d711132015-08-25 15:25:11 +00001254bool SampleProfileLoader::runOnModule(Module &M) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001255 if (!ProfileIsValid)
1256 return false;
1257
Diego Novillo84f06cc2015-11-27 23:14:51 +00001258 // Compute the total number of samples collected in this profile.
1259 for (const auto &I : Reader->getProfiles())
1260 TotalCollectedSamples += I.second.getTotalSamples();
1261
Diego Novillo4d711132015-08-25 15:25:11 +00001262 bool retval = false;
1263 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001264 if (!F.isDeclaration()) {
1265 clearFunctionData();
Diego Novillo4d711132015-08-25 15:25:11 +00001266 retval |= runOnFunction(F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001267 }
Diego Novillo4d711132015-08-25 15:25:11 +00001268 return retval;
1269}
1270
Xinliang David Lie897edb2016-05-27 22:30:44 +00001271bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1272 return SampleLoader.runOnModule(M);
1273}
1274
Diego Novillo8d6568b2013-11-13 12:22:21 +00001275bool SampleProfileLoader::runOnFunction(Function &F) {
Dehao Chen6c73b492016-02-22 22:46:21 +00001276 F.setEntryCount(0);
Diego Novillode1ab262014-09-09 12:40:50 +00001277 Samples = Reader->getSamplesFor(F);
1278 if (!Samples->empty())
1279 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001280 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001281}