blob: ab26fa5b23e058377ceba307ceea72f7646e91c9 [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"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000038#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000039#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000040#include "llvm/IR/Instructions.h"
41#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000042#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000043#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000044#include "llvm/IR/Module.h"
45#include "llvm/Pass.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Diego Novillo9518b632014-01-10 23:23:51 +000048#include "llvm/Support/LineIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000049#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Regex.h"
51#include "llvm/Support/raw_ostream.h"
Logan Chien61c6df02014-02-22 06:34:10 +000052#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000053
54using namespace llvm;
55
56// Command line option to specify the file to read samples from. This is
57// mainly used for debugging.
58static cl::opt<std::string> SampleProfileFile(
59 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
60 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000061static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
62 "sample-profile-max-propagate-iterations", cl::init(100),
63 cl::desc("Maximum number of iterations to go through when propagating "
64 "sample block/edge weights through the CFG."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000065
66namespace {
Diego Novillo92aa8c22014-03-10 22:41:28 +000067/// \brief Represents the relative location of an instruction.
68///
69/// Instruction locations are specified by the line offset from the
70/// beginning of the function (marked by the line where the function
71/// header is) and the discriminator value within that line.
72///
73/// The discriminator value is useful to distinguish instructions
74/// that are on the same line but belong to different basic blocks
75/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
76struct InstructionLocation {
77 InstructionLocation(int L, unsigned D) : LineOffset(L), Discriminator(D) {}
78 int LineOffset;
79 unsigned Discriminator;
80};
81}
Diego Novilloc0dd1032013-11-26 20:37:33 +000082
Diego Novillo92aa8c22014-03-10 22:41:28 +000083namespace llvm {
84template <> struct DenseMapInfo<InstructionLocation> {
85 typedef DenseMapInfo<int> OffsetInfo;
86 typedef DenseMapInfo<unsigned> DiscriminatorInfo;
87 static inline InstructionLocation getEmptyKey() {
88 return InstructionLocation(OffsetInfo::getEmptyKey(),
89 DiscriminatorInfo::getEmptyKey());
90 }
91 static inline InstructionLocation getTombstoneKey() {
92 return InstructionLocation(OffsetInfo::getTombstoneKey(),
93 DiscriminatorInfo::getTombstoneKey());
94 }
95 static inline unsigned getHashValue(InstructionLocation Val) {
96 return DenseMapInfo<std::pair<int, unsigned> >::getHashValue(
97 std::pair<int, unsigned>(Val.LineOffset, Val.Discriminator));
98 }
99 static inline bool isEqual(InstructionLocation LHS, InstructionLocation RHS) {
100 return LHS.LineOffset == RHS.LineOffset &&
101 LHS.Discriminator == RHS.Discriminator;
102 }
103};
104}
105
106namespace {
107typedef DenseMap<InstructionLocation, unsigned> BodySampleMap;
108typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000109typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
110typedef std::pair<BasicBlock *, BasicBlock *> Edge;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000111typedef DenseMap<Edge, unsigned> EdgeWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000112typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000113
114/// \brief Representation of the runtime profile for a function.
115///
116/// This data structure contains the runtime profile for a given
117/// function. It contains the total number of samples collected
118/// in the function and a map of samples collected in every statement.
119class SampleFunctionProfile {
120public:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000121 SampleFunctionProfile()
122 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
Diego Novillo92aa8c22014-03-10 22:41:28 +0000123 LI(0), Ctx(0) {}
Diego Novilloc0dd1032013-11-26 20:37:33 +0000124
Diego Novillo0accb3d2014-01-10 23:23:46 +0000125 unsigned getFunctionLoc(Function &F);
126 bool emitAnnotations(Function &F, DominatorTree *DomTree,
127 PostDominatorTree *PostDomTree, LoopInfo *Loops);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000128 unsigned getInstWeight(Instruction &I);
129 unsigned getBlockWeight(BasicBlock *B);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000130 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
131 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
Diego Novillo92aa8c22014-03-10 22:41:28 +0000132 void addBodySamples(int LineOffset, unsigned Discriminator, unsigned Num) {
133 assert(LineOffset >= 0);
134 BodySamples[InstructionLocation(LineOffset, Discriminator)] += Num;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000135 }
136 void print(raw_ostream &OS);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000137 void printEdgeWeight(raw_ostream &OS, Edge E);
138 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
139 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
140 bool computeBlockWeights(Function &F);
141 void findEquivalenceClasses(Function &F);
142 void findEquivalencesFor(BasicBlock *BB1,
143 SmallVector<BasicBlock *, 8> Descendants,
144 DominatorTreeBase<BasicBlock> *DomTree);
145 void propagateWeights(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000146 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000147 void buildEdges(Function &F);
148 bool propagateThroughEdges(Function &F);
149 bool empty() { return BodySamples.empty(); }
Diego Novilloc0dd1032013-11-26 20:37:33 +0000150
151protected:
152 /// \brief Total number of samples collected inside this function.
153 ///
154 /// Samples are cumulative, they include all the samples collected
155 /// inside this function and all its inlined callees.
156 unsigned TotalSamples;
157
Diego Novillo0accb3d2014-01-10 23:23:46 +0000158 /// \brief Total number of samples collected at the head of the function.
Diego Novillo9518b632014-01-10 23:23:51 +0000159 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000160 unsigned TotalHeadSamples;
161
Diego Novillo0accb3d2014-01-10 23:23:46 +0000162 /// \brief Line number for the function header. Used to compute relative
163 /// line numbers from the absolute line LOCs found in instruction locations.
164 /// The relative line numbers are needed to address the samples from the
165 /// profile file.
166 unsigned HeaderLineno;
167
Diego Novilloc0dd1032013-11-26 20:37:33 +0000168 /// \brief Map line offsets to collected samples.
169 ///
170 /// Each entry in this map contains the number of samples
171 /// collected at the corresponding line offset. All line locations
172 /// are an offset from the start of the function.
173 BodySampleMap BodySamples;
174
175 /// \brief Map basic blocks to their computed weights.
176 ///
177 /// The weight of a basic block is defined to be the maximum
178 /// of all the instruction weights in that block.
179 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000180
181 /// \brief Map edges to their computed weights.
182 ///
183 /// Edge weights are computed by propagating basic block weights in
184 /// SampleProfile::propagateWeights.
185 EdgeWeightMap EdgeWeights;
186
187 /// \brief Set of visited blocks during propagation.
188 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
189
190 /// \brief Set of visited edges during propagation.
191 SmallSet<Edge, 128> VisitedEdges;
192
193 /// \brief Equivalence classes for block weights.
194 ///
195 /// Two blocks BB1 and BB2 are in the same equivalence class if they
196 /// dominate and post-dominate each other, and they are in the same loop
197 /// nest. When this happens, the two blocks are guaranteed to execute
198 /// the same number of times.
199 EquivalenceClassMap EquivalenceClass;
200
201 /// \brief Dominance, post-dominance and loop information.
202 DominatorTree *DT;
203 PostDominatorTree *PDT;
204 LoopInfo *LI;
205
206 /// \brief Predecessors for each basic block in the CFG.
207 BlockEdgeMap Predecessors;
208
209 /// \brief Successors for each basic block in the CFG.
210 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000211
212 /// \brief LLVM context holding the debug data we need.
213 LLVMContext *Ctx;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000214};
215
Diego Novillo8d6568b2013-11-13 12:22:21 +0000216/// \brief Sample-based profile reader.
217///
218/// Each profile contains sample counts for all the functions
219/// executed. Inside each function, statements are annotated with the
220/// collected samples on all the instructions associated with that
221/// statement.
222///
223/// For this to produce meaningful data, the program needs to be
224/// compiled with some debug information (at minimum, line numbers:
225/// -gline-tables-only). Otherwise, it will be impossible to match IR
226/// instructions to the line numbers collected by the profiler.
227///
228/// From the profile file, we are interested in collecting the
229/// following information:
230///
231/// * A list of functions included in the profile (mangled names).
232///
233/// * For each function F:
234/// 1. The total number of samples collected in F.
235///
236/// 2. The samples collected at each line in F. To provide some
237/// protection against source code shuffling, line numbers should
238/// be relative to the start of the function.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000239class SampleModuleProfile {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000240public:
Diego Novilloc0dd1032013-11-26 20:37:33 +0000241 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000242
Alexey Samsonovaa19c0a2013-11-13 13:09:39 +0000243 void dump();
244 void loadText();
245 void loadNative() { llvm_unreachable("not implemented"); }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000246 void printFunctionProfile(raw_ostream &OS, StringRef FName);
247 void dumpFunctionProfile(StringRef FName);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000248 SampleFunctionProfile &getProfile(const Function &F) {
249 return Profiles[F.getName()];
250 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000251
Diego Novillo9518b632014-01-10 23:23:51 +0000252 /// \brief Report a parse error message and stop compilation.
253 void reportParseError(int64_t LineNumber, Twine Msg) const {
254 report_fatal_error(Filename + ":" + Twine(LineNumber) + ": " + Msg + "\n");
255 }
256
Diego Novillo8d6568b2013-11-13 12:22:21 +0000257protected:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000258 /// \brief Map every function to its associated profile.
259 ///
260 /// The profile of every function executed at runtime is collected
Diego Novilloc0dd1032013-11-26 20:37:33 +0000261 /// in the structure SampleFunctionProfile. This maps function objects
Diego Novillo8d6568b2013-11-13 12:22:21 +0000262 /// to their corresponding profiles.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000263 StringMap<SampleFunctionProfile> Profiles;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000264
265 /// \brief Path name to the file holding the profile data.
266 ///
267 /// The format of this file is defined by each profiler
268 /// independently. If possible, the profiler should have a text
269 /// version of the profile format to be used in constructing test
270 /// cases and debugging.
271 StringRef Filename;
272};
273
Diego Novillo8d6568b2013-11-13 12:22:21 +0000274/// \brief Sample profile pass.
275///
276/// This pass reads profile data from the file specified by
277/// -sample-profile-file and annotates every affected function with the
278/// profile information found in that file.
279class SampleProfileLoader : public FunctionPass {
280public:
281 // Class identification, replacement for typeinfo
282 static char ID;
283
284 SampleProfileLoader(StringRef Name = SampleProfileFile)
Ahmed Charles56440fd2014-03-06 05:51:42 +0000285 : FunctionPass(ID), Profiler(), Filename(Name) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000286 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
287 }
288
Craig Topper3e4c6972014-03-05 09:10:37 +0000289 bool doInitialization(Module &M) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000290
291 void dump() { Profiler->dump(); }
292
Craig Topper3e4c6972014-03-05 09:10:37 +0000293 const char *getPassName() const override { return "Sample profile pass"; }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000294
Craig Topper3e4c6972014-03-05 09:10:37 +0000295 bool runOnFunction(Function &F) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000296
Craig Topper3e4c6972014-03-05 09:10:37 +0000297 void getAnalysisUsage(AnalysisUsage &AU) const override {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000298 AU.setPreservesCFG();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000299 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000300 AU.addRequired<DominatorTreeWrapperPass>();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000301 AU.addRequired<PostDominatorTree>();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000302 }
303
304protected:
305 /// \brief Profile reader object.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000306 std::unique_ptr<SampleModuleProfile> Profiler;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000307
308 /// \brief Name of the profile file to load.
309 StringRef Filename;
310};
311}
312
Diego Novilloc0dd1032013-11-26 20:37:33 +0000313/// \brief Print this function profile on stream \p OS.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000314///
315/// \param OS Stream to emit the output to.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000316void SampleFunctionProfile::print(raw_ostream &OS) {
317 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
Diego Novillo8d6568b2013-11-13 12:22:21 +0000318 << " sampled lines\n";
Diego Novilloc0dd1032013-11-26 20:37:33 +0000319 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
320 SE = BodySamples.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000321 SI != SE; ++SI)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000322 OS << "\tline offset: " << SI->first.LineOffset
323 << ", discriminator: " << SI->first.Discriminator
Diego Novillo8d6568b2013-11-13 12:22:21 +0000324 << ", number of samples: " << SI->second << "\n";
325 OS << "\n";
326}
327
Diego Novillo0accb3d2014-01-10 23:23:46 +0000328/// \brief Print the weight of edge \p E on stream \p OS.
329///
330/// \param OS Stream to emit the output to.
331/// \param E Edge to print.
332void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
333 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
334 << "]: " << EdgeWeights[E] << "\n";
335}
336
337/// \brief Print the equivalence class of block \p BB on stream \p OS.
338///
339/// \param OS Stream to emit the output to.
340/// \param BB Block to print.
341void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
342 BasicBlock *BB) {
343 BasicBlock *Equiv = EquivalenceClass[BB];
344 OS << "equivalence[" << BB->getName()
345 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
346}
347
348/// \brief Print the weight of block \p BB on stream \p OS.
349///
350/// \param OS Stream to emit the output to.
351/// \param BB Block to print.
352void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
353 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
354}
355
Diego Novilloc0dd1032013-11-26 20:37:33 +0000356/// \brief Print the function profile for \p FName on stream \p OS.
357///
358/// \param OS Stream to emit the output to.
359/// \param FName Name of the function to print.
360void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
361 StringRef FName) {
362 OS << "Function: " << FName << ":\n";
363 Profiles[FName].print(OS);
364}
365
Diego Novillo8d6568b2013-11-13 12:22:21 +0000366/// \brief Dump the function profile for \p FName.
367///
368/// \param FName Name of the function to print.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000369void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000370 printFunctionProfile(dbgs(), FName);
371}
372
373/// \brief Dump all the function profiles found.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000374void SampleModuleProfile::dump() {
375 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
376 E = Profiles.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000377 I != E; ++I)
378 dumpFunctionProfile(I->getKey());
379}
380
381/// \brief Load samples from a text file.
382///
Diego Novillo9518b632014-01-10 23:23:51 +0000383/// The file contains a list of samples for every function executed at
384/// runtime. Each function profile has the following format:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000385///
Diego Novillo9518b632014-01-10 23:23:51 +0000386/// function1:total_samples:total_head_samples
387/// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
388/// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000389/// ...
Diego Novillo9518b632014-01-10 23:23:51 +0000390/// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000391///
392/// Function names must be mangled in order for the profile loader to
Diego Novillo9518b632014-01-10 23:23:51 +0000393/// match them in the current translation unit. The two numbers in the
394/// function header specify how many total samples were accumulated in
395/// the function (first number), and the total number of samples accumulated
396/// at the prologue of the function (second number). This head sample
397/// count provides an indicator of how frequent is the function invoked.
398///
399/// Each sampled line may contain several items. Some are optional
400/// (marked below):
401///
402/// a- Source line offset. This number represents the line number
403/// in the function where the sample was collected. The line number
404/// is always relative to the line where symbol of the function
405/// is defined. So, if the function has its header at line 280,
406/// the offset 13 is at line 293 in the file.
407///
408/// b- [OPTIONAL] Discriminator. This is used if the sampled program
409/// was compiled with DWARF discriminator support
410/// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators)
Diego Novillo9518b632014-01-10 23:23:51 +0000411///
412/// c- Number of samples. This is the number of samples collected by
413/// the profiler at this source location.
414///
415/// d- [OPTIONAL] Potential call targets and samples. If present, this
416/// line contains a call instruction. This models both direct and
417/// indirect calls. Each called target is listed together with the
418/// number of samples. For example,
419///
420/// 130: 7 foo:3 bar:2 baz:7
421///
422/// The above means that at relative line offset 130 there is a
423/// call instruction that calls one of foo(), bar() and baz(). With
424/// baz() being the relatively more frequent call target.
425///
426/// FIXME: This is currently unhandled, but it has a lot of
427/// potential for aiding the inliner.
428///
Diego Novillo8d6568b2013-11-13 12:22:21 +0000429///
430/// Since this is a flat profile, a function that shows up more than
431/// once gets all its samples aggregated across all its instances.
Diego Novillo9518b632014-01-10 23:23:51 +0000432///
433/// FIXME: flat profiles are too imprecise to provide good optimization
434/// opportunities. Convert them to context-sensitive profile.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000435///
436/// This textual representation is useful to generate unit tests and
437/// for debugging purposes, but it should not be used to generate
438/// profiles for large programs, as the representation is extremely
439/// inefficient.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000440void SampleModuleProfile::loadText() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000441 std::unique_ptr<MemoryBuffer> Buffer;
Diego Novillo9518b632014-01-10 23:23:51 +0000442 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
443 if (EC)
444 report_fatal_error("Could not open file " + Filename + ": " + EC.message());
445 line_iterator LineIt(*Buffer, '#');
Diego Novillo8d6568b2013-11-13 12:22:21 +0000446
447 // Read the profile of each function. Since each function may be
448 // mentioned more than once, and we are collecting flat profiles,
449 // accumulate samples as we parse them.
Diego Novillo9518b632014-01-10 23:23:51 +0000450 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+)$");
Diego Novillo92aa8c22014-03-10 22:41:28 +0000451 Regex LineSample("^([0-9]+)\\.?([0-9]+)?: ([0-9]+)(.*)$");
Diego Novillo9518b632014-01-10 23:23:51 +0000452 while (!LineIt.is_at_eof()) {
453 // Read the header of each function. The function header should
454 // have this format:
455 //
456 // function_name:total_samples:total_head_samples
457 //
458 // See above for an explanation of each field.
459 SmallVector<StringRef, 3> Matches;
460 if (!HeadRE.match(*LineIt, &Matches))
461 reportParseError(LineIt.line_number(),
462 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
463 assert(Matches.size() == 4);
Diego Novillo8d6568b2013-11-13 12:22:21 +0000464 StringRef FName = Matches[1];
Diego Novillo9518b632014-01-10 23:23:51 +0000465 unsigned NumSamples, NumHeadSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000466 Matches[2].getAsInteger(10, NumSamples);
467 Matches[3].getAsInteger(10, NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000468 Profiles[FName] = SampleFunctionProfile();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000469 SampleFunctionProfile &FProfile = Profiles[FName];
470 FProfile.addTotalSamples(NumSamples);
471 FProfile.addHeadSamples(NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000472 ++LineIt;
473
474 // Now read the body. The body of the function ends when we reach
475 // EOF or when we see the start of the next function.
476 while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
477 if (!LineSample.match(*LineIt, &Matches))
478 reportParseError(
479 LineIt.line_number(),
480 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
481 assert(Matches.size() == 5);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000482 unsigned LineOffset, NumSamples, Discriminator = 0;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000483 Matches[1].getAsInteger(10, LineOffset);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000484 if (Matches[2] != "")
485 Matches[2].getAsInteger(10, Discriminator);
Diego Novillo9518b632014-01-10 23:23:51 +0000486 Matches[3].getAsInteger(10, NumSamples);
487
488 // FIXME: Handle called targets (in Matches[4]).
489
Diego Novillo0accb3d2014-01-10 23:23:46 +0000490 // When dealing with instruction weights, we use the value
491 // zero to indicate the absence of a sample. If we read an
492 // actual zero from the profile file, return it as 1 to
493 // avoid the confusion later on.
494 if (NumSamples == 0)
495 NumSamples = 1;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000496 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000497 ++LineIt;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000498 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000499 }
500}
501
Diego Novillo0accb3d2014-01-10 23:23:46 +0000502/// \brief Get the weight for an instruction.
503///
504/// The "weight" of an instruction \p Inst is the number of samples
505/// collected on that instruction at runtime. To retrieve it, we
506/// need to compute the line number of \p Inst relative to the start of its
507/// function. We use HeaderLineno to compute the offset. We then
508/// look up the samples collected for \p Inst using BodySamples.
509///
510/// \param Inst Instruction to query.
511///
512/// \returns The profiled weight of I.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000513unsigned SampleFunctionProfile::getInstWeight(Instruction &Inst) {
514 DebugLoc DLoc = Inst.getDebugLoc();
515 unsigned Lineno = DLoc.getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000516 if (Lineno < HeaderLineno)
517 return 0;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000518
519 DILocation DIL(DLoc.getAsMDNode(*Ctx));
520 int LOffset = Lineno - HeaderLineno;
521 unsigned Discriminator = DIL.getDiscriminator();
522 unsigned Weight =
523 BodySamples.lookup(InstructionLocation(LOffset, Discriminator));
524 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst
525 << " (line offset: " << LOffset << "." << Discriminator
Diego Novillo0accb3d2014-01-10 23:23:46 +0000526 << " - weight: " << Weight << ")\n");
527 return Weight;
528}
529
530/// \brief Compute the weight of a basic block.
531///
532/// The weight of basic block \p B is the maximum weight of all the
533/// instructions in B. The weight of \p B is computed and cached in
534/// the BlockWeights map.
535///
536/// \param B The basic block to query.
537///
538/// \returns The computed weight of B.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000539unsigned SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000540 // If we've computed B's weight before, return it.
541 std::pair<BlockWeightMap::iterator, bool> Entry =
542 BlockWeights.insert(std::make_pair(B, 0));
543 if (!Entry.second)
544 return Entry.first->second;
545
546 // Otherwise, compute and cache B's weight.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000547 unsigned Weight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000548 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000549 unsigned InstWeight = getInstWeight(*I);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000550 if (InstWeight > Weight)
551 Weight = InstWeight;
552 }
553 Entry.first->second = Weight;
554 return Weight;
555}
556
557/// \brief Compute and store the weights of every basic block.
558///
559/// This populates the BlockWeights map by computing
560/// the weights of every basic block in the CFG.
561///
562/// \param F The function to query.
563bool SampleFunctionProfile::computeBlockWeights(Function &F) {
564 bool Changed = false;
565 DEBUG(dbgs() << "Block weights\n");
566 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000567 unsigned Weight = getBlockWeight(B);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000568 Changed |= (Weight > 0);
569 DEBUG(printBlockWeight(dbgs(), B));
570 }
571
572 return Changed;
573}
574
575/// \brief Find equivalence classes for the given block.
576///
577/// This finds all the blocks that are guaranteed to execute the same
578/// number of times as \p BB1. To do this, it traverses all the the
579/// descendants of \p BB1 in the dominator or post-dominator tree.
580///
581/// A block BB2 will be in the same equivalence class as \p BB1 if
582/// the following holds:
583///
584/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
585/// is a descendant of \p BB1 in the dominator tree, then BB2 should
586/// dominate BB1 in the post-dominator tree.
587///
588/// 2- Both BB2 and \p BB1 must be in the same loop.
589///
590/// For every block BB2 that meets those two requirements, we set BB2's
591/// equivalence class to \p BB1.
592///
593/// \param BB1 Block to check.
594/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
595/// \param DomTree Opposite dominator tree. If \p Descendants is filled
596/// with blocks from \p BB1's dominator tree, then
597/// this is the post-dominator tree, and vice versa.
598void SampleFunctionProfile::findEquivalencesFor(
599 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
600 DominatorTreeBase<BasicBlock> *DomTree) {
601 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(),
602 E = Descendants.end();
603 I != E; ++I) {
604 BasicBlock *BB2 = *I;
605 bool IsDomParent = DomTree->dominates(BB2, BB1);
606 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
607 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
608 IsInSameLoop) {
609 EquivalenceClass[BB2] = BB1;
610
611 // If BB2 is heavier than BB1, make BB2 have the same weight
612 // as BB1.
613 //
614 // Note that we don't worry about the opposite situation here
615 // (when BB2 is lighter than BB1). We will deal with this
616 // during the propagation phase. Right now, we just want to
617 // make sure that BB1 has the largest weight of all the
618 // members of its equivalence set.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000619 unsigned &BB1Weight = BlockWeights[BB1];
620 unsigned &BB2Weight = BlockWeights[BB2];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000621 BB1Weight = std::max(BB1Weight, BB2Weight);
622 }
623 }
624}
625
626/// \brief Find equivalence classes.
627///
628/// Since samples may be missing from blocks, we can fill in the gaps by setting
629/// the weights of all the blocks in the same equivalence class to the same
630/// weight. To compute the concept of equivalence, we use dominance and loop
631/// information. Two blocks B1 and B2 are in the same equivalence class if B1
632/// dominates B2, B2 post-dominates B1 and both are in the same loop.
633///
634/// \param F The function to query.
635void SampleFunctionProfile::findEquivalenceClasses(Function &F) {
636 SmallVector<BasicBlock *, 8> DominatedBBs;
637 DEBUG(dbgs() << "\nBlock equivalence classes\n");
638 // Find equivalence sets based on dominance and post-dominance information.
639 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
640 BasicBlock *BB1 = B;
641
642 // Compute BB1's equivalence class once.
643 if (EquivalenceClass.count(BB1)) {
644 DEBUG(printBlockEquivalence(dbgs(), BB1));
645 continue;
646 }
647
648 // By default, blocks are in their own equivalence class.
649 EquivalenceClass[BB1] = BB1;
650
651 // Traverse all the blocks dominated by BB1. We are looking for
652 // every basic block BB2 such that:
653 //
654 // 1- BB1 dominates BB2.
655 // 2- BB2 post-dominates BB1.
656 // 3- BB1 and BB2 are in the same loop nest.
657 //
658 // If all those conditions hold, it means that BB2 is executed
659 // as many times as BB1, so they are placed in the same equivalence
660 // class by making BB2's equivalence class be BB1.
661 DominatedBBs.clear();
662 DT->getDescendants(BB1, DominatedBBs);
663 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
664
665 // Repeat the same logic for all the blocks post-dominated by BB1.
666 // We are looking for every basic block BB2 such that:
667 //
668 // 1- BB1 post-dominates BB2.
669 // 2- BB2 dominates BB1.
670 // 3- BB1 and BB2 are in the same loop nest.
671 //
672 // If all those conditions hold, BB2's equivalence class is BB1.
673 DominatedBBs.clear();
674 PDT->getDescendants(BB1, DominatedBBs);
Chandler Carruth73523022014-01-13 13:07:17 +0000675 findEquivalencesFor(BB1, DominatedBBs, DT);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000676
677 DEBUG(printBlockEquivalence(dbgs(), BB1));
678 }
679
680 // Assign weights to equivalence classes.
681 //
682 // All the basic blocks in the same equivalence class will execute
683 // the same number of times. Since we know that the head block in
684 // each equivalence class has the largest weight, assign that weight
685 // to all the blocks in that equivalence class.
686 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
687 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
688 BasicBlock *BB = B;
689 BasicBlock *EquivBB = EquivalenceClass[BB];
690 if (BB != EquivBB)
691 BlockWeights[BB] = BlockWeights[EquivBB];
692 DEBUG(printBlockWeight(dbgs(), BB));
693 }
694}
695
696/// \brief Visit the given edge to decide if it has a valid weight.
697///
698/// If \p E has not been visited before, we copy to \p UnknownEdge
699/// and increment the count of unknown edges.
700///
701/// \param E Edge to visit.
702/// \param NumUnknownEdges Current number of unknown edges.
703/// \param UnknownEdge Set if E has not been visited before.
704///
705/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000706unsigned SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000707 Edge *UnknownEdge) {
708 if (!VisitedEdges.count(E)) {
709 (*NumUnknownEdges)++;
710 *UnknownEdge = E;
711 return 0;
712 }
713
714 return EdgeWeights[E];
715}
716
717/// \brief Propagate weights through incoming/outgoing edges.
718///
719/// If the weight of a basic block is known, and there is only one edge
720/// with an unknown weight, we can calculate the weight of that edge.
721///
722/// Similarly, if all the edges have a known count, we can calculate the
723/// count of the basic block, if needed.
724///
725/// \param F Function to process.
726///
727/// \returns True if new weights were assigned to edges or blocks.
728bool SampleFunctionProfile::propagateThroughEdges(Function &F) {
729 bool Changed = false;
730 DEBUG(dbgs() << "\nPropagation through edges\n");
731 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
732 BasicBlock *BB = BI;
733
734 // Visit all the predecessor and successor edges to determine
735 // which ones have a weight assigned already. Note that it doesn't
736 // matter that we only keep track of a single unknown edge. The
737 // only case we are interested in handling is when only a single
738 // edge is unknown (see setEdgeOrBlockWeight).
739 for (unsigned i = 0; i < 2; i++) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000740 unsigned TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000741 unsigned NumUnknownEdges = 0;
742 Edge UnknownEdge, SelfReferentialEdge;
743
744 if (i == 0) {
745 // First, visit all predecessor edges.
746 for (size_t I = 0; I < Predecessors[BB].size(); I++) {
747 Edge E = std::make_pair(Predecessors[BB][I], BB);
748 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
749 if (E.first == E.second)
750 SelfReferentialEdge = E;
751 }
752 } else {
753 // On the second round, visit all successor edges.
754 for (size_t I = 0; I < Successors[BB].size(); I++) {
755 Edge E = std::make_pair(BB, Successors[BB][I]);
756 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
757 }
758 }
759
760 // After visiting all the edges, there are three cases that we
761 // can handle immediately:
762 //
763 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
764 // In this case, we simply check that the sum of all the edges
765 // is the same as BB's weight. If not, we change BB's weight
766 // to match. Additionally, if BB had not been visited before,
767 // we mark it visited.
768 //
769 // - Only one edge is unknown and BB has already been visited.
770 // In this case, we can compute the weight of the edge by
771 // subtracting the total block weight from all the known
772 // edge weights. If the edges weight more than BB, then the
773 // edge of the last remaining edge is set to zero.
774 //
775 // - There exists a self-referential edge and the weight of BB is
776 // known. In this case, this edge can be based on BB's weight.
777 // We add up all the other known edges and set the weight on
778 // the self-referential edge as we did in the previous case.
779 //
780 // In any other case, we must continue iterating. Eventually,
781 // all edges will get a weight, or iteration will stop when
782 // it reaches SampleProfileMaxPropagateIterations.
783 if (NumUnknownEdges <= 1) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000784 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000785 if (NumUnknownEdges == 0) {
786 // If we already know the weight of all edges, the weight of the
787 // basic block can be computed. It should be no larger than the sum
788 // of all edge weights.
789 if (TotalWeight > BBWeight) {
790 BBWeight = TotalWeight;
791 Changed = true;
792 DEBUG(dbgs() << "All edge weights for " << BB->getName()
793 << " known. Set weight for block: ";
794 printBlockWeight(dbgs(), BB););
795 }
796 if (VisitedBlocks.insert(BB))
797 Changed = true;
798 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
799 // If there is a single unknown edge and the block has been
800 // visited, then we can compute E's weight.
801 if (BBWeight >= TotalWeight)
802 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
803 else
804 EdgeWeights[UnknownEdge] = 0;
805 VisitedEdges.insert(UnknownEdge);
806 Changed = true;
807 DEBUG(dbgs() << "Set weight for edge: ";
808 printEdgeWeight(dbgs(), UnknownEdge));
809 }
810 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000811 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000812 // We have a self-referential edge and the weight of BB is known.
813 if (BBWeight >= TotalWeight)
814 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
815 else
816 EdgeWeights[SelfReferentialEdge] = 0;
817 VisitedEdges.insert(SelfReferentialEdge);
818 Changed = true;
819 DEBUG(dbgs() << "Set self-referential edge weight to: ";
820 printEdgeWeight(dbgs(), SelfReferentialEdge));
821 }
822 }
823 }
824
825 return Changed;
826}
827
828/// \brief Build in/out edge lists for each basic block in the CFG.
829///
830/// We are interested in unique edges. If a block B1 has multiple
831/// edges to another block B2, we only add a single B1->B2 edge.
832void SampleFunctionProfile::buildEdges(Function &F) {
833 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
834 BasicBlock *B1 = I;
835
836 // Add predecessors for B1.
837 SmallPtrSet<BasicBlock *, 16> Visited;
838 if (!Predecessors[B1].empty())
839 llvm_unreachable("Found a stale predecessors list in a basic block.");
840 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
841 BasicBlock *B2 = *PI;
842 if (Visited.insert(B2))
843 Predecessors[B1].push_back(B2);
844 }
845
846 // Add successors for B1.
847 Visited.clear();
848 if (!Successors[B1].empty())
849 llvm_unreachable("Found a stale successors list in a basic block.");
850 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
851 BasicBlock *B2 = *SI;
852 if (Visited.insert(B2))
853 Successors[B1].push_back(B2);
854 }
855 }
856}
857
858/// \brief Propagate weights into edges
859///
860/// The following rules are applied to every block B in the CFG:
861///
862/// - If B has a single predecessor/successor, then the weight
863/// of that edge is the weight of the block.
864///
865/// - If all incoming or outgoing edges are known except one, and the
866/// weight of the block is already known, the weight of the unknown
867/// edge will be the weight of the block minus the sum of all the known
868/// edges. If the sum of all the known edges is larger than B's weight,
869/// we set the unknown edge weight to zero.
870///
871/// - If there is a self-referential edge, and the weight of the block is
872/// known, the weight for that edge is set to the weight of the block
873/// minus the weight of the other incoming edges to that block (if
874/// known).
875void SampleFunctionProfile::propagateWeights(Function &F) {
876 bool Changed = true;
877 unsigned i = 0;
878
879 // Before propagation starts, build, for each block, a list of
880 // unique predecessors and successors. This is necessary to handle
881 // identical edges in multiway branches. Since we visit all blocks and all
882 // edges of the CFG, it is cleaner to build these lists once at the start
883 // of the pass.
884 buildEdges(F);
885
886 // Propagate until we converge or we go past the iteration limit.
887 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
888 Changed = propagateThroughEdges(F);
889 }
890
891 // Generate MD_prof metadata for every branch instruction using the
892 // edge weights computed during propagation.
893 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
894 MDBuilder MDB(F.getContext());
895 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
896 BasicBlock *B = I;
897 TerminatorInst *TI = B->getTerminator();
898 if (TI->getNumSuccessors() == 1)
899 continue;
900 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
901 continue;
902
903 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000904 << TI->getDebugLoc().getLine() << ".\n");
905 SmallVector<unsigned, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000906 bool AllWeightsZero = true;
907 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
908 BasicBlock *Succ = TI->getSuccessor(I);
909 Edge E = std::make_pair(B, Succ);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000910 unsigned Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000911 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
912 Weights.push_back(Weight);
913 if (Weight != 0)
914 AllWeightsZero = false;
915 }
916
917 // Only set weights if there is at least one non-zero weight.
918 // In any other case, let the analyzer set weights.
919 if (!AllWeightsZero) {
920 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
921 TI->setMetadata(llvm::LLVMContext::MD_prof,
922 MDB.createBranchWeights(Weights));
923 } else {
924 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
925 }
926 }
927}
928
929/// \brief Get the line number for the function header.
930///
931/// This looks up function \p F in the current compilation unit and
932/// retrieves the line number where the function is defined. This is
933/// line 0 for all the samples read from the profile file. Every line
934/// number is relative to this line.
935///
936/// \param F Function object to query.
937///
938/// \returns the line number where \p F is defined.
939unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
940 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
941 if (CUNodes) {
942 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) {
943 DICompileUnit CU(CUNodes->getOperand(I));
944 DIArray Subprograms = CU.getSubprograms();
945 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) {
946 DISubprogram Subprogram(Subprograms.getElement(J));
947 if (Subprogram.describes(&F))
948 return Subprogram.getLineNumber();
949 }
950 }
951 }
952
953 report_fatal_error("No debug information found in function " + F.getName() +
954 "\n");
955}
956
957/// \brief Generate branch weight metadata for all branches in \p F.
958///
959/// Branch weights are computed out of instruction samples using a
960/// propagation heuristic. Propagation proceeds in 3 phases:
961///
962/// 1- Assignment of block weights. All the basic blocks in the function
963/// are initial assigned the same weight as their most frequently
964/// executed instruction.
965///
966/// 2- Creation of equivalence classes. Since samples may be missing from
967/// blocks, we can fill in the gaps by setting the weights of all the
968/// blocks in the same equivalence class to the same weight. To compute
969/// the concept of equivalence, we use dominance and loop information.
970/// Two blocks B1 and B2 are in the same equivalence class if B1
971/// dominates B2, B2 post-dominates B1 and both are in the same loop.
972///
973/// 3- Propagation of block weights into edges. This uses a simple
974/// propagation heuristic. The following rules are applied to every
975/// block B in the CFG:
976///
977/// - If B has a single predecessor/successor, then the weight
978/// of that edge is the weight of the block.
979///
980/// - If all the edges are known except one, and the weight of the
981/// block is already known, the weight of the unknown edge will
982/// be the weight of the block minus the sum of all the known
983/// edges. If the sum of all the known edges is larger than B's weight,
984/// we set the unknown edge weight to zero.
985///
986/// - If there is a self-referential edge, and the weight of the block is
987/// known, the weight for that edge is set to the weight of the block
988/// minus the weight of the other incoming edges to that block (if
989/// known).
990///
991/// Since this propagation is not guaranteed to finalize for every CFG, we
992/// only allow it to proceed for a limited number of iterations (controlled
993/// by -sample-profile-max-propagate-iterations).
994///
995/// FIXME: Try to replace this propagation heuristic with a scheme
996/// that is guaranteed to finalize. A work-list approach similar to
997/// the standard value propagation algorithm used by SSA-CCP might
998/// work here.
999///
1000/// Once all the branch weights are computed, we emit the MD_prof
1001/// metadata on B using the computed values for each of its branches.
1002///
1003/// \param F The function to query.
1004bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
1005 PostDominatorTree *PostDomTree,
1006 LoopInfo *Loops) {
1007 bool Changed = false;
1008
1009 // Initialize invariants used during computation and propagation.
1010 HeaderLineno = getFunctionLoc(F);
1011 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1012 << ": " << HeaderLineno << "\n");
1013 DT = DomTree;
1014 PDT = PostDomTree;
1015 LI = Loops;
Diego Novillo92aa8c22014-03-10 22:41:28 +00001016 Ctx = &F.getParent()->getContext();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001017
1018 // Compute basic block weights.
1019 Changed |= computeBlockWeights(F);
1020
1021 if (Changed) {
1022 // Find equivalence classes.
1023 findEquivalenceClasses(F);
1024
1025 // Propagate weights to all edges.
1026 propagateWeights(F);
1027 }
1028
1029 return Changed;
1030}
1031
Diego Novilloc0dd1032013-11-26 20:37:33 +00001032char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001033INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1034 "Sample Profile loader", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +00001035INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001036INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
1037INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Diego Novillo92aa8c22014-03-10 22:41:28 +00001038INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001039INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1040 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001041
1042bool SampleProfileLoader::doInitialization(Module &M) {
1043 Profiler.reset(new SampleModuleProfile(Filename));
1044 Profiler->loadText();
1045 return true;
1046}
1047
1048FunctionPass *llvm::createSampleProfileLoaderPass() {
1049 return new SampleProfileLoader(SampleProfileFile);
1050}
1051
1052FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1053 return new SampleProfileLoader(Name);
1054}
1055
Diego Novillo8d6568b2013-11-13 12:22:21 +00001056bool SampleProfileLoader::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +00001057 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001058 PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
1059 LoopInfo *LI = &getAnalysis<LoopInfo>();
1060 SampleFunctionProfile &FunctionProfile = Profiler->getProfile(F);
1061 if (!FunctionProfile.empty())
1062 return FunctionProfile.emitAnnotations(F, DT, PDT, LI);
1063 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001064}