blob: de4170692fe0a098b775da6e4f21e969abd90972 [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 Novillo748b3ffe2015-10-28 22:30:25 +000066static cl::opt<unsigned> SampleProfileCoverage(
67 "sample-profile-check-coverage", cl::init(0), cl::value_desc("N"),
68 cl::desc("Emit a warning if less than N% of samples in the input profile "
69 "are matched to the IR."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000070
71namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000072typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000073typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
74typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000075typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000076typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
77 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000078
Diego Novillode1ab262014-09-09 12:40:50 +000079/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000080///
Diego Novillode1ab262014-09-09 12:40:50 +000081/// This pass reads profile data from the file specified by
82/// -sample-profile-file and annotates every affected function with the
83/// profile information found in that file.
Diego Novillo4d711132015-08-25 15:25:11 +000084class SampleProfileLoader : public ModulePass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000085public:
Diego Novillode1ab262014-09-09 12:40:50 +000086 // Class identification, replacement for typeinfo
87 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000088
Diego Novillode1ab262014-09-09 12:40:50 +000089 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novillo7732ae42015-08-26 20:00:27 +000090 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
91 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
Diego Novillode1ab262014-09-09 12:40:50 +000092 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
93 }
94
95 bool doInitialization(Module &M) override;
96
97 void dump() { Reader->dump(); }
98
99 const char *getPassName() const override { return "Sample profile pass"; }
100
Diego Novillo4d711132015-08-25 15:25:11 +0000101 bool runOnModule(Module &M) override;
Diego Novillode1ab262014-09-09 12:40:50 +0000102
103 void getAnalysisUsage(AnalysisUsage &AU) const override {
104 AU.setPreservesCFG();
Diego Novillode1ab262014-09-09 12:40:50 +0000105 }
106
107protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000108 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000109 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000110 bool emitAnnotations(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000111 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
112 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
Dehao Chen67226882015-09-30 00:42:46 +0000113 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
114 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
115 bool inlineHotFunctions(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000116 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000117 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
118 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000119 bool computeBlockWeights(Function &F);
120 void findEquivalenceClasses(Function &F);
121 void findEquivalencesFor(BasicBlock *BB1,
122 SmallVector<BasicBlock *, 8> Descendants,
123 DominatorTreeBase<BasicBlock> *DomTree);
124 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000125 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000126 void buildEdges(Function &F);
127 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000128 void computeDominanceAndLoopInfo(Function &F);
Dehao Chen10042412015-10-21 01:22:27 +0000129 unsigned getOffset(unsigned L, unsigned H) const;
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000130 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000131
Diego Novilloc0dd1032013-11-26 20:37:33 +0000132 /// \brief Map basic blocks to their computed weights.
133 ///
134 /// The weight of a basic block is defined to be the maximum
135 /// of all the instruction weights in that block.
136 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000137
138 /// \brief Map edges to their computed weights.
139 ///
140 /// Edge weights are computed by propagating basic block weights in
141 /// SampleProfile::propagateWeights.
142 EdgeWeightMap EdgeWeights;
143
144 /// \brief Set of visited blocks during propagation.
Dehao Chen8e7df832015-09-29 18:28:15 +0000145 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000146
147 /// \brief Set of visited edges during propagation.
148 SmallSet<Edge, 128> VisitedEdges;
149
150 /// \brief Equivalence classes for block weights.
151 ///
152 /// Two blocks BB1 and BB2 are in the same equivalence class if they
153 /// dominate and post-dominate each other, and they are in the same loop
154 /// nest. When this happens, the two blocks are guaranteed to execute
155 /// the same number of times.
156 EquivalenceClassMap EquivalenceClass;
157
158 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000159 std::unique_ptr<DominatorTree> DT;
160 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
161 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000162
163 /// \brief Predecessors for each basic block in the CFG.
164 BlockEdgeMap Predecessors;
165
166 /// \brief Successors for each basic block in the CFG.
167 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000168
Diego Novillo8d6568b2013-11-13 12:22:21 +0000169 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000170 std::unique_ptr<SampleProfileReader> Reader;
171
172 /// \brief Samples collected for the body of this function.
173 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000174
175 /// \brief Name of the profile file to load.
176 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000177
Alp Toker16f98b22014-04-09 14:47:27 +0000178 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000179 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000180};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000181
182class SampleCoverageTracker {
183public:
184 SampleCoverageTracker() : SampleCoverage() {}
185
Diego Novillof9ed08e2015-10-31 21:53:58 +0000186 bool markSamplesUsed(const FunctionSamples *Samples, uint32_t LineOffset,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000187 uint32_t Discriminator);
Diego Novillof9ed08e2015-10-31 21:53:58 +0000188 unsigned computeCoverage(unsigned Used, unsigned Total) const;
189 unsigned countUsedSamples(const FunctionSamples *Samples) const;
190 unsigned countBodySamples(const FunctionSamples *Samples) const;
Diego Novillo1ca881c2015-11-23 16:30:17 +0000191 void clear() { SampleCoverage.clear(); }
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000192
193private:
194 typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
195 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
196 FunctionSamplesCoverageMap;
197
198 /// Coverage map for sampling records.
199 ///
200 /// This map keeps a record of sampling records that have been matched to
201 /// an IR instruction. This is used to detect some form of staleness in
202 /// profiles (see flag -sample-profile-check-coverage).
203 ///
204 /// Each entry in the map corresponds to a FunctionSamples instance. This is
205 /// another map that counts how many times the sample record at the
206 /// given location has been used.
207 FunctionSamplesCoverageMap SampleCoverage;
208};
209
210SampleCoverageTracker CoverageTracker;
211}
212
213/// Mark as used the sample record for the given function samples at
214/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000215///
216/// \returns true if this is the first time we mark the given record.
217bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *Samples,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000218 uint32_t LineOffset,
219 uint32_t Discriminator) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000220 LineLocation Loc(LineOffset, Discriminator);
221 unsigned &Count = SampleCoverage[Samples][Loc];
222 return ++Count == 1;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000223}
224
225/// Return the number of sample records that were applied from this profile.
226unsigned
Diego Novillof9ed08e2015-10-31 21:53:58 +0000227SampleCoverageTracker::countUsedSamples(const FunctionSamples *Samples) const {
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000228 auto I = SampleCoverage.find(Samples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000229
230 // The size of the coverage map for Samples represents the number of records
231 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000232 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000233
234 // If there are inlined callsites in this function, count the samples found
235 // in the respective bodies. However, do not bother counting callees with 0
236 // total samples, these are callees that were never invoked at runtime.
237 for (const auto &I : Samples->getCallsiteSamples()) {
238 const FunctionSamples *CalleeSamples = &I.second;
239 if (CalleeSamples->getTotalSamples() > 0)
Diego Novillo39ab68f2015-11-23 15:24:13 +0000240 Count += countUsedSamples(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000241 }
242
Diego Novillof9ed08e2015-10-31 21:53:58 +0000243 return Count;
244}
245
246/// Return the number of sample records in the body of this profile.
247///
Diego Novillo5fb49e52015-11-20 21:46:38 +0000248/// The count includes all the samples in inlined callees. However, callsites
249/// with 0 samples indicate inlined function calls that were never actually
250/// invoked at runtime. Ignore these callsites for coverage purposes.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000251unsigned
252SampleCoverageTracker::countBodySamples(const FunctionSamples *Samples) const {
253 unsigned Count = Samples->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000254
255 // Count all the callsites with non-zero samples.
256 for (const auto &I : Samples->getCallsiteSamples()) {
257 const FunctionSamples *CalleeSamples = &I.second;
258 if (CalleeSamples->getTotalSamples() > 0)
Diego Novillo39ab68f2015-11-23 15:24:13 +0000259 Count += countBodySamples(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000260 }
261
Diego Novillof9ed08e2015-10-31 21:53:58 +0000262 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000263}
264
265/// Return the fraction of sample records used in this profile.
266///
267/// The returned value is an unsigned integer in the range 0-100 indicating
268/// the percentage of sample records that were used while applying this
269/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000270unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
271 unsigned Total) const {
272 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000273 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000274 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000275}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000276
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000277/// Clear all the per-function data used to load samples and propagate weights.
278void SampleProfileLoader::clearFunctionData() {
279 BlockWeights.clear();
280 EdgeWeights.clear();
281 VisitedBlocks.clear();
282 VisitedEdges.clear();
283 EquivalenceClass.clear();
284 DT = nullptr;
285 PDT = nullptr;
286 LI = nullptr;
287 Predecessors.clear();
288 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000289 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000290}
291
Dehao Chen10042412015-10-21 01:22:27 +0000292/// \brief Returns the offset of lineno \p L to head_lineno \p H
293///
294/// \param L Lineno
295/// \param H Header lineno of the function
296///
297/// \returns offset to the header lineno. 16 bits are used to represent offset.
298/// We assume that a single function will not exceed 65535 LOC.
299unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
300 return (L - H) & 0xffff;
301}
302
Diego Novillo0accb3d2014-01-10 23:23:46 +0000303/// \brief Print the weight of edge \p E on stream \p OS.
304///
305/// \param OS Stream to emit the output to.
306/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000307void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000308 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
309 << "]: " << EdgeWeights[E] << "\n";
310}
311
312/// \brief Print the equivalence class of block \p BB on stream \p OS.
313///
314/// \param OS Stream to emit the output to.
315/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000316void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000317 const BasicBlock *BB) {
318 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000319 OS << "equivalence[" << BB->getName()
320 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
321}
322
323/// \brief Print the weight of block \p BB on stream \p OS.
324///
325/// \param OS Stream to emit the output to.
326/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000327void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
328 const BasicBlock *BB) const {
329 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000330 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000331 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000332}
333
Diego Novillo0accb3d2014-01-10 23:23:46 +0000334/// \brief Get the weight for an instruction.
335///
336/// The "weight" of an instruction \p Inst is the number of samples
337/// collected on that instruction at runtime. To retrieve it, we
338/// need to compute the line number of \p Inst relative to the start of its
339/// function. We use HeaderLineno to compute the offset. We then
340/// look up the samples collected for \p Inst using BodySamples.
341///
342/// \param Inst Instruction to query.
343///
Dehao Chen8e7df832015-09-29 18:28:15 +0000344/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000345ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000346SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000347 DebugLoc DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000348 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000349 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000350
Dehao Chen67226882015-09-30 00:42:46 +0000351 const FunctionSamples *FS = findFunctionSamples(Inst);
352 if (!FS)
353 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000354
355 const DILocation *DIL = DLoc;
356 unsigned Lineno = DLoc.getLine();
357 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000358
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000359 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
360 uint32_t Discriminator = DIL->getDiscriminator();
361 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
362 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000363 bool FirstMark =
364 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator);
365 if (FirstMark) {
366 const Function *F = Inst.getParent()->getParent();
367 LLVMContext &Ctx = F->getContext();
Diego Novillodf544a02015-11-20 15:39:42 +0000368 emitOptimizationRemark(
369 Ctx, DEBUG_TYPE, *F, DLoc,
370 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
371 Twine(LineOffset) +
372 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000373 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000374 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
375 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
376 << DIL->getDiscriminator() << " - weight: " << R.get()
377 << ")\n");
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000378 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000379 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000380}
381
382/// \brief Compute the weight of a basic block.
383///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000384/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000385/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000386///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000387/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000388///
Dehao Chen8e7df832015-09-29 18:28:15 +0000389/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000390ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000391SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
392 bool Found = false;
Diego Novillo38be3332015-10-15 16:36:21 +0000393 uint64_t Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000394 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000395 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen8e7df832015-09-29 18:28:15 +0000396 if (R && R.get() >= Weight) {
397 Weight = R.get();
398 Found = true;
399 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000400 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000401 if (Found)
402 return Weight;
403 else
404 return std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000405}
406
407/// \brief Compute and store the weights of every basic block.
408///
409/// This populates the BlockWeights map by computing
410/// the weights of every basic block in the CFG.
411///
412/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000413bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000414 bool Changed = false;
415 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000416 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000417 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000418 if (Weight) {
419 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000420 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000421 Changed = true;
422 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000423 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000424 }
425
426 return Changed;
427}
428
Dehao Chen67226882015-09-30 00:42:46 +0000429/// \brief Get the FunctionSamples for a call instruction.
430///
431/// The FunctionSamples of a call instruction \p Inst is the inlined
432/// instance in which that call instruction is calling to. It contains
433/// all samples that resides in the inlined instance. We first find the
434/// inlined instance in which the call instruction is from, then we
435/// traverse its children to find the callsite with the matching
436/// location and callee function name.
437///
438/// \param Inst Call instruction to query.
439///
440/// \returns The FunctionSamples pointer to the inlined instance.
441const FunctionSamples *
442SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
443 const DILocation *DIL = Inst.getDebugLoc();
444 if (!DIL) {
445 return nullptr;
446 }
447 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000448 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000449 return nullptr;
450
451 Function *CalleeFunc = Inst.getCalledFunction();
452 if (!CalleeFunc) {
453 return nullptr;
454 }
455
456 StringRef CalleeName = CalleeFunc->getName();
457 const FunctionSamples *FS = findFunctionSamples(Inst);
458 if (FS == nullptr)
459 return nullptr;
460
Dehao Chen10042412015-10-21 01:22:27 +0000461 return FS->findFunctionSamplesAt(
462 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
463 DIL->getDiscriminator(), CalleeName));
Dehao Chen67226882015-09-30 00:42:46 +0000464}
465
466/// \brief Get the FunctionSamples for an instruction.
467///
468/// The FunctionSamples of an instruction \p Inst is the inlined instance
469/// in which that instruction is coming from. We traverse the inline stack
470/// of that instruction, and match it with the tree nodes in the profile.
471///
472/// \param Inst Instruction to query.
473///
474/// \returns the FunctionSamples pointer to the inlined instance.
475const FunctionSamples *
476SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
477 SmallVector<CallsiteLocation, 10> S;
478 const DILocation *DIL = Inst.getDebugLoc();
479 if (!DIL) {
480 return Samples;
481 }
482 StringRef CalleeName;
483 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
484 DIL = DIL->getInlinedAt()) {
485 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000486 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000487 return nullptr;
488 if (!CalleeName.empty()) {
Dehao Chen10042412015-10-21 01:22:27 +0000489 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
Dehao Chen67226882015-09-30 00:42:46 +0000490 DIL->getDiscriminator(), CalleeName));
491 }
492 CalleeName = SP->getLinkageName();
493 }
494 if (S.size() == 0)
495 return Samples;
496 const FunctionSamples *FS = Samples;
497 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
498 FS = FS->findFunctionSamplesAt(S[i]);
499 }
500 return FS;
501}
502
503/// \brief Iteratively inline hot callsites of a function.
504///
505/// Iteratively traverse all callsites of the function \p F, and find if
506/// the corresponding inlined instance exists and is hot in profile. If
507/// it is hot enough, inline the callsites and adds new callsites of the
508/// callee into the caller.
509///
510/// TODO: investigate the possibility of not invoking InlineFunction directly.
511///
512/// \param F function to perform iterative inlining.
513///
514/// \returns True if there is any inline happened.
515bool SampleProfileLoader::inlineHotFunctions(Function &F) {
516 bool Changed = false;
Diego Novillo7963ea12015-10-26 18:52:53 +0000517 LLVMContext &Ctx = F.getContext();
Dehao Chen67226882015-09-30 00:42:46 +0000518 while (true) {
519 bool LocalChanged = false;
520 SmallVector<CallInst *, 10> CIS;
521 for (auto &BB : F) {
522 for (auto &I : BB.getInstList()) {
523 CallInst *CI = dyn_cast<CallInst>(&I);
524 if (CI) {
525 const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
526 if (FS && FS->getTotalSamples() > 0) {
527 CIS.push_back(CI);
528 }
529 }
530 }
531 }
532 for (auto CI : CIS) {
533 InlineFunctionInfo IFI;
Diego Novillo7963ea12015-10-26 18:52:53 +0000534 Function *CalledFunction = CI->getCalledFunction();
535 DebugLoc DLoc = CI->getDebugLoc();
536 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
537 if (InlineFunction(CI, IFI)) {
Dehao Chen67226882015-09-30 00:42:46 +0000538 LocalChanged = true;
Diego Novillo7963ea12015-10-26 18:52:53 +0000539 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
540 Twine("inlined hot callee '") +
541 CalledFunction->getName() + "' with " +
542 Twine(NumSamples) + " samples into '" +
543 F.getName() + "'");
544 }
Dehao Chen67226882015-09-30 00:42:46 +0000545 }
546 if (LocalChanged) {
547 Changed = true;
548 } else {
549 break;
550 }
551 }
552 return Changed;
553}
554
Diego Novillo0accb3d2014-01-10 23:23:46 +0000555/// \brief Find equivalence classes for the given block.
556///
557/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000558/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000559/// descendants of \p BB1 in the dominator or post-dominator tree.
560///
561/// A block BB2 will be in the same equivalence class as \p BB1 if
562/// the following holds:
563///
564/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
565/// is a descendant of \p BB1 in the dominator tree, then BB2 should
566/// dominate BB1 in the post-dominator tree.
567///
568/// 2- Both BB2 and \p BB1 must be in the same loop.
569///
570/// For every block BB2 that meets those two requirements, we set BB2's
571/// equivalence class to \p BB1.
572///
573/// \param BB1 Block to check.
574/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
575/// \param DomTree Opposite dominator tree. If \p Descendants is filled
576/// with blocks from \p BB1's dominator tree, then
577/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000578void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000579 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
580 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000581 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000582 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000583 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000584 bool IsDomParent = DomTree->dominates(BB2, BB1);
585 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000586 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
587 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000588
589 // If BB2 is heavier than BB1, make BB2 have the same weight
590 // as BB1.
591 //
592 // Note that we don't worry about the opposite situation here
593 // (when BB2 is lighter than BB1). We will deal with this
594 // during the propagation phase. Right now, we just want to
595 // make sure that BB1 has the largest weight of all the
596 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000597 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000598 }
599 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000600 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000601}
602
603/// \brief Find equivalence classes.
604///
605/// Since samples may be missing from blocks, we can fill in the gaps by setting
606/// the weights of all the blocks in the same equivalence class to the same
607/// weight. To compute the concept of equivalence, we use dominance and loop
608/// information. Two blocks B1 and B2 are in the same equivalence class if B1
609/// dominates B2, B2 post-dominates B1 and both are in the same loop.
610///
611/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000612void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000613 SmallVector<BasicBlock *, 8> DominatedBBs;
614 DEBUG(dbgs() << "\nBlock equivalence classes\n");
615 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000616 for (auto &BB : F) {
617 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000618
619 // Compute BB1's equivalence class once.
620 if (EquivalenceClass.count(BB1)) {
621 DEBUG(printBlockEquivalence(dbgs(), BB1));
622 continue;
623 }
624
625 // By default, blocks are in their own equivalence class.
626 EquivalenceClass[BB1] = BB1;
627
628 // Traverse all the blocks dominated by BB1. We are looking for
629 // every basic block BB2 such that:
630 //
631 // 1- BB1 dominates BB2.
632 // 2- BB2 post-dominates BB1.
633 // 3- BB1 and BB2 are in the same loop nest.
634 //
635 // If all those conditions hold, it means that BB2 is executed
636 // as many times as BB1, so they are placed in the same equivalence
637 // class by making BB2's equivalence class be BB1.
638 DominatedBBs.clear();
639 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000640 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000641
Diego Novillo0accb3d2014-01-10 23:23:46 +0000642 DEBUG(printBlockEquivalence(dbgs(), BB1));
643 }
644
645 // Assign weights to equivalence classes.
646 //
647 // All the basic blocks in the same equivalence class will execute
648 // the same number of times. Since we know that the head block in
649 // each equivalence class has the largest weight, assign that weight
650 // to all the blocks in that equivalence class.
651 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000652 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000653 const BasicBlock *BB = &BI;
654 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000655 if (BB != EquivBB)
656 BlockWeights[BB] = BlockWeights[EquivBB];
657 DEBUG(printBlockWeight(dbgs(), BB));
658 }
659}
660
661/// \brief Visit the given edge to decide if it has a valid weight.
662///
663/// If \p E has not been visited before, we copy to \p UnknownEdge
664/// and increment the count of unknown edges.
665///
666/// \param E Edge to visit.
667/// \param NumUnknownEdges Current number of unknown edges.
668/// \param UnknownEdge Set if E has not been visited before.
669///
670/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000671uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000672 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000673 if (!VisitedEdges.count(E)) {
674 (*NumUnknownEdges)++;
675 *UnknownEdge = E;
676 return 0;
677 }
678
679 return EdgeWeights[E];
680}
681
682/// \brief Propagate weights through incoming/outgoing edges.
683///
684/// If the weight of a basic block is known, and there is only one edge
685/// with an unknown weight, we can calculate the weight of that edge.
686///
687/// Similarly, if all the edges have a known count, we can calculate the
688/// count of the basic block, if needed.
689///
690/// \param F Function to process.
691///
692/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000693bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000694 bool Changed = false;
695 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000696 for (const auto &BI : F) {
697 const BasicBlock *BB = &BI;
698 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000699
700 // Visit all the predecessor and successor edges to determine
701 // which ones have a weight assigned already. Note that it doesn't
702 // matter that we only keep track of a single unknown edge. The
703 // only case we are interested in handling is when only a single
704 // edge is unknown (see setEdgeOrBlockWeight).
705 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000706 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000707 unsigned NumUnknownEdges = 0;
708 Edge UnknownEdge, SelfReferentialEdge;
709
710 if (i == 0) {
711 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000712 for (auto *Pred : Predecessors[BB]) {
713 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000714 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
715 if (E.first == E.second)
716 SelfReferentialEdge = E;
717 }
718 } else {
719 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000720 for (auto *Succ : Successors[BB]) {
721 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000722 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
723 }
724 }
725
726 // After visiting all the edges, there are three cases that we
727 // can handle immediately:
728 //
729 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
730 // In this case, we simply check that the sum of all the edges
731 // is the same as BB's weight. If not, we change BB's weight
732 // to match. Additionally, if BB had not been visited before,
733 // we mark it visited.
734 //
735 // - Only one edge is unknown and BB has already been visited.
736 // In this case, we can compute the weight of the edge by
737 // subtracting the total block weight from all the known
738 // edge weights. If the edges weight more than BB, then the
739 // edge of the last remaining edge is set to zero.
740 //
741 // - There exists a self-referential edge and the weight of BB is
742 // known. In this case, this edge can be based on BB's weight.
743 // We add up all the other known edges and set the weight on
744 // the self-referential edge as we did in the previous case.
745 //
746 // In any other case, we must continue iterating. Eventually,
747 // all edges will get a weight, or iteration will stop when
748 // it reaches SampleProfileMaxPropagateIterations.
749 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000750 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000751 if (NumUnknownEdges == 0) {
752 // If we already know the weight of all edges, the weight of the
753 // basic block can be computed. It should be no larger than the sum
754 // of all edge weights.
755 if (TotalWeight > BBWeight) {
756 BBWeight = TotalWeight;
757 Changed = true;
758 DEBUG(dbgs() << "All edge weights for " << BB->getName()
759 << " known. Set weight for block: ";
760 printBlockWeight(dbgs(), BB););
761 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000762 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000763 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000764 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000765 // If there is a single unknown edge and the block has been
766 // visited, then we can compute E's weight.
767 if (BBWeight >= TotalWeight)
768 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
769 else
770 EdgeWeights[UnknownEdge] = 0;
771 VisitedEdges.insert(UnknownEdge);
772 Changed = true;
773 DEBUG(dbgs() << "Set weight for edge: ";
774 printEdgeWeight(dbgs(), UnknownEdge));
775 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000776 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000777 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000778 // We have a self-referential edge and the weight of BB is known.
779 if (BBWeight >= TotalWeight)
780 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
781 else
782 EdgeWeights[SelfReferentialEdge] = 0;
783 VisitedEdges.insert(SelfReferentialEdge);
784 Changed = true;
785 DEBUG(dbgs() << "Set self-referential edge weight to: ";
786 printEdgeWeight(dbgs(), SelfReferentialEdge));
787 }
788 }
789 }
790
791 return Changed;
792}
793
794/// \brief Build in/out edge lists for each basic block in the CFG.
795///
796/// We are interested in unique edges. If a block B1 has multiple
797/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000798void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000799 for (auto &BI : F) {
800 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000801
802 // Add predecessors for B1.
803 SmallPtrSet<BasicBlock *, 16> Visited;
804 if (!Predecessors[B1].empty())
805 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000806 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
807 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000808 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000809 Predecessors[B1].push_back(B2);
810 }
811
812 // Add successors for B1.
813 Visited.clear();
814 if (!Successors[B1].empty())
815 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000816 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
817 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000818 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000819 Successors[B1].push_back(B2);
820 }
821 }
822}
823
824/// \brief Propagate weights into edges
825///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000826/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000827///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000828/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000829/// of that edge is the weight of the block.
830///
831/// - If all incoming or outgoing edges are known except one, and the
832/// weight of the block is already known, the weight of the unknown
833/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000834/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000835/// we set the unknown edge weight to zero.
836///
837/// - If there is a self-referential edge, and the weight of the block is
838/// known, the weight for that edge is set to the weight of the block
839/// minus the weight of the other incoming edges to that block (if
840/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000841void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000842 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +0000843 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000844
Diego Novilloffc84e32015-05-13 17:04:29 +0000845 // Add an entry count to the function using the samples gathered
846 // at the function entry.
847 F.setEntryCount(Samples->getHeadSamples());
848
Diego Novillo0accb3d2014-01-10 23:23:46 +0000849 // Before propagation starts, build, for each block, a list of
850 // unique predecessors and successors. This is necessary to handle
851 // identical edges in multiway branches. Since we visit all blocks and all
852 // edges of the CFG, it is cleaner to build these lists once at the start
853 // of the pass.
854 buildEdges(F);
855
856 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +0000857 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000858 Changed = propagateThroughEdges(F);
859 }
860
861 // Generate MD_prof metadata for every branch instruction using the
862 // edge weights computed during propagation.
863 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +0000864 LLVMContext &Ctx = F.getContext();
865 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000866 for (auto &BI : F) {
867 BasicBlock *BB = &BI;
868 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000869 if (TI->getNumSuccessors() == 1)
870 continue;
871 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
872 continue;
873
874 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000875 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +0000876 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +0000877 uint32_t MaxWeight = 0;
Diego Novillo7963ea12015-10-26 18:52:53 +0000878 DebugLoc MaxDestLoc;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000879 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
880 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000881 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +0000882 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000883 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +0000884 // Use uint32_t saturated arithmetic to adjust the incoming weights,
885 // if needed. Sample counts in profiles are 64-bit unsigned values,
886 // but internally branch weights are expressed as 32-bit values.
887 if (Weight > std::numeric_limits<uint32_t>::max()) {
888 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
889 Weight = std::numeric_limits<uint32_t>::max();
890 }
891 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo7963ea12015-10-26 18:52:53 +0000892 if (Weight != 0) {
893 if (Weight > MaxWeight) {
894 MaxWeight = Weight;
Diego Novillo7963ea12015-10-26 18:52:53 +0000895 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
896 }
897 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000898 }
899
900 // Only set weights if there is at least one non-zero weight.
901 // In any other case, let the analyzer set weights.
Diego Novillo7963ea12015-10-26 18:52:53 +0000902 if (MaxWeight > 0) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000903 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
904 TI->setMetadata(llvm::LLVMContext::MD_prof,
905 MDB.createBranchWeights(Weights));
Diego Novillo7963ea12015-10-26 18:52:53 +0000906 DebugLoc BranchLoc = TI->getDebugLoc();
907 emitOptimizationRemark(
908 Ctx, DEBUG_TYPE, F, MaxDestLoc,
909 Twine("most popular destination for conditional branches at ") +
Diego Novilloc04270d2015-10-27 17:37:00 +0000910 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
911 Twine(BranchLoc.getLine()) + ":" +
912 Twine(BranchLoc.getCol()))
913 : Twine("<UNKNOWN LOCATION>")));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000914 } else {
915 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
916 }
917 }
918}
919
920/// \brief Get the line number for the function header.
921///
922/// This looks up function \p F in the current compilation unit and
923/// retrieves the line number where the function is defined. This is
924/// line 0 for all the samples read from the profile file. Every line
925/// number is relative to this line.
926///
927/// \param F Function object to query.
928///
Diego Novilloa32aa322014-03-14 21:58:59 +0000929/// \returns the line number where \p F is defined. If it returns 0,
930/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +0000931unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000932 if (DISubprogram *S = getDISubprogram(&F))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000933 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000934
Diego Novilloaa555072015-10-27 18:41:46 +0000935 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +0000936 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +0000937 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +0000938 "No debug information found in function " + F.getName() +
939 ": Function profile not used",
940 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +0000941 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000942}
943
Diego Novillo7732ae42015-08-26 20:00:27 +0000944void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
945 DT.reset(new DominatorTree);
946 DT->recalculate(F);
947
948 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
949 PDT->recalculate(F);
950
951 LI.reset(new LoopInfo);
952 LI->analyze(*DT);
953}
954
Diego Novillo0accb3d2014-01-10 23:23:46 +0000955/// \brief Generate branch weight metadata for all branches in \p F.
956///
957/// Branch weights are computed out of instruction samples using a
958/// propagation heuristic. Propagation proceeds in 3 phases:
959///
960/// 1- Assignment of block weights. All the basic blocks in the function
961/// are initial assigned the same weight as their most frequently
962/// executed instruction.
963///
964/// 2- Creation of equivalence classes. Since samples may be missing from
965/// blocks, we can fill in the gaps by setting the weights of all the
966/// blocks in the same equivalence class to the same weight. To compute
967/// the concept of equivalence, we use dominance and loop information.
968/// Two blocks B1 and B2 are in the same equivalence class if B1
969/// dominates B2, B2 post-dominates B1 and both are in the same loop.
970///
971/// 3- Propagation of block weights into edges. This uses a simple
972/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000973/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000974///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000975/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000976/// of that edge is the weight of the block.
977///
978/// - If all the edges are known except one, and the weight of the
979/// block is already known, the weight of the unknown edge will
980/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000981/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000982/// we set the unknown edge weight to zero.
983///
984/// - If there is a self-referential edge, and the weight of the block is
985/// known, the weight for that edge is set to the weight of the block
986/// minus the weight of the other incoming edges to that block (if
987/// known).
988///
989/// Since this propagation is not guaranteed to finalize for every CFG, we
990/// only allow it to proceed for a limited number of iterations (controlled
991/// by -sample-profile-max-propagate-iterations).
992///
993/// FIXME: Try to replace this propagation heuristic with a scheme
994/// that is guaranteed to finalize. A work-list approach similar to
995/// the standard value propagation algorithm used by SSA-CCP might
996/// work here.
997///
998/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000999/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001000///
1001/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001002///
1003/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001004bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001005 bool Changed = false;
1006
Dehao Chen41dc5a62015-10-09 16:50:16 +00001007 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001008 return false;
1009
Diego Novillo0accb3d2014-01-10 23:23:46 +00001010 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001011 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001012
Dehao Chen67226882015-09-30 00:42:46 +00001013 Changed |= inlineHotFunctions(F);
1014
Diego Novillo0accb3d2014-01-10 23:23:46 +00001015 // Compute basic block weights.
1016 Changed |= computeBlockWeights(F);
1017
1018 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001019 // Compute dominance and loop info needed for propagation.
1020 computeDominanceAndLoopInfo(F);
1021
Diego Novillo0accb3d2014-01-10 23:23:46 +00001022 // Find equivalence classes.
1023 findEquivalenceClasses(F);
1024
1025 // Propagate weights to all edges.
1026 propagateWeights(F);
1027 }
1028
Diego Novillof9ed08e2015-10-31 21:53:58 +00001029 // If coverage checking was requested, compute it now.
1030 if (SampleProfileCoverage) {
1031 unsigned Used = CoverageTracker.countUsedSamples(Samples);
1032 unsigned Total = CoverageTracker.countBodySamples(Samples);
1033 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1034 if (Coverage < SampleProfileCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001035 F.getContext().diagnose(DiagnosticInfoSampleProfile(
David Blaikie2297a912015-11-02 20:01:13 +00001036 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001037 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1038 Twine(Coverage) + "%) were applied",
1039 DS_Warning));
1040 }
1041 }
1042
Diego Novillo0accb3d2014-01-10 23:23:46 +00001043 return Changed;
1044}
1045
Diego Novilloc0dd1032013-11-26 20:37:33 +00001046char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001047INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1048 "Sample Profile loader", false, false)
Diego Novillo92aa8c22014-03-10 22:41:28 +00001049INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001050INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1051 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001052
1053bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001054 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001055 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001056 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001057 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001058 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001059 return false;
1060 }
Diego Novillofcd55602014-11-03 00:51:45 +00001061 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001062 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001063 return true;
1064}
1065
Diego Novillo4d711132015-08-25 15:25:11 +00001066ModulePass *llvm::createSampleProfileLoaderPass() {
Diego Novilloc0dd1032013-11-26 20:37:33 +00001067 return new SampleProfileLoader(SampleProfileFile);
1068}
1069
Diego Novillo4d711132015-08-25 15:25:11 +00001070ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Diego Novilloc0dd1032013-11-26 20:37:33 +00001071 return new SampleProfileLoader(Name);
1072}
1073
Diego Novillo4d711132015-08-25 15:25:11 +00001074bool SampleProfileLoader::runOnModule(Module &M) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001075 if (!ProfileIsValid)
1076 return false;
1077
Diego Novillo4d711132015-08-25 15:25:11 +00001078 bool retval = false;
1079 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001080 if (!F.isDeclaration()) {
1081 clearFunctionData();
Diego Novillo4d711132015-08-25 15:25:11 +00001082 retval |= runOnFunction(F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001083 }
Diego Novillo4d711132015-08-25 15:25:11 +00001084 return retval;
1085}
1086
Diego Novillo8d6568b2013-11-13 12:22:21 +00001087bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novillode1ab262014-09-09 12:40:50 +00001088 Samples = Reader->getSamplesFor(F);
1089 if (!Samples->empty())
1090 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001091 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001092}