blob: 69194eac078557ba9f61f8b43a5e4b692b552443 [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"
Diego Novillo8d6568b2013-11-13 12:22:21 +000037#include "llvm/IR/Instructions.h"
38#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000039#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000040#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000041#include "llvm/IR/Module.h"
42#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000043#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000046#include "llvm/Support/ErrorOr.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000047#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000048#include "llvm/Transforms/IPO.h"
Dehao Chen67226882015-09-30 00:42:46 +000049#include "llvm/Transforms/Utils/Cloning.h"
Logan Chien61c6df02014-02-22 06:34:10 +000050#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000051
52using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000053using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "sample-profile"
56
Diego Novillo8d6568b2013-11-13 12:22:21 +000057// Command line option to specify the file to read samples from. This is
58// mainly used for debugging.
59static 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);
Diego Novillo0accb3d2014-01-10 23:23:46 +000062static 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."));
Diego Novillo243ea6a2015-11-23 20:12:21 +000066static 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."));
70static cl::opt<unsigned> SampleProfileSampleCoverage(
71 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +000072 cl::desc("Emit a warning if less than N% of samples in the input profile "
73 "are matched to the IR."));
Diego Novillob5792402015-11-27 23:14:49 +000074static cl::opt<double> SampleProfileHotThreshold(
75 "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
Diego Novillo0b6985a2015-11-24 22:38:37 +000076 cl::desc("Inlined functions that account for more than N% of all samples "
77 "collected in the parent function, will be inlined again."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000078
79namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000080typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000081typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
82typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000083typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000084typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
85 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000086
Diego Novillode1ab262014-09-09 12:40:50 +000087/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000088///
Diego Novillode1ab262014-09-09 12:40:50 +000089/// This pass reads profile data from the file specified by
90/// -sample-profile-file and annotates every affected function with the
91/// profile information found in that file.
Diego Novillo4d711132015-08-25 15:25:11 +000092class SampleProfileLoader : public ModulePass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000093public:
Diego Novillode1ab262014-09-09 12:40:50 +000094 // Class identification, replacement for typeinfo
95 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000096
Diego Novillode1ab262014-09-09 12:40:50 +000097 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novillo7732ae42015-08-26 20:00:27 +000098 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
99 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
Diego Novillode1ab262014-09-09 12:40:50 +0000100 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
101 }
102
103 bool doInitialization(Module &M) override;
104
105 void dump() { Reader->dump(); }
106
107 const char *getPassName() const override { return "Sample profile pass"; }
108
Diego Novillo4d711132015-08-25 15:25:11 +0000109 bool runOnModule(Module &M) override;
Diego Novillode1ab262014-09-09 12:40:50 +0000110
111 void getAnalysisUsage(AnalysisUsage &AU) const override {
112 AU.setPreservesCFG();
Diego Novillode1ab262014-09-09 12:40:50 +0000113 }
114
115protected:
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 Novillo0accb3d2014-01-10 23:23:46 +0000124 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000125 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
126 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000127 bool computeBlockWeights(Function &F);
128 void findEquivalenceClasses(Function &F);
129 void findEquivalencesFor(BasicBlock *BB1,
130 SmallVector<BasicBlock *, 8> Descendants,
131 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.
Dehao Chen8e7df832015-09-29 18:28:15 +0000153 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000154
155 /// \brief Set of visited edges during propagation.
156 SmallSet<Edge, 128> VisitedEdges;
157
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 Novillo8d6568b2013-11-13 12:22:21 +0000188};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000189
190class SampleCoverageTracker {
191public:
Diego Novillo243ea6a2015-11-23 20:12:21 +0000192 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000193
Diego Novillo243ea6a2015-11-23 20:12:21 +0000194 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
195 uint32_t Discriminator, uint64_t Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +0000196 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000197 unsigned countUsedRecords(const FunctionSamples *FS) const;
198 unsigned countBodyRecords(const FunctionSamples *FS) const;
199 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
200 uint64_t countBodySamples(const FunctionSamples *FS) const;
201 void clear() {
202 SampleCoverage.clear();
203 TotalUsedSamples = 0;
204 }
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000205
206private:
207 typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
208 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
209 FunctionSamplesCoverageMap;
210
211 /// Coverage map for sampling records.
212 ///
213 /// This map keeps a record of sampling records that have been matched to
214 /// an IR instruction. This is used to detect some form of staleness in
215 /// profiles (see flag -sample-profile-check-coverage).
216 ///
217 /// Each entry in the map corresponds to a FunctionSamples instance. This is
218 /// another map that counts how many times the sample record at the
219 /// given location has been used.
220 FunctionSamplesCoverageMap SampleCoverage;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000221
222 /// Number of samples used from the profile.
223 ///
224 /// When a sampling record is used for the first time, the samples from
225 /// that record are added to this accumulator. Coverage is later computed
226 /// based on the total number of samples available in this function and
227 /// its callsites.
228 ///
229 /// Note that this accumulator tracks samples used from a single function
230 /// and all the inlined callsites. Strictly, we should have a map of counters
231 /// keyed by FunctionSamples pointers, but these stats are cleared after
232 /// every function, so we just need to keep a single counter.
233 uint64_t TotalUsedSamples;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000234};
235
236SampleCoverageTracker CoverageTracker;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000237
238/// Return true if the given callsite is hot wrt to its caller.
239///
240/// Functions that were inlined in the original binary will be represented
241/// in the inline stack in the sample profile. If the profile shows that
242/// the original inline decision was "good" (i.e., the callsite is executed
243/// frequently), then we will recreate the inline decision and apply the
244/// profile from the inlined callsite.
245///
246/// To decide whether an inlined callsite is hot, we compute the fraction
247/// of samples used by the callsite with respect to the total number of samples
248/// collected in the caller.
249///
250/// If that fraction is larger than the default given by
251/// SampleProfileHotThreshold, the callsite will be inlined again.
252bool callsiteIsHot(const FunctionSamples *CallerFS,
253 const FunctionSamples *CallsiteFS) {
254 if (!CallsiteFS)
255 return false; // The callsite was not inlined in the original binary.
256
257 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
258 if (ParentTotalSamples == 0)
259 return false; // Avoid division by zero.
260
261 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
262 if (CallsiteTotalSamples == 0)
263 return false; // Callsite is trivially cold.
264
Diego Novillob5792402015-11-27 23:14:49 +0000265 double PercentSamples =
266 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000267 return PercentSamples >= SampleProfileHotThreshold;
268}
269
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000270}
271
272/// Mark as used the sample record for the given function samples at
273/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000274///
275/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000276bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000277 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000278 uint32_t Discriminator,
279 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000280 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000281 unsigned &Count = SampleCoverage[FS][Loc];
282 bool FirstTime = (++Count == 1);
283 if (FirstTime)
284 TotalUsedSamples += Samples;
285 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000286}
287
288/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000289///
290/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000291unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000292SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
293 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000294
Diego Novillo243ea6a2015-11-23 20:12:21 +0000295 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000296 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000297 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000298
299 // If there are inlined callsites in this function, count the samples found
300 // in the respective bodies. However, do not bother counting callees with 0
301 // total samples, these are callees that were never invoked at runtime.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000302 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000303 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000304 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000305 Count += countUsedRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000306 }
307
Diego Novillof9ed08e2015-10-31 21:53:58 +0000308 return Count;
309}
310
311/// Return the number of sample records in the body of this profile.
312///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000313/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000314unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000315SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
316 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000317
Diego Novillo0b6985a2015-11-24 22:38:37 +0000318 // Only count records in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000319 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000320 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000321 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000322 Count += countBodyRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000323 }
324
Diego Novillof9ed08e2015-10-31 21:53:58 +0000325 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000326}
327
Diego Novillo243ea6a2015-11-23 20:12:21 +0000328/// Return the number of samples collected in the body of this profile.
329///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000330/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000331uint64_t
332SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
333 uint64_t Total = 0;
334 for (const auto &I : FS->getBodySamples())
335 Total += I.second.getSamples();
336
Diego Novillo0b6985a2015-11-24 22:38:37 +0000337 // Only count samples in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000338 for (const auto &I : FS->getCallsiteSamples()) {
339 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000340 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000341 Total += countBodySamples(CalleeSamples);
342 }
343
344 return Total;
345}
346
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000347/// Return the fraction of sample records used in this profile.
348///
349/// The returned value is an unsigned integer in the range 0-100 indicating
350/// the percentage of sample records that were used while applying this
351/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000352unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
353 unsigned Total) const {
354 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000355 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000356 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000357}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000358
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000359/// Clear all the per-function data used to load samples and propagate weights.
360void SampleProfileLoader::clearFunctionData() {
361 BlockWeights.clear();
362 EdgeWeights.clear();
363 VisitedBlocks.clear();
364 VisitedEdges.clear();
365 EquivalenceClass.clear();
366 DT = nullptr;
367 PDT = nullptr;
368 LI = nullptr;
369 Predecessors.clear();
370 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000371 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000372}
373
Dehao Chen10042412015-10-21 01:22:27 +0000374/// \brief Returns the offset of lineno \p L to head_lineno \p H
375///
376/// \param L Lineno
377/// \param H Header lineno of the function
378///
379/// \returns offset to the header lineno. 16 bits are used to represent offset.
380/// We assume that a single function will not exceed 65535 LOC.
381unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
382 return (L - H) & 0xffff;
383}
384
Diego Novillo0accb3d2014-01-10 23:23:46 +0000385/// \brief Print the weight of edge \p E on stream \p OS.
386///
387/// \param OS Stream to emit the output to.
388/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000389void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000390 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
391 << "]: " << EdgeWeights[E] << "\n";
392}
393
394/// \brief Print the equivalence class of block \p BB on stream \p OS.
395///
396/// \param OS Stream to emit the output to.
397/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000398void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000399 const BasicBlock *BB) {
400 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000401 OS << "equivalence[" << BB->getName()
402 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
403}
404
405/// \brief Print the weight of block \p BB on stream \p OS.
406///
407/// \param OS Stream to emit the output to.
408/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000409void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
410 const BasicBlock *BB) const {
411 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000412 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000413 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000414}
415
Diego Novillo0accb3d2014-01-10 23:23:46 +0000416/// \brief Get the weight for an instruction.
417///
418/// The "weight" of an instruction \p Inst is the number of samples
419/// collected on that instruction at runtime. To retrieve it, we
420/// need to compute the line number of \p Inst relative to the start of its
421/// function. We use HeaderLineno to compute the offset. We then
422/// look up the samples collected for \p Inst using BodySamples.
423///
424/// \param Inst Instruction to query.
425///
Dehao Chen8e7df832015-09-29 18:28:15 +0000426/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000427ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000428SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000429 DebugLoc DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000430 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000431 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000432
Dehao Chen67226882015-09-30 00:42:46 +0000433 const FunctionSamples *FS = findFunctionSamples(Inst);
434 if (!FS)
435 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000436
437 const DILocation *DIL = DLoc;
438 unsigned Lineno = DLoc.getLine();
439 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000440
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000441 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
442 uint32_t Discriminator = DIL->getDiscriminator();
443 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
444 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000445 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000446 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000447 if (FirstMark) {
448 const Function *F = Inst.getParent()->getParent();
449 LLVMContext &Ctx = F->getContext();
Diego Novillodf544a02015-11-20 15:39:42 +0000450 emitOptimizationRemark(
451 Ctx, DEBUG_TYPE, *F, DLoc,
452 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
453 Twine(LineOffset) +
454 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000455 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000456 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
457 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
458 << DIL->getDiscriminator() << " - weight: " << R.get()
459 << ")\n");
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000460 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000461 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000462}
463
464/// \brief Compute the weight of a basic block.
465///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000466/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000467/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000468///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000469/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000470///
Dehao Chen8e7df832015-09-29 18:28:15 +0000471/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000472ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000473SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
474 bool Found = false;
Diego Novillo38be3332015-10-15 16:36:21 +0000475 uint64_t Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000476 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000477 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen8e7df832015-09-29 18:28:15 +0000478 if (R && R.get() >= Weight) {
479 Weight = R.get();
480 Found = true;
481 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000482 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000483 if (Found)
484 return Weight;
485 else
486 return std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000487}
488
489/// \brief Compute and store the weights of every basic block.
490///
491/// This populates the BlockWeights map by computing
492/// the weights of every basic block in the CFG.
493///
494/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000495bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000496 bool Changed = false;
497 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000498 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000499 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000500 if (Weight) {
501 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000502 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000503 Changed = true;
504 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000505 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000506 }
507
508 return Changed;
509}
510
Dehao Chen67226882015-09-30 00:42:46 +0000511/// \brief Get the FunctionSamples for a call instruction.
512///
513/// The FunctionSamples of a call instruction \p Inst is the inlined
514/// instance in which that call instruction is calling to. It contains
515/// all samples that resides in the inlined instance. We first find the
516/// inlined instance in which the call instruction is from, then we
517/// traverse its children to find the callsite with the matching
518/// location and callee function name.
519///
520/// \param Inst Call instruction to query.
521///
522/// \returns The FunctionSamples pointer to the inlined instance.
523const FunctionSamples *
524SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
525 const DILocation *DIL = Inst.getDebugLoc();
526 if (!DIL) {
527 return nullptr;
528 }
529 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000530 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000531 return nullptr;
532
533 Function *CalleeFunc = Inst.getCalledFunction();
534 if (!CalleeFunc) {
535 return nullptr;
536 }
537
538 StringRef CalleeName = CalleeFunc->getName();
539 const FunctionSamples *FS = findFunctionSamples(Inst);
540 if (FS == nullptr)
541 return nullptr;
542
Dehao Chen10042412015-10-21 01:22:27 +0000543 return FS->findFunctionSamplesAt(
544 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
545 DIL->getDiscriminator(), CalleeName));
Dehao Chen67226882015-09-30 00:42:46 +0000546}
547
548/// \brief Get the FunctionSamples for an instruction.
549///
550/// The FunctionSamples of an instruction \p Inst is the inlined instance
551/// in which that instruction is coming from. We traverse the inline stack
552/// of that instruction, and match it with the tree nodes in the profile.
553///
554/// \param Inst Instruction to query.
555///
556/// \returns the FunctionSamples pointer to the inlined instance.
557const FunctionSamples *
558SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
559 SmallVector<CallsiteLocation, 10> S;
560 const DILocation *DIL = Inst.getDebugLoc();
561 if (!DIL) {
562 return Samples;
563 }
564 StringRef CalleeName;
565 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
566 DIL = DIL->getInlinedAt()) {
567 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000568 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000569 return nullptr;
570 if (!CalleeName.empty()) {
Dehao Chen10042412015-10-21 01:22:27 +0000571 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
Dehao Chen67226882015-09-30 00:42:46 +0000572 DIL->getDiscriminator(), CalleeName));
573 }
574 CalleeName = SP->getLinkageName();
575 }
576 if (S.size() == 0)
577 return Samples;
578 const FunctionSamples *FS = Samples;
579 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
580 FS = FS->findFunctionSamplesAt(S[i]);
581 }
582 return FS;
583}
584
585/// \brief Iteratively inline hot callsites of a function.
586///
587/// Iteratively traverse all callsites of the function \p F, and find if
588/// the corresponding inlined instance exists and is hot in profile. If
589/// it is hot enough, inline the callsites and adds new callsites of the
590/// callee into the caller.
591///
592/// TODO: investigate the possibility of not invoking InlineFunction directly.
593///
594/// \param F function to perform iterative inlining.
595///
596/// \returns True if there is any inline happened.
597bool SampleProfileLoader::inlineHotFunctions(Function &F) {
598 bool Changed = false;
Diego Novillo7963ea12015-10-26 18:52:53 +0000599 LLVMContext &Ctx = F.getContext();
Dehao Chen67226882015-09-30 00:42:46 +0000600 while (true) {
601 bool LocalChanged = false;
602 SmallVector<CallInst *, 10> CIS;
603 for (auto &BB : F) {
604 for (auto &I : BB.getInstList()) {
605 CallInst *CI = dyn_cast<CallInst>(&I);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000606 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
607 CIS.push_back(CI);
Dehao Chen67226882015-09-30 00:42:46 +0000608 }
609 }
610 for (auto CI : CIS) {
611 InlineFunctionInfo IFI;
Diego Novillo7963ea12015-10-26 18:52:53 +0000612 Function *CalledFunction = CI->getCalledFunction();
613 DebugLoc DLoc = CI->getDebugLoc();
614 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
615 if (InlineFunction(CI, IFI)) {
Dehao Chen67226882015-09-30 00:42:46 +0000616 LocalChanged = true;
Diego Novillo7963ea12015-10-26 18:52:53 +0000617 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
618 Twine("inlined hot callee '") +
619 CalledFunction->getName() + "' with " +
620 Twine(NumSamples) + " samples into '" +
621 F.getName() + "'");
622 }
Dehao Chen67226882015-09-30 00:42:46 +0000623 }
624 if (LocalChanged) {
625 Changed = true;
626 } else {
627 break;
628 }
629 }
630 return Changed;
631}
632
Diego Novillo0accb3d2014-01-10 23:23:46 +0000633/// \brief Find equivalence classes for the given block.
634///
635/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000636/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000637/// descendants of \p BB1 in the dominator or post-dominator tree.
638///
639/// A block BB2 will be in the same equivalence class as \p BB1 if
640/// the following holds:
641///
642/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
643/// is a descendant of \p BB1 in the dominator tree, then BB2 should
644/// dominate BB1 in the post-dominator tree.
645///
646/// 2- Both BB2 and \p BB1 must be in the same loop.
647///
648/// For every block BB2 that meets those two requirements, we set BB2's
649/// equivalence class to \p BB1.
650///
651/// \param BB1 Block to check.
652/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
653/// \param DomTree Opposite dominator tree. If \p Descendants is filled
654/// with blocks from \p BB1's dominator tree, then
655/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000656void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000657 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
658 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000659 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000660 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000661 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000662 bool IsDomParent = DomTree->dominates(BB2, BB1);
663 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000664 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
665 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000666
667 // If BB2 is heavier than BB1, make BB2 have the same weight
668 // as BB1.
669 //
670 // Note that we don't worry about the opposite situation here
671 // (when BB2 is lighter than BB1). We will deal with this
672 // during the propagation phase. Right now, we just want to
673 // make sure that BB1 has the largest weight of all the
674 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000675 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000676 }
677 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000678 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000679}
680
681/// \brief Find equivalence classes.
682///
683/// Since samples may be missing from blocks, we can fill in the gaps by setting
684/// the weights of all the blocks in the same equivalence class to the same
685/// weight. To compute the concept of equivalence, we use dominance and loop
686/// information. Two blocks B1 and B2 are in the same equivalence class if B1
687/// dominates B2, B2 post-dominates B1 and both are in the same loop.
688///
689/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000690void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000691 SmallVector<BasicBlock *, 8> DominatedBBs;
692 DEBUG(dbgs() << "\nBlock equivalence classes\n");
693 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000694 for (auto &BB : F) {
695 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000696
697 // Compute BB1's equivalence class once.
698 if (EquivalenceClass.count(BB1)) {
699 DEBUG(printBlockEquivalence(dbgs(), BB1));
700 continue;
701 }
702
703 // By default, blocks are in their own equivalence class.
704 EquivalenceClass[BB1] = BB1;
705
706 // Traverse all the blocks dominated by BB1. We are looking for
707 // every basic block BB2 such that:
708 //
709 // 1- BB1 dominates BB2.
710 // 2- BB2 post-dominates BB1.
711 // 3- BB1 and BB2 are in the same loop nest.
712 //
713 // If all those conditions hold, it means that BB2 is executed
714 // as many times as BB1, so they are placed in the same equivalence
715 // class by making BB2's equivalence class be BB1.
716 DominatedBBs.clear();
717 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000718 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000719
Diego Novillo0accb3d2014-01-10 23:23:46 +0000720 DEBUG(printBlockEquivalence(dbgs(), BB1));
721 }
722
723 // Assign weights to equivalence classes.
724 //
725 // All the basic blocks in the same equivalence class will execute
726 // the same number of times. Since we know that the head block in
727 // each equivalence class has the largest weight, assign that weight
728 // to all the blocks in that equivalence class.
729 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000730 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000731 const BasicBlock *BB = &BI;
732 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000733 if (BB != EquivBB)
734 BlockWeights[BB] = BlockWeights[EquivBB];
735 DEBUG(printBlockWeight(dbgs(), BB));
736 }
737}
738
739/// \brief Visit the given edge to decide if it has a valid weight.
740///
741/// If \p E has not been visited before, we copy to \p UnknownEdge
742/// and increment the count of unknown edges.
743///
744/// \param E Edge to visit.
745/// \param NumUnknownEdges Current number of unknown edges.
746/// \param UnknownEdge Set if E has not been visited before.
747///
748/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000749uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000750 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000751 if (!VisitedEdges.count(E)) {
752 (*NumUnknownEdges)++;
753 *UnknownEdge = E;
754 return 0;
755 }
756
757 return EdgeWeights[E];
758}
759
760/// \brief Propagate weights through incoming/outgoing edges.
761///
762/// If the weight of a basic block is known, and there is only one edge
763/// with an unknown weight, we can calculate the weight of that edge.
764///
765/// Similarly, if all the edges have a known count, we can calculate the
766/// count of the basic block, if needed.
767///
768/// \param F Function to process.
769///
770/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000771bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000772 bool Changed = false;
773 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000774 for (const auto &BI : F) {
775 const BasicBlock *BB = &BI;
776 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000777
778 // Visit all the predecessor and successor edges to determine
779 // which ones have a weight assigned already. Note that it doesn't
780 // matter that we only keep track of a single unknown edge. The
781 // only case we are interested in handling is when only a single
782 // edge is unknown (see setEdgeOrBlockWeight).
783 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000784 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000785 unsigned NumUnknownEdges = 0;
786 Edge UnknownEdge, SelfReferentialEdge;
787
788 if (i == 0) {
789 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000790 for (auto *Pred : Predecessors[BB]) {
791 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000792 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
793 if (E.first == E.second)
794 SelfReferentialEdge = E;
795 }
796 } else {
797 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000798 for (auto *Succ : Successors[BB]) {
799 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000800 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
801 }
802 }
803
804 // After visiting all the edges, there are three cases that we
805 // can handle immediately:
806 //
807 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
808 // In this case, we simply check that the sum of all the edges
809 // is the same as BB's weight. If not, we change BB's weight
810 // to match. Additionally, if BB had not been visited before,
811 // we mark it visited.
812 //
813 // - Only one edge is unknown and BB has already been visited.
814 // In this case, we can compute the weight of the edge by
815 // subtracting the total block weight from all the known
816 // edge weights. If the edges weight more than BB, then the
817 // edge of the last remaining edge is set to zero.
818 //
819 // - There exists a self-referential edge and the weight of BB is
820 // known. In this case, this edge can be based on BB's weight.
821 // We add up all the other known edges and set the weight on
822 // the self-referential edge as we did in the previous case.
823 //
824 // In any other case, we must continue iterating. Eventually,
825 // all edges will get a weight, or iteration will stop when
826 // it reaches SampleProfileMaxPropagateIterations.
827 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000828 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000829 if (NumUnknownEdges == 0) {
830 // If we already know the weight of all edges, the weight of the
831 // basic block can be computed. It should be no larger than the sum
832 // of all edge weights.
833 if (TotalWeight > BBWeight) {
834 BBWeight = TotalWeight;
835 Changed = true;
836 DEBUG(dbgs() << "All edge weights for " << BB->getName()
837 << " known. Set weight for block: ";
838 printBlockWeight(dbgs(), BB););
839 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000840 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000841 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000842 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000843 // If there is a single unknown edge and the block has been
844 // visited, then we can compute E's weight.
845 if (BBWeight >= TotalWeight)
846 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
847 else
848 EdgeWeights[UnknownEdge] = 0;
849 VisitedEdges.insert(UnknownEdge);
850 Changed = true;
851 DEBUG(dbgs() << "Set weight for edge: ";
852 printEdgeWeight(dbgs(), UnknownEdge));
853 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000854 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000855 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000856 // We have a self-referential edge and the weight of BB is known.
857 if (BBWeight >= TotalWeight)
858 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
859 else
860 EdgeWeights[SelfReferentialEdge] = 0;
861 VisitedEdges.insert(SelfReferentialEdge);
862 Changed = true;
863 DEBUG(dbgs() << "Set self-referential edge weight to: ";
864 printEdgeWeight(dbgs(), SelfReferentialEdge));
865 }
866 }
867 }
868
869 return Changed;
870}
871
872/// \brief Build in/out edge lists for each basic block in the CFG.
873///
874/// We are interested in unique edges. If a block B1 has multiple
875/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000876void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000877 for (auto &BI : F) {
878 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000879
880 // Add predecessors for B1.
881 SmallPtrSet<BasicBlock *, 16> Visited;
882 if (!Predecessors[B1].empty())
883 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000884 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
885 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000886 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000887 Predecessors[B1].push_back(B2);
888 }
889
890 // Add successors for B1.
891 Visited.clear();
892 if (!Successors[B1].empty())
893 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000894 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
895 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000896 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000897 Successors[B1].push_back(B2);
898 }
899 }
900}
901
902/// \brief Propagate weights into edges
903///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000904/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000905///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000906/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000907/// of that edge is the weight of the block.
908///
909/// - If all incoming or outgoing edges are known except one, and the
910/// weight of the block is already known, the weight of the unknown
911/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000912/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000913/// we set the unknown edge weight to zero.
914///
915/// - If there is a self-referential edge, and the weight of the block is
916/// known, the weight for that edge is set to the weight of the block
917/// minus the weight of the other incoming edges to that block (if
918/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000919void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000920 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +0000921 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000922
Diego Novilloffc84e32015-05-13 17:04:29 +0000923 // Add an entry count to the function using the samples gathered
924 // at the function entry.
925 F.setEntryCount(Samples->getHeadSamples());
926
Diego Novillo0accb3d2014-01-10 23:23:46 +0000927 // Before propagation starts, build, for each block, a list of
928 // unique predecessors and successors. This is necessary to handle
929 // identical edges in multiway branches. Since we visit all blocks and all
930 // edges of the CFG, it is cleaner to build these lists once at the start
931 // of the pass.
932 buildEdges(F);
933
934 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +0000935 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000936 Changed = propagateThroughEdges(F);
937 }
938
939 // Generate MD_prof metadata for every branch instruction using the
940 // edge weights computed during propagation.
941 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +0000942 LLVMContext &Ctx = F.getContext();
943 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000944 for (auto &BI : F) {
945 BasicBlock *BB = &BI;
946 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000947 if (TI->getNumSuccessors() == 1)
948 continue;
949 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
950 continue;
951
952 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000953 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +0000954 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +0000955 uint32_t MaxWeight = 0;
Diego Novillo7963ea12015-10-26 18:52:53 +0000956 DebugLoc MaxDestLoc;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000957 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
958 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000959 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +0000960 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000961 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +0000962 // Use uint32_t saturated arithmetic to adjust the incoming weights,
963 // if needed. Sample counts in profiles are 64-bit unsigned values,
964 // but internally branch weights are expressed as 32-bit values.
965 if (Weight > std::numeric_limits<uint32_t>::max()) {
966 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
967 Weight = std::numeric_limits<uint32_t>::max();
968 }
969 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo7963ea12015-10-26 18:52:53 +0000970 if (Weight != 0) {
971 if (Weight > MaxWeight) {
972 MaxWeight = Weight;
Diego Novillo7963ea12015-10-26 18:52:53 +0000973 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
974 }
975 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000976 }
977
978 // Only set weights if there is at least one non-zero weight.
979 // In any other case, let the analyzer set weights.
Diego Novillo7963ea12015-10-26 18:52:53 +0000980 if (MaxWeight > 0) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000981 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
982 TI->setMetadata(llvm::LLVMContext::MD_prof,
983 MDB.createBranchWeights(Weights));
Diego Novillo7963ea12015-10-26 18:52:53 +0000984 DebugLoc BranchLoc = TI->getDebugLoc();
985 emitOptimizationRemark(
986 Ctx, DEBUG_TYPE, F, MaxDestLoc,
987 Twine("most popular destination for conditional branches at ") +
Diego Novilloc04270d2015-10-27 17:37:00 +0000988 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
989 Twine(BranchLoc.getLine()) + ":" +
990 Twine(BranchLoc.getCol()))
991 : Twine("<UNKNOWN LOCATION>")));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000992 } else {
993 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
994 }
995 }
996}
997
998/// \brief Get the line number for the function header.
999///
1000/// This looks up function \p F in the current compilation unit and
1001/// retrieves the line number where the function is defined. This is
1002/// line 0 for all the samples read from the profile file. Every line
1003/// number is relative to this line.
1004///
1005/// \param F Function object to query.
1006///
Diego Novilloa32aa322014-03-14 21:58:59 +00001007/// \returns the line number where \p F is defined. If it returns 0,
1008/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001009unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001010 if (DISubprogram *S = getDISubprogram(&F))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001011 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001012
Diego Novilloaa555072015-10-27 18:41:46 +00001013 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001014 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001015 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001016 "No debug information found in function " + F.getName() +
1017 ": Function profile not used",
1018 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001019 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001020}
1021
Diego Novillo7732ae42015-08-26 20:00:27 +00001022void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1023 DT.reset(new DominatorTree);
1024 DT->recalculate(F);
1025
1026 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1027 PDT->recalculate(F);
1028
1029 LI.reset(new LoopInfo);
1030 LI->analyze(*DT);
1031}
1032
Diego Novillo0accb3d2014-01-10 23:23:46 +00001033/// \brief Generate branch weight metadata for all branches in \p F.
1034///
1035/// Branch weights are computed out of instruction samples using a
1036/// propagation heuristic. Propagation proceeds in 3 phases:
1037///
1038/// 1- Assignment of block weights. All the basic blocks in the function
1039/// are initial assigned the same weight as their most frequently
1040/// executed instruction.
1041///
1042/// 2- Creation of equivalence classes. Since samples may be missing from
1043/// blocks, we can fill in the gaps by setting the weights of all the
1044/// blocks in the same equivalence class to the same weight. To compute
1045/// the concept of equivalence, we use dominance and loop information.
1046/// Two blocks B1 and B2 are in the same equivalence class if B1
1047/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1048///
1049/// 3- Propagation of block weights into edges. This uses a simple
1050/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001051/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001052///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001053/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001054/// of that edge is the weight of the block.
1055///
1056/// - If all the edges are known except one, and the weight of the
1057/// block is already known, the weight of the unknown edge will
1058/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001059/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001060/// we set the unknown edge weight to zero.
1061///
1062/// - If there is a self-referential edge, and the weight of the block is
1063/// known, the weight for that edge is set to the weight of the block
1064/// minus the weight of the other incoming edges to that block (if
1065/// known).
1066///
1067/// Since this propagation is not guaranteed to finalize for every CFG, we
1068/// only allow it to proceed for a limited number of iterations (controlled
1069/// by -sample-profile-max-propagate-iterations).
1070///
1071/// FIXME: Try to replace this propagation heuristic with a scheme
1072/// that is guaranteed to finalize. A work-list approach similar to
1073/// the standard value propagation algorithm used by SSA-CCP might
1074/// work here.
1075///
1076/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001077/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001078///
1079/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001080///
1081/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001082bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001083 bool Changed = false;
1084
Dehao Chen41dc5a62015-10-09 16:50:16 +00001085 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001086 return false;
1087
Diego Novillo0accb3d2014-01-10 23:23:46 +00001088 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001089 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001090
Dehao Chen67226882015-09-30 00:42:46 +00001091 Changed |= inlineHotFunctions(F);
1092
Diego Novillo0accb3d2014-01-10 23:23:46 +00001093 // Compute basic block weights.
1094 Changed |= computeBlockWeights(F);
1095
1096 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001097 // Compute dominance and loop info needed for propagation.
1098 computeDominanceAndLoopInfo(F);
1099
Diego Novillo0accb3d2014-01-10 23:23:46 +00001100 // Find equivalence classes.
1101 findEquivalenceClasses(F);
1102
1103 // Propagate weights to all edges.
1104 propagateWeights(F);
1105 }
1106
Diego Novillof9ed08e2015-10-31 21:53:58 +00001107 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001108 if (SampleProfileRecordCoverage) {
1109 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1110 unsigned Total = CoverageTracker.countBodyRecords(Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001111 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001112 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001113 F.getContext().diagnose(DiagnosticInfoSampleProfile(
David Blaikie2297a912015-11-02 20:01:13 +00001114 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001115 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1116 Twine(Coverage) + "%) were applied",
1117 DS_Warning));
1118 }
1119 }
1120
Diego Novillo243ea6a2015-11-23 20:12:21 +00001121 if (SampleProfileSampleCoverage) {
1122 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1123 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1124 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1125 if (Coverage < SampleProfileSampleCoverage) {
1126 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1127 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1128 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1129 Twine(Coverage) + "%) were applied",
1130 DS_Warning));
1131 }
1132 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001133 return Changed;
1134}
1135
Diego Novilloc0dd1032013-11-26 20:37:33 +00001136char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001137INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1138 "Sample Profile loader", false, false)
Diego Novillo92aa8c22014-03-10 22:41:28 +00001139INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001140INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1141 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001142
1143bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001144 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001145 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001146 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001147 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001148 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001149 return false;
1150 }
Diego Novillofcd55602014-11-03 00:51:45 +00001151 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001152 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001153 return true;
1154}
1155
Diego Novillo4d711132015-08-25 15:25:11 +00001156ModulePass *llvm::createSampleProfileLoaderPass() {
Diego Novilloc0dd1032013-11-26 20:37:33 +00001157 return new SampleProfileLoader(SampleProfileFile);
1158}
1159
Diego Novillo4d711132015-08-25 15:25:11 +00001160ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Diego Novilloc0dd1032013-11-26 20:37:33 +00001161 return new SampleProfileLoader(Name);
1162}
1163
Diego Novillo4d711132015-08-25 15:25:11 +00001164bool SampleProfileLoader::runOnModule(Module &M) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001165 if (!ProfileIsValid)
1166 return false;
1167
Diego Novillo4d711132015-08-25 15:25:11 +00001168 bool retval = false;
1169 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001170 if (!F.isDeclaration()) {
1171 clearFunctionData();
Diego Novillo4d711132015-08-25 15:25:11 +00001172 retval |= runOnFunction(F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001173 }
Diego Novillo4d711132015-08-25 15:25:11 +00001174 return retval;
1175}
1176
Diego Novillo8d6568b2013-11-13 12:22:21 +00001177bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novillode1ab262014-09-09 12:40:50 +00001178 Samples = Reader->getSamplesFor(F);
1179 if (!Samples->empty())
1180 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001181 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001182}