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