blob: 221aa0a1861a407a410ce94e293573742087ab36 [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
25#define DEBUG_TYPE "sample-profile"
26
Chandler Carruth07baed52014-01-13 08:04:33 +000027#include "llvm/Transforms/Scalar.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000028#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000029#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000030#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000031#include "llvm/ADT/StringMap.h"
32#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000033#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000034#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000035#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000036#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000037#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000038#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000039#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000040#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000041#include "llvm/IR/Instructions.h"
42#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000043#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000044#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000045#include "llvm/IR/Module.h"
46#include "llvm/Pass.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
Diego Novillo9518b632014-01-10 23:23:51 +000049#include "llvm/Support/LineIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000050#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Regex.h"
52#include "llvm/Support/raw_ostream.h"
Logan Chien61c6df02014-02-22 06:34:10 +000053#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000054
55using namespace llvm;
56
57// 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 Novillo8d6568b2013-11-13 12:22:21 +000066
67namespace {
Diego Novillo92aa8c22014-03-10 22:41:28 +000068/// \brief Represents the relative location of an instruction.
69///
70/// Instruction locations are specified by the line offset from the
71/// beginning of the function (marked by the line where the function
72/// header is) and the discriminator value within that line.
73///
74/// The discriminator value is useful to distinguish instructions
75/// that are on the same line but belong to different basic blocks
76/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
77struct InstructionLocation {
78 InstructionLocation(int L, unsigned D) : LineOffset(L), Discriminator(D) {}
79 int LineOffset;
80 unsigned Discriminator;
81};
82}
Diego Novilloc0dd1032013-11-26 20:37:33 +000083
Diego Novillo92aa8c22014-03-10 22:41:28 +000084namespace llvm {
85template <> struct DenseMapInfo<InstructionLocation> {
86 typedef DenseMapInfo<int> OffsetInfo;
87 typedef DenseMapInfo<unsigned> DiscriminatorInfo;
88 static inline InstructionLocation getEmptyKey() {
89 return InstructionLocation(OffsetInfo::getEmptyKey(),
90 DiscriminatorInfo::getEmptyKey());
91 }
92 static inline InstructionLocation getTombstoneKey() {
93 return InstructionLocation(OffsetInfo::getTombstoneKey(),
94 DiscriminatorInfo::getTombstoneKey());
95 }
96 static inline unsigned getHashValue(InstructionLocation Val) {
Diego Novillo70959082014-03-14 22:07:18 +000097 return DenseMapInfo<std::pair<int, unsigned>>::getHashValue(
Diego Novillo92aa8c22014-03-10 22:41:28 +000098 std::pair<int, unsigned>(Val.LineOffset, Val.Discriminator));
99 }
100 static inline bool isEqual(InstructionLocation LHS, InstructionLocation RHS) {
101 return LHS.LineOffset == RHS.LineOffset &&
102 LHS.Discriminator == RHS.Discriminator;
103 }
104};
105}
106
107namespace {
108typedef DenseMap<InstructionLocation, unsigned> BodySampleMap;
109typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000110typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
111typedef std::pair<BasicBlock *, BasicBlock *> Edge;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000112typedef DenseMap<Edge, unsigned> EdgeWeightMap;
Diego Novillo70959082014-03-14 22:07:18 +0000113typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000114
115/// \brief Representation of the runtime profile for a function.
116///
117/// This data structure contains the runtime profile for a given
118/// function. It contains the total number of samples collected
119/// in the function and a map of samples collected in every statement.
120class SampleFunctionProfile {
121public:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000122 SampleFunctionProfile()
123 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
Diego Novillo92aa8c22014-03-10 22:41:28 +0000124 LI(0), Ctx(0) {}
Diego Novilloc0dd1032013-11-26 20:37:33 +0000125
Diego Novillo0accb3d2014-01-10 23:23:46 +0000126 unsigned getFunctionLoc(Function &F);
127 bool emitAnnotations(Function &F, DominatorTree *DomTree,
128 PostDominatorTree *PostDomTree, LoopInfo *Loops);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000129 unsigned getInstWeight(Instruction &I);
130 unsigned getBlockWeight(BasicBlock *B);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000131 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
132 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
Diego Novillo92aa8c22014-03-10 22:41:28 +0000133 void addBodySamples(int LineOffset, unsigned Discriminator, unsigned Num) {
134 assert(LineOffset >= 0);
135 BodySamples[InstructionLocation(LineOffset, Discriminator)] += Num;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000136 }
137 void print(raw_ostream &OS);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000138 void printEdgeWeight(raw_ostream &OS, Edge E);
139 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
140 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
141 bool computeBlockWeights(Function &F);
142 void findEquivalenceClasses(Function &F);
143 void findEquivalencesFor(BasicBlock *BB1,
144 SmallVector<BasicBlock *, 8> Descendants,
145 DominatorTreeBase<BasicBlock> *DomTree);
146 void propagateWeights(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000147 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000148 void buildEdges(Function &F);
149 bool propagateThroughEdges(Function &F);
150 bool empty() { return BodySamples.empty(); }
Diego Novilloc0dd1032013-11-26 20:37:33 +0000151
152protected:
153 /// \brief Total number of samples collected inside this function.
154 ///
155 /// Samples are cumulative, they include all the samples collected
156 /// inside this function and all its inlined callees.
157 unsigned TotalSamples;
158
Diego Novillo0accb3d2014-01-10 23:23:46 +0000159 /// \brief Total number of samples collected at the head of the function.
Diego Novillo9518b632014-01-10 23:23:51 +0000160 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000161 unsigned TotalHeadSamples;
162
Diego Novillo0accb3d2014-01-10 23:23:46 +0000163 /// \brief Line number for the function header. Used to compute relative
164 /// line numbers from the absolute line LOCs found in instruction locations.
165 /// The relative line numbers are needed to address the samples from the
166 /// profile file.
167 unsigned HeaderLineno;
168
Diego Novilloc0dd1032013-11-26 20:37:33 +0000169 /// \brief Map line offsets to collected samples.
170 ///
171 /// Each entry in this map contains the number of samples
172 /// collected at the corresponding line offset. All line locations
173 /// are an offset from the start of the function.
174 BodySampleMap BodySamples;
175
176 /// \brief Map basic blocks to their computed weights.
177 ///
178 /// The weight of a basic block is defined to be the maximum
179 /// of all the instruction weights in that block.
180 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000181
182 /// \brief Map edges to their computed weights.
183 ///
184 /// Edge weights are computed by propagating basic block weights in
185 /// SampleProfile::propagateWeights.
186 EdgeWeightMap EdgeWeights;
187
188 /// \brief Set of visited blocks during propagation.
189 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
190
191 /// \brief Set of visited edges during propagation.
192 SmallSet<Edge, 128> VisitedEdges;
193
194 /// \brief Equivalence classes for block weights.
195 ///
196 /// Two blocks BB1 and BB2 are in the same equivalence class if they
197 /// dominate and post-dominate each other, and they are in the same loop
198 /// nest. When this happens, the two blocks are guaranteed to execute
199 /// the same number of times.
200 EquivalenceClassMap EquivalenceClass;
201
202 /// \brief Dominance, post-dominance and loop information.
203 DominatorTree *DT;
204 PostDominatorTree *PDT;
205 LoopInfo *LI;
206
207 /// \brief Predecessors for each basic block in the CFG.
208 BlockEdgeMap Predecessors;
209
210 /// \brief Successors for each basic block in the CFG.
211 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000212
213 /// \brief LLVM context holding the debug data we need.
214 LLVMContext *Ctx;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000215};
216
Diego Novillo8d6568b2013-11-13 12:22:21 +0000217/// \brief Sample-based profile reader.
218///
219/// Each profile contains sample counts for all the functions
220/// executed. Inside each function, statements are annotated with the
221/// collected samples on all the instructions associated with that
222/// statement.
223///
224/// For this to produce meaningful data, the program needs to be
225/// compiled with some debug information (at minimum, line numbers:
226/// -gline-tables-only). Otherwise, it will be impossible to match IR
227/// instructions to the line numbers collected by the profiler.
228///
229/// From the profile file, we are interested in collecting the
230/// following information:
231///
232/// * A list of functions included in the profile (mangled names).
233///
234/// * For each function F:
235/// 1. The total number of samples collected in F.
236///
237/// 2. The samples collected at each line in F. To provide some
238/// protection against source code shuffling, line numbers should
239/// be relative to the start of the function.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000240class SampleModuleProfile {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000241public:
Diego Novilloa32aa322014-03-14 21:58:59 +0000242 SampleModuleProfile(const Module &M, StringRef F)
243 : Profiles(0), Filename(F), M(M) {}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000244
Alexey Samsonovaa19c0a2013-11-13 13:09:39 +0000245 void dump();
Diego Novilloa32aa322014-03-14 21:58:59 +0000246 bool loadText();
Alexey Samsonovaa19c0a2013-11-13 13:09:39 +0000247 void loadNative() { llvm_unreachable("not implemented"); }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000248 void printFunctionProfile(raw_ostream &OS, StringRef FName);
249 void dumpFunctionProfile(StringRef FName);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000250 SampleFunctionProfile &getProfile(const Function &F) {
251 return Profiles[F.getName()];
252 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000253
Diego Novillo9518b632014-01-10 23:23:51 +0000254 /// \brief Report a parse error message and stop compilation.
255 void reportParseError(int64_t LineNumber, Twine Msg) const {
Diego Novilloa32aa322014-03-14 21:58:59 +0000256 DiagnosticInfoSampleProfile Diag(Filename.data(), LineNumber, Msg);
257 M.getContext().diagnose(Diag);
Diego Novillo9518b632014-01-10 23:23:51 +0000258 }
259
Diego Novillo8d6568b2013-11-13 12:22:21 +0000260protected:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000261 /// \brief Map every function to its associated profile.
262 ///
263 /// The profile of every function executed at runtime is collected
Diego Novilloc0dd1032013-11-26 20:37:33 +0000264 /// in the structure SampleFunctionProfile. This maps function objects
Diego Novillo8d6568b2013-11-13 12:22:21 +0000265 /// to their corresponding profiles.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000266 StringMap<SampleFunctionProfile> Profiles;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000267
268 /// \brief Path name to the file holding the profile data.
269 ///
270 /// The format of this file is defined by each profiler
271 /// independently. If possible, the profiler should have a text
272 /// version of the profile format to be used in constructing test
273 /// cases and debugging.
274 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000275
276 /// \brief Module being compiled. Used mainly to access the current
277 /// LLVM context for diagnostics.
278 const Module &M;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000279};
280
Diego Novillo8d6568b2013-11-13 12:22:21 +0000281/// \brief Sample profile pass.
282///
283/// This pass reads profile data from the file specified by
284/// -sample-profile-file and annotates every affected function with the
285/// profile information found in that file.
286class SampleProfileLoader : public FunctionPass {
287public:
288 // Class identification, replacement for typeinfo
289 static char ID;
290
291 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novilloa32aa322014-03-14 21:58:59 +0000292 : FunctionPass(ID), Profiler(), Filename(Name), ProfileIsValid(false) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000293 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
294 }
295
Craig Topper3e4c6972014-03-05 09:10:37 +0000296 bool doInitialization(Module &M) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000297
298 void dump() { Profiler->dump(); }
299
Craig Topper3e4c6972014-03-05 09:10:37 +0000300 const char *getPassName() const override { return "Sample profile pass"; }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000301
Craig Topper3e4c6972014-03-05 09:10:37 +0000302 bool runOnFunction(Function &F) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000303
Craig Topper3e4c6972014-03-05 09:10:37 +0000304 void getAnalysisUsage(AnalysisUsage &AU) const override {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000305 AU.setPreservesCFG();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000306 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000307 AU.addRequired<DominatorTreeWrapperPass>();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000308 AU.addRequired<PostDominatorTree>();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000309 }
310
311protected:
312 /// \brief Profile reader object.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000313 std::unique_ptr<SampleModuleProfile> Profiler;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000314
315 /// \brief Name of the profile file to load.
316 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000317
318 /// \brief Flag indicating whether the profile input loaded succesfully.
319 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000320};
321}
322
Diego Novilloc0dd1032013-11-26 20:37:33 +0000323/// \brief Print this function profile on stream \p OS.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000324///
325/// \param OS Stream to emit the output to.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000326void SampleFunctionProfile::print(raw_ostream &OS) {
327 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
Diego Novillo8d6568b2013-11-13 12:22:21 +0000328 << " sampled lines\n";
Diego Novilloc0dd1032013-11-26 20:37:33 +0000329 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
330 SE = BodySamples.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000331 SI != SE; ++SI)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000332 OS << "\tline offset: " << SI->first.LineOffset
333 << ", discriminator: " << SI->first.Discriminator
Diego Novillo8d6568b2013-11-13 12:22:21 +0000334 << ", number of samples: " << SI->second << "\n";
335 OS << "\n";
336}
337
Diego Novillo0accb3d2014-01-10 23:23:46 +0000338/// \brief Print the weight of edge \p E on stream \p OS.
339///
340/// \param OS Stream to emit the output to.
341/// \param E Edge to print.
342void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
343 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
344 << "]: " << EdgeWeights[E] << "\n";
345}
346
347/// \brief Print the equivalence class of block \p BB on stream \p OS.
348///
349/// \param OS Stream to emit the output to.
350/// \param BB Block to print.
351void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
352 BasicBlock *BB) {
353 BasicBlock *Equiv = EquivalenceClass[BB];
354 OS << "equivalence[" << BB->getName()
355 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
356}
357
358/// \brief Print the weight of block \p BB on stream \p OS.
359///
360/// \param OS Stream to emit the output to.
361/// \param BB Block to print.
362void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
363 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
364}
365
Diego Novilloc0dd1032013-11-26 20:37:33 +0000366/// \brief Print the function profile for \p FName on stream \p OS.
367///
368/// \param OS Stream to emit the output to.
369/// \param FName Name of the function to print.
370void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
371 StringRef FName) {
372 OS << "Function: " << FName << ":\n";
373 Profiles[FName].print(OS);
374}
375
Diego Novillo8d6568b2013-11-13 12:22:21 +0000376/// \brief Dump the function profile for \p FName.
377///
378/// \param FName Name of the function to print.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000379void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000380 printFunctionProfile(dbgs(), FName);
381}
382
383/// \brief Dump all the function profiles found.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000384void SampleModuleProfile::dump() {
385 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
386 E = Profiles.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000387 I != E; ++I)
388 dumpFunctionProfile(I->getKey());
389}
390
391/// \brief Load samples from a text file.
392///
Diego Novillo9518b632014-01-10 23:23:51 +0000393/// The file contains a list of samples for every function executed at
394/// runtime. Each function profile has the following format:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000395///
Diego Novillo9518b632014-01-10 23:23:51 +0000396/// function1:total_samples:total_head_samples
397/// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
398/// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000399/// ...
Diego Novillo9518b632014-01-10 23:23:51 +0000400/// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000401///
402/// Function names must be mangled in order for the profile loader to
Diego Novillo9518b632014-01-10 23:23:51 +0000403/// match them in the current translation unit. The two numbers in the
404/// function header specify how many total samples were accumulated in
405/// the function (first number), and the total number of samples accumulated
406/// at the prologue of the function (second number). This head sample
407/// count provides an indicator of how frequent is the function invoked.
408///
409/// Each sampled line may contain several items. Some are optional
410/// (marked below):
411///
412/// a- Source line offset. This number represents the line number
413/// in the function where the sample was collected. The line number
414/// is always relative to the line where symbol of the function
415/// is defined. So, if the function has its header at line 280,
416/// the offset 13 is at line 293 in the file.
417///
418/// b- [OPTIONAL] Discriminator. This is used if the sampled program
419/// was compiled with DWARF discriminator support
420/// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators)
Diego Novillo9518b632014-01-10 23:23:51 +0000421///
422/// c- Number of samples. This is the number of samples collected by
423/// the profiler at this source location.
424///
425/// d- [OPTIONAL] Potential call targets and samples. If present, this
426/// line contains a call instruction. This models both direct and
427/// indirect calls. Each called target is listed together with the
428/// number of samples. For example,
429///
430/// 130: 7 foo:3 bar:2 baz:7
431///
432/// The above means that at relative line offset 130 there is a
433/// call instruction that calls one of foo(), bar() and baz(). With
434/// baz() being the relatively more frequent call target.
435///
436/// FIXME: This is currently unhandled, but it has a lot of
437/// potential for aiding the inliner.
438///
Diego Novillo8d6568b2013-11-13 12:22:21 +0000439///
440/// Since this is a flat profile, a function that shows up more than
441/// once gets all its samples aggregated across all its instances.
Diego Novillo9518b632014-01-10 23:23:51 +0000442///
443/// FIXME: flat profiles are too imprecise to provide good optimization
444/// opportunities. Convert them to context-sensitive profile.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000445///
446/// This textual representation is useful to generate unit tests and
447/// for debugging purposes, but it should not be used to generate
448/// profiles for large programs, as the representation is extremely
449/// inefficient.
Diego Novilloa32aa322014-03-14 21:58:59 +0000450///
451/// \returns true if the file was loaded successfully, false otherwise.
452bool SampleModuleProfile::loadText() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000453 std::unique_ptr<MemoryBuffer> Buffer;
Diego Novillo9518b632014-01-10 23:23:51 +0000454 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
Diego Novilloa32aa322014-03-14 21:58:59 +0000455 if (EC) {
456 std::string Msg(EC.message());
NAKAMURA Takumibfb17282014-03-15 00:10:12 +0000457 M.getContext().diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
Diego Novilloa32aa322014-03-14 21:58:59 +0000458 return false;
459 }
Diego Novillo9518b632014-01-10 23:23:51 +0000460 line_iterator LineIt(*Buffer, '#');
Diego Novillo8d6568b2013-11-13 12:22:21 +0000461
462 // Read the profile of each function. Since each function may be
463 // mentioned more than once, and we are collecting flat profiles,
464 // accumulate samples as we parse them.
Diego Novillo9518b632014-01-10 23:23:51 +0000465 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+)$");
Diego Novillo92aa8c22014-03-10 22:41:28 +0000466 Regex LineSample("^([0-9]+)\\.?([0-9]+)?: ([0-9]+)(.*)$");
Diego Novillo9518b632014-01-10 23:23:51 +0000467 while (!LineIt.is_at_eof()) {
468 // Read the header of each function. The function header should
469 // have this format:
470 //
471 // function_name:total_samples:total_head_samples
472 //
473 // See above for an explanation of each field.
474 SmallVector<StringRef, 3> Matches;
Diego Novilloa32aa322014-03-14 21:58:59 +0000475 if (!HeadRE.match(*LineIt, &Matches)) {
Diego Novillo9518b632014-01-10 23:23:51 +0000476 reportParseError(LineIt.line_number(),
477 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
Diego Novilloa32aa322014-03-14 21:58:59 +0000478 return false;
479 }
Diego Novillo9518b632014-01-10 23:23:51 +0000480 assert(Matches.size() == 4);
Diego Novillo8d6568b2013-11-13 12:22:21 +0000481 StringRef FName = Matches[1];
Diego Novillo9518b632014-01-10 23:23:51 +0000482 unsigned NumSamples, NumHeadSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000483 Matches[2].getAsInteger(10, NumSamples);
484 Matches[3].getAsInteger(10, NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000485 Profiles[FName] = SampleFunctionProfile();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000486 SampleFunctionProfile &FProfile = Profiles[FName];
487 FProfile.addTotalSamples(NumSamples);
488 FProfile.addHeadSamples(NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000489 ++LineIt;
490
491 // Now read the body. The body of the function ends when we reach
492 // EOF or when we see the start of the next function.
493 while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
Diego Novilloa32aa322014-03-14 21:58:59 +0000494 if (!LineSample.match(*LineIt, &Matches)) {
Diego Novillo9518b632014-01-10 23:23:51 +0000495 reportParseError(
496 LineIt.line_number(),
497 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
Diego Novilloa32aa322014-03-14 21:58:59 +0000498 return false;
499 }
Diego Novillo9518b632014-01-10 23:23:51 +0000500 assert(Matches.size() == 5);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000501 unsigned LineOffset, NumSamples, Discriminator = 0;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000502 Matches[1].getAsInteger(10, LineOffset);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000503 if (Matches[2] != "")
504 Matches[2].getAsInteger(10, Discriminator);
Diego Novillo9518b632014-01-10 23:23:51 +0000505 Matches[3].getAsInteger(10, NumSamples);
506
507 // FIXME: Handle called targets (in Matches[4]).
508
Diego Novillo0accb3d2014-01-10 23:23:46 +0000509 // When dealing with instruction weights, we use the value
510 // zero to indicate the absence of a sample. If we read an
511 // actual zero from the profile file, return it as 1 to
512 // avoid the confusion later on.
513 if (NumSamples == 0)
514 NumSamples = 1;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000515 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000516 ++LineIt;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000517 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000518 }
Diego Novilloa32aa322014-03-14 21:58:59 +0000519
520 return true;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000521}
522
Diego Novillo0accb3d2014-01-10 23:23:46 +0000523/// \brief Get the weight for an instruction.
524///
525/// The "weight" of an instruction \p Inst is the number of samples
526/// collected on that instruction at runtime. To retrieve it, we
527/// need to compute the line number of \p Inst relative to the start of its
528/// function. We use HeaderLineno to compute the offset. We then
529/// look up the samples collected for \p Inst using BodySamples.
530///
531/// \param Inst Instruction to query.
532///
533/// \returns The profiled weight of I.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000534unsigned SampleFunctionProfile::getInstWeight(Instruction &Inst) {
535 DebugLoc DLoc = Inst.getDebugLoc();
536 unsigned Lineno = DLoc.getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000537 if (Lineno < HeaderLineno)
538 return 0;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000539
540 DILocation DIL(DLoc.getAsMDNode(*Ctx));
541 int LOffset = Lineno - HeaderLineno;
542 unsigned Discriminator = DIL.getDiscriminator();
543 unsigned Weight =
544 BodySamples.lookup(InstructionLocation(LOffset, Discriminator));
545 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst
546 << " (line offset: " << LOffset << "." << Discriminator
Diego Novillo0accb3d2014-01-10 23:23:46 +0000547 << " - weight: " << Weight << ")\n");
548 return Weight;
549}
550
551/// \brief Compute the weight of a basic block.
552///
553/// The weight of basic block \p B is the maximum weight of all the
554/// instructions in B. The weight of \p B is computed and cached in
555/// the BlockWeights map.
556///
557/// \param B The basic block to query.
558///
559/// \returns The computed weight of B.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000560unsigned SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000561 // If we've computed B's weight before, return it.
562 std::pair<BlockWeightMap::iterator, bool> Entry =
563 BlockWeights.insert(std::make_pair(B, 0));
564 if (!Entry.second)
565 return Entry.first->second;
566
567 // Otherwise, compute and cache B's weight.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000568 unsigned Weight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000569 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000570 unsigned InstWeight = getInstWeight(*I);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000571 if (InstWeight > Weight)
572 Weight = InstWeight;
573 }
574 Entry.first->second = Weight;
575 return Weight;
576}
577
578/// \brief Compute and store the weights of every basic block.
579///
580/// This populates the BlockWeights map by computing
581/// the weights of every basic block in the CFG.
582///
583/// \param F The function to query.
584bool SampleFunctionProfile::computeBlockWeights(Function &F) {
585 bool Changed = false;
586 DEBUG(dbgs() << "Block weights\n");
587 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000588 unsigned Weight = getBlockWeight(B);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000589 Changed |= (Weight > 0);
590 DEBUG(printBlockWeight(dbgs(), B));
591 }
592
593 return Changed;
594}
595
596/// \brief Find equivalence classes for the given block.
597///
598/// This finds all the blocks that are guaranteed to execute the same
599/// number of times as \p BB1. To do this, it traverses all the the
600/// descendants of \p BB1 in the dominator or post-dominator tree.
601///
602/// A block BB2 will be in the same equivalence class as \p BB1 if
603/// the following holds:
604///
605/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
606/// is a descendant of \p BB1 in the dominator tree, then BB2 should
607/// dominate BB1 in the post-dominator tree.
608///
609/// 2- Both BB2 and \p BB1 must be in the same loop.
610///
611/// For every block BB2 that meets those two requirements, we set BB2's
612/// equivalence class to \p BB1.
613///
614/// \param BB1 Block to check.
615/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
616/// \param DomTree Opposite dominator tree. If \p Descendants is filled
617/// with blocks from \p BB1's dominator tree, then
618/// this is the post-dominator tree, and vice versa.
619void SampleFunctionProfile::findEquivalencesFor(
620 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
621 DominatorTreeBase<BasicBlock> *DomTree) {
622 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(),
623 E = Descendants.end();
624 I != E; ++I) {
625 BasicBlock *BB2 = *I;
626 bool IsDomParent = DomTree->dominates(BB2, BB1);
627 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
628 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
629 IsInSameLoop) {
630 EquivalenceClass[BB2] = BB1;
631
632 // If BB2 is heavier than BB1, make BB2 have the same weight
633 // as BB1.
634 //
635 // Note that we don't worry about the opposite situation here
636 // (when BB2 is lighter than BB1). We will deal with this
637 // during the propagation phase. Right now, we just want to
638 // make sure that BB1 has the largest weight of all the
639 // members of its equivalence set.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000640 unsigned &BB1Weight = BlockWeights[BB1];
641 unsigned &BB2Weight = BlockWeights[BB2];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000642 BB1Weight = std::max(BB1Weight, BB2Weight);
643 }
644 }
645}
646
647/// \brief Find equivalence classes.
648///
649/// Since samples may be missing from blocks, we can fill in the gaps by setting
650/// the weights of all the blocks in the same equivalence class to the same
651/// weight. To compute the concept of equivalence, we use dominance and loop
652/// information. Two blocks B1 and B2 are in the same equivalence class if B1
653/// dominates B2, B2 post-dominates B1 and both are in the same loop.
654///
655/// \param F The function to query.
656void SampleFunctionProfile::findEquivalenceClasses(Function &F) {
657 SmallVector<BasicBlock *, 8> DominatedBBs;
658 DEBUG(dbgs() << "\nBlock equivalence classes\n");
659 // Find equivalence sets based on dominance and post-dominance information.
660 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
661 BasicBlock *BB1 = B;
662
663 // Compute BB1's equivalence class once.
664 if (EquivalenceClass.count(BB1)) {
665 DEBUG(printBlockEquivalence(dbgs(), BB1));
666 continue;
667 }
668
669 // By default, blocks are in their own equivalence class.
670 EquivalenceClass[BB1] = BB1;
671
672 // Traverse all the blocks dominated by BB1. We are looking for
673 // every basic block BB2 such that:
674 //
675 // 1- BB1 dominates BB2.
676 // 2- BB2 post-dominates BB1.
677 // 3- BB1 and BB2 are in the same loop nest.
678 //
679 // If all those conditions hold, it means that BB2 is executed
680 // as many times as BB1, so they are placed in the same equivalence
681 // class by making BB2's equivalence class be BB1.
682 DominatedBBs.clear();
683 DT->getDescendants(BB1, DominatedBBs);
684 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
685
686 // Repeat the same logic for all the blocks post-dominated by BB1.
687 // We are looking for every basic block BB2 such that:
688 //
689 // 1- BB1 post-dominates BB2.
690 // 2- BB2 dominates BB1.
691 // 3- BB1 and BB2 are in the same loop nest.
692 //
693 // If all those conditions hold, BB2's equivalence class is BB1.
694 DominatedBBs.clear();
695 PDT->getDescendants(BB1, DominatedBBs);
Chandler Carruth73523022014-01-13 13:07:17 +0000696 findEquivalencesFor(BB1, DominatedBBs, DT);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000697
698 DEBUG(printBlockEquivalence(dbgs(), BB1));
699 }
700
701 // Assign weights to equivalence classes.
702 //
703 // All the basic blocks in the same equivalence class will execute
704 // the same number of times. Since we know that the head block in
705 // each equivalence class has the largest weight, assign that weight
706 // to all the blocks in that equivalence class.
707 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
708 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
709 BasicBlock *BB = B;
710 BasicBlock *EquivBB = EquivalenceClass[BB];
711 if (BB != EquivBB)
712 BlockWeights[BB] = BlockWeights[EquivBB];
713 DEBUG(printBlockWeight(dbgs(), BB));
714 }
715}
716
717/// \brief Visit the given edge to decide if it has a valid weight.
718///
719/// If \p E has not been visited before, we copy to \p UnknownEdge
720/// and increment the count of unknown edges.
721///
722/// \param E Edge to visit.
723/// \param NumUnknownEdges Current number of unknown edges.
724/// \param UnknownEdge Set if E has not been visited before.
725///
726/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000727unsigned SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000728 Edge *UnknownEdge) {
729 if (!VisitedEdges.count(E)) {
730 (*NumUnknownEdges)++;
731 *UnknownEdge = E;
732 return 0;
733 }
734
735 return EdgeWeights[E];
736}
737
738/// \brief Propagate weights through incoming/outgoing edges.
739///
740/// If the weight of a basic block is known, and there is only one edge
741/// with an unknown weight, we can calculate the weight of that edge.
742///
743/// Similarly, if all the edges have a known count, we can calculate the
744/// count of the basic block, if needed.
745///
746/// \param F Function to process.
747///
748/// \returns True if new weights were assigned to edges or blocks.
749bool SampleFunctionProfile::propagateThroughEdges(Function &F) {
750 bool Changed = false;
751 DEBUG(dbgs() << "\nPropagation through edges\n");
752 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
753 BasicBlock *BB = BI;
754
755 // Visit all the predecessor and successor edges to determine
756 // which ones have a weight assigned already. Note that it doesn't
757 // matter that we only keep track of a single unknown edge. The
758 // only case we are interested in handling is when only a single
759 // edge is unknown (see setEdgeOrBlockWeight).
760 for (unsigned i = 0; i < 2; i++) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000761 unsigned TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000762 unsigned NumUnknownEdges = 0;
763 Edge UnknownEdge, SelfReferentialEdge;
764
765 if (i == 0) {
766 // First, visit all predecessor edges.
767 for (size_t I = 0; I < Predecessors[BB].size(); I++) {
768 Edge E = std::make_pair(Predecessors[BB][I], BB);
769 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
770 if (E.first == E.second)
771 SelfReferentialEdge = E;
772 }
773 } else {
774 // On the second round, visit all successor edges.
775 for (size_t I = 0; I < Successors[BB].size(); I++) {
776 Edge E = std::make_pair(BB, Successors[BB][I]);
777 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
778 }
779 }
780
781 // After visiting all the edges, there are three cases that we
782 // can handle immediately:
783 //
784 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
785 // In this case, we simply check that the sum of all the edges
786 // is the same as BB's weight. If not, we change BB's weight
787 // to match. Additionally, if BB had not been visited before,
788 // we mark it visited.
789 //
790 // - Only one edge is unknown and BB has already been visited.
791 // In this case, we can compute the weight of the edge by
792 // subtracting the total block weight from all the known
793 // edge weights. If the edges weight more than BB, then the
794 // edge of the last remaining edge is set to zero.
795 //
796 // - There exists a self-referential edge and the weight of BB is
797 // known. In this case, this edge can be based on BB's weight.
798 // We add up all the other known edges and set the weight on
799 // the self-referential edge as we did in the previous case.
800 //
801 // In any other case, we must continue iterating. Eventually,
802 // all edges will get a weight, or iteration will stop when
803 // it reaches SampleProfileMaxPropagateIterations.
804 if (NumUnknownEdges <= 1) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000805 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000806 if (NumUnknownEdges == 0) {
807 // If we already know the weight of all edges, the weight of the
808 // basic block can be computed. It should be no larger than the sum
809 // of all edge weights.
810 if (TotalWeight > BBWeight) {
811 BBWeight = TotalWeight;
812 Changed = true;
813 DEBUG(dbgs() << "All edge weights for " << BB->getName()
814 << " known. Set weight for block: ";
815 printBlockWeight(dbgs(), BB););
816 }
817 if (VisitedBlocks.insert(BB))
818 Changed = true;
819 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
820 // If there is a single unknown edge and the block has been
821 // visited, then we can compute E's weight.
822 if (BBWeight >= TotalWeight)
823 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
824 else
825 EdgeWeights[UnknownEdge] = 0;
826 VisitedEdges.insert(UnknownEdge);
827 Changed = true;
828 DEBUG(dbgs() << "Set weight for edge: ";
829 printEdgeWeight(dbgs(), UnknownEdge));
830 }
831 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000832 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000833 // We have a self-referential edge and the weight of BB is known.
834 if (BBWeight >= TotalWeight)
835 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
836 else
837 EdgeWeights[SelfReferentialEdge] = 0;
838 VisitedEdges.insert(SelfReferentialEdge);
839 Changed = true;
840 DEBUG(dbgs() << "Set self-referential edge weight to: ";
841 printEdgeWeight(dbgs(), SelfReferentialEdge));
842 }
843 }
844 }
845
846 return Changed;
847}
848
849/// \brief Build in/out edge lists for each basic block in the CFG.
850///
851/// We are interested in unique edges. If a block B1 has multiple
852/// edges to another block B2, we only add a single B1->B2 edge.
853void SampleFunctionProfile::buildEdges(Function &F) {
854 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
855 BasicBlock *B1 = I;
856
857 // Add predecessors for B1.
858 SmallPtrSet<BasicBlock *, 16> Visited;
859 if (!Predecessors[B1].empty())
860 llvm_unreachable("Found a stale predecessors list in a basic block.");
861 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
862 BasicBlock *B2 = *PI;
863 if (Visited.insert(B2))
864 Predecessors[B1].push_back(B2);
865 }
866
867 // Add successors for B1.
868 Visited.clear();
869 if (!Successors[B1].empty())
870 llvm_unreachable("Found a stale successors list in a basic block.");
871 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
872 BasicBlock *B2 = *SI;
873 if (Visited.insert(B2))
874 Successors[B1].push_back(B2);
875 }
876 }
877}
878
879/// \brief Propagate weights into edges
880///
881/// The following rules are applied to every block B in the CFG:
882///
883/// - If B has a single predecessor/successor, then the weight
884/// of that edge is the weight of the block.
885///
886/// - If all incoming or outgoing edges are known except one, and the
887/// weight of the block is already known, the weight of the unknown
888/// edge will be the weight of the block minus the sum of all the known
889/// edges. If the sum of all the known edges is larger than B's weight,
890/// we set the unknown edge weight to zero.
891///
892/// - If there is a self-referential edge, and the weight of the block is
893/// known, the weight for that edge is set to the weight of the block
894/// minus the weight of the other incoming edges to that block (if
895/// known).
896void SampleFunctionProfile::propagateWeights(Function &F) {
897 bool Changed = true;
898 unsigned i = 0;
899
900 // Before propagation starts, build, for each block, a list of
901 // unique predecessors and successors. This is necessary to handle
902 // identical edges in multiway branches. Since we visit all blocks and all
903 // edges of the CFG, it is cleaner to build these lists once at the start
904 // of the pass.
905 buildEdges(F);
906
907 // Propagate until we converge or we go past the iteration limit.
908 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
909 Changed = propagateThroughEdges(F);
910 }
911
912 // Generate MD_prof metadata for every branch instruction using the
913 // edge weights computed during propagation.
914 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
915 MDBuilder MDB(F.getContext());
916 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
917 BasicBlock *B = I;
918 TerminatorInst *TI = B->getTerminator();
919 if (TI->getNumSuccessors() == 1)
920 continue;
921 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
922 continue;
923
924 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000925 << TI->getDebugLoc().getLine() << ".\n");
926 SmallVector<unsigned, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000927 bool AllWeightsZero = true;
928 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
929 BasicBlock *Succ = TI->getSuccessor(I);
930 Edge E = std::make_pair(B, Succ);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000931 unsigned Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000932 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
933 Weights.push_back(Weight);
934 if (Weight != 0)
935 AllWeightsZero = false;
936 }
937
938 // Only set weights if there is at least one non-zero weight.
939 // In any other case, let the analyzer set weights.
940 if (!AllWeightsZero) {
941 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
942 TI->setMetadata(llvm::LLVMContext::MD_prof,
943 MDB.createBranchWeights(Weights));
944 } else {
945 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
946 }
947 }
948}
949
950/// \brief Get the line number for the function header.
951///
952/// This looks up function \p F in the current compilation unit and
953/// retrieves the line number where the function is defined. This is
954/// line 0 for all the samples read from the profile file. Every line
955/// number is relative to this line.
956///
957/// \param F Function object to query.
958///
Diego Novilloa32aa322014-03-14 21:58:59 +0000959/// \returns the line number where \p F is defined. If it returns 0,
960/// it means that there is no debug information available for \p F.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000961unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
962 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
963 if (CUNodes) {
964 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) {
965 DICompileUnit CU(CUNodes->getOperand(I));
966 DIArray Subprograms = CU.getSubprograms();
967 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) {
968 DISubprogram Subprogram(Subprograms.getElement(J));
969 if (Subprogram.describes(&F))
970 return Subprogram.getLineNumber();
971 }
972 }
973 }
974
David Blaikie61079682014-03-16 01:36:18 +0000975 F.getContext().diagnose(DiagnosticInfoSampleProfile(
976 "No debug information found in function " + F.getName()));
Diego Novilloa32aa322014-03-14 21:58:59 +0000977 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000978}
979
980/// \brief Generate branch weight metadata for all branches in \p F.
981///
982/// Branch weights are computed out of instruction samples using a
983/// propagation heuristic. Propagation proceeds in 3 phases:
984///
985/// 1- Assignment of block weights. All the basic blocks in the function
986/// are initial assigned the same weight as their most frequently
987/// executed instruction.
988///
989/// 2- Creation of equivalence classes. Since samples may be missing from
990/// blocks, we can fill in the gaps by setting the weights of all the
991/// blocks in the same equivalence class to the same weight. To compute
992/// the concept of equivalence, we use dominance and loop information.
993/// Two blocks B1 and B2 are in the same equivalence class if B1
994/// dominates B2, B2 post-dominates B1 and both are in the same loop.
995///
996/// 3- Propagation of block weights into edges. This uses a simple
997/// propagation heuristic. The following rules are applied to every
998/// block B in the CFG:
999///
1000/// - If B has a single predecessor/successor, then the weight
1001/// of that edge is the weight of the block.
1002///
1003/// - If all the edges are known except one, and the weight of the
1004/// block is already known, the weight of the unknown edge will
1005/// be the weight of the block minus the sum of all the known
1006/// edges. If the sum of all the known edges is larger than B's weight,
1007/// we set the unknown edge weight to zero.
1008///
1009/// - If there is a self-referential edge, and the weight of the block is
1010/// known, the weight for that edge is set to the weight of the block
1011/// minus the weight of the other incoming edges to that block (if
1012/// known).
1013///
1014/// Since this propagation is not guaranteed to finalize for every CFG, we
1015/// only allow it to proceed for a limited number of iterations (controlled
1016/// by -sample-profile-max-propagate-iterations).
1017///
1018/// FIXME: Try to replace this propagation heuristic with a scheme
1019/// that is guaranteed to finalize. A work-list approach similar to
1020/// the standard value propagation algorithm used by SSA-CCP might
1021/// work here.
1022///
1023/// Once all the branch weights are computed, we emit the MD_prof
1024/// metadata on B using the computed values for each of its branches.
1025///
1026/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001027///
1028/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001029bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
1030 PostDominatorTree *PostDomTree,
1031 LoopInfo *Loops) {
1032 bool Changed = false;
1033
1034 // Initialize invariants used during computation and propagation.
1035 HeaderLineno = getFunctionLoc(F);
Diego Novilloa32aa322014-03-14 21:58:59 +00001036 if (HeaderLineno == 0)
1037 return false;
1038
Diego Novillo0accb3d2014-01-10 23:23:46 +00001039 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1040 << ": " << HeaderLineno << "\n");
1041 DT = DomTree;
1042 PDT = PostDomTree;
1043 LI = Loops;
Diego Novillo92aa8c22014-03-10 22:41:28 +00001044 Ctx = &F.getParent()->getContext();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001045
1046 // Compute basic block weights.
1047 Changed |= computeBlockWeights(F);
1048
1049 if (Changed) {
1050 // Find equivalence classes.
1051 findEquivalenceClasses(F);
1052
1053 // Propagate weights to all edges.
1054 propagateWeights(F);
1055 }
1056
1057 return Changed;
1058}
1059
Diego Novilloc0dd1032013-11-26 20:37:33 +00001060char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001061INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1062 "Sample Profile loader", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +00001063INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001064INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
1065INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Diego Novillo92aa8c22014-03-10 22:41:28 +00001066INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001067INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1068 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001069
1070bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novilloa32aa322014-03-14 21:58:59 +00001071 Profiler.reset(new SampleModuleProfile(M, Filename));
1072 ProfileIsValid = Profiler->loadText();
Diego Novilloc0dd1032013-11-26 20:37:33 +00001073 return true;
1074}
1075
1076FunctionPass *llvm::createSampleProfileLoaderPass() {
1077 return new SampleProfileLoader(SampleProfileFile);
1078}
1079
1080FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1081 return new SampleProfileLoader(Name);
1082}
1083
Diego Novillo8d6568b2013-11-13 12:22:21 +00001084bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novilloa32aa322014-03-14 21:58:59 +00001085 if (!ProfileIsValid)
1086 return false;
Chandler Carruth73523022014-01-13 13:07:17 +00001087 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001088 PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
1089 LoopInfo *LI = &getAnalysis<LoopInfo>();
1090 SampleFunctionProfile &FunctionProfile = Profiler->getProfile(F);
1091 if (!FunctionProfile.empty())
1092 return FunctionProfile.emitAnnotations(F, DT, PDT, LI);
1093 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001094}