1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 // This pass generates branch weight annotations on the IR:
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.
23 //===----------------------------------------------------------------------===//
25 #define DEBUG_TYPE "sample-profile"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Analysis/PostDominators.h"
36 #include "llvm/DebugInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstIterator.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/MDBuilder.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/LineIterator.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/Regex.h"
52 #include "llvm/Support/raw_ostream.h"
57 // Command line option to specify the file to read samples from. This is
58 // mainly used for debugging.
59 static cl::opt<std::string> SampleProfileFile(
60 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
61 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
62 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
63 "sample-profile-max-propagate-iterations", cl::init(100),
64 cl::desc("Maximum number of iterations to go through when propagating "
65 "sample block/edge weights through the CFG."));
69 typedef DenseMap<uint32_t, uint32_t> BodySampleMap;
70 typedef DenseMap<BasicBlock *, uint32_t> BlockWeightMap;
71 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
72 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
73 typedef DenseMap<Edge, uint32_t> EdgeWeightMap;
74 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
76 /// \brief Representation of the runtime profile for a function.
78 /// This data structure contains the runtime profile for a given
79 /// function. It contains the total number of samples collected
80 /// in the function and a map of samples collected in every statement.
81 class SampleFunctionProfile {
83 SampleFunctionProfile()
84 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
87 unsigned getFunctionLoc(Function &F);
88 bool emitAnnotations(Function &F, DominatorTree *DomTree,
89 PostDominatorTree *PostDomTree, LoopInfo *Loops);
90 uint32_t getInstWeight(Instruction &I);
91 uint32_t getBlockWeight(BasicBlock *B);
92 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
93 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
94 void addBodySamples(unsigned LineOffset, unsigned Num) {
95 BodySamples[LineOffset] += Num;
97 void print(raw_ostream &OS);
98 void printEdgeWeight(raw_ostream &OS, Edge E);
99 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
100 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
101 bool computeBlockWeights(Function &F);
102 void findEquivalenceClasses(Function &F);
103 void findEquivalencesFor(BasicBlock *BB1,
104 SmallVector<BasicBlock *, 8> Descendants,
105 DominatorTreeBase<BasicBlock> *DomTree);
106 void propagateWeights(Function &F);
107 uint32_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
108 void buildEdges(Function &F);
109 bool propagateThroughEdges(Function &F);
110 bool empty() { return BodySamples.empty(); }
113 /// \brief Total number of samples collected inside this function.
115 /// Samples are cumulative, they include all the samples collected
116 /// inside this function and all its inlined callees.
117 unsigned TotalSamples;
119 /// \brief Total number of samples collected at the head of the function.
120 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
121 unsigned TotalHeadSamples;
123 /// \brief Line number for the function header. Used to compute relative
124 /// line numbers from the absolute line LOCs found in instruction locations.
125 /// The relative line numbers are needed to address the samples from the
127 unsigned HeaderLineno;
129 /// \brief Map line offsets to collected samples.
131 /// Each entry in this map contains the number of samples
132 /// collected at the corresponding line offset. All line locations
133 /// are an offset from the start of the function.
134 BodySampleMap BodySamples;
136 /// \brief Map basic blocks to their computed weights.
138 /// The weight of a basic block is defined to be the maximum
139 /// of all the instruction weights in that block.
140 BlockWeightMap BlockWeights;
142 /// \brief Map edges to their computed weights.
144 /// Edge weights are computed by propagating basic block weights in
145 /// SampleProfile::propagateWeights.
146 EdgeWeightMap EdgeWeights;
148 /// \brief Set of visited blocks during propagation.
149 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
151 /// \brief Set of visited edges during propagation.
152 SmallSet<Edge, 128> VisitedEdges;
154 /// \brief Equivalence classes for block weights.
156 /// Two blocks BB1 and BB2 are in the same equivalence class if they
157 /// dominate and post-dominate each other, and they are in the same loop
158 /// nest. When this happens, the two blocks are guaranteed to execute
159 /// the same number of times.
160 EquivalenceClassMap EquivalenceClass;
162 /// \brief Dominance, post-dominance and loop information.
164 PostDominatorTree *PDT;
167 /// \brief Predecessors for each basic block in the CFG.
168 BlockEdgeMap Predecessors;
170 /// \brief Successors for each basic block in the CFG.
171 BlockEdgeMap Successors;
174 /// \brief Sample-based profile reader.
176 /// Each profile contains sample counts for all the functions
177 /// executed. Inside each function, statements are annotated with the
178 /// collected samples on all the instructions associated with that
181 /// For this to produce meaningful data, the program needs to be
182 /// compiled with some debug information (at minimum, line numbers:
183 /// -gline-tables-only). Otherwise, it will be impossible to match IR
184 /// instructions to the line numbers collected by the profiler.
186 /// From the profile file, we are interested in collecting the
187 /// following information:
189 /// * A list of functions included in the profile (mangled names).
191 /// * For each function F:
192 /// 1. The total number of samples collected in F.
194 /// 2. The samples collected at each line in F. To provide some
195 /// protection against source code shuffling, line numbers should
196 /// be relative to the start of the function.
197 class SampleModuleProfile {
199 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
203 void loadNative() { llvm_unreachable("not implemented"); }
204 void printFunctionProfile(raw_ostream &OS, StringRef FName);
205 void dumpFunctionProfile(StringRef FName);
206 SampleFunctionProfile &getProfile(const Function &F) {
207 return Profiles[F.getName()];
210 /// \brief Report a parse error message and stop compilation.
211 void reportParseError(int64_t LineNumber, Twine Msg) const {
212 report_fatal_error(Filename + ":" + Twine(LineNumber) + ": " + Msg + "\n");
216 /// \brief Map every function to its associated profile.
218 /// The profile of every function executed at runtime is collected
219 /// in the structure SampleFunctionProfile. This maps function objects
220 /// to their corresponding profiles.
221 StringMap<SampleFunctionProfile> Profiles;
223 /// \brief Path name to the file holding the profile data.
225 /// The format of this file is defined by each profiler
226 /// independently. If possible, the profiler should have a text
227 /// version of the profile format to be used in constructing test
228 /// cases and debugging.
232 /// \brief Sample profile pass.
234 /// This pass reads profile data from the file specified by
235 /// -sample-profile-file and annotates every affected function with the
236 /// profile information found in that file.
237 class SampleProfileLoader : public FunctionPass {
239 // Class identification, replacement for typeinfo
242 SampleProfileLoader(StringRef Name = SampleProfileFile)
243 : FunctionPass(ID), Profiler(0), Filename(Name) {
244 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
247 bool doInitialization(Module &M) override;
249 void dump() { Profiler->dump(); }
251 const char *getPassName() const override { return "Sample profile pass"; }
253 bool runOnFunction(Function &F) override;
255 void getAnalysisUsage(AnalysisUsage &AU) const override {
256 AU.setPreservesCFG();
257 AU.addRequired<LoopInfo>();
258 AU.addRequired<DominatorTreeWrapperPass>();
259 AU.addRequired<PostDominatorTree>();
263 /// \brief Profile reader object.
264 OwningPtr<SampleModuleProfile> Profiler;
266 /// \brief Name of the profile file to load.
271 /// \brief Print this function profile on stream \p OS.
273 /// \param OS Stream to emit the output to.
274 void SampleFunctionProfile::print(raw_ostream &OS) {
275 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
276 << " sampled lines\n";
277 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
278 SE = BodySamples.end();
280 OS << "\tline offset: " << SI->first
281 << ", number of samples: " << SI->second << "\n";
285 /// \brief Print the weight of edge \p E on stream \p OS.
287 /// \param OS Stream to emit the output to.
288 /// \param E Edge to print.
289 void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
290 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
291 << "]: " << EdgeWeights[E] << "\n";
294 /// \brief Print the equivalence class of block \p BB on stream \p OS.
296 /// \param OS Stream to emit the output to.
297 /// \param BB Block to print.
298 void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
300 BasicBlock *Equiv = EquivalenceClass[BB];
301 OS << "equivalence[" << BB->getName()
302 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
305 /// \brief Print the weight of block \p BB on stream \p OS.
307 /// \param OS Stream to emit the output to.
308 /// \param BB Block to print.
309 void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
310 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
313 /// \brief Print the function profile for \p FName on stream \p OS.
315 /// \param OS Stream to emit the output to.
316 /// \param FName Name of the function to print.
317 void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
319 OS << "Function: " << FName << ":\n";
320 Profiles[FName].print(OS);
323 /// \brief Dump the function profile for \p FName.
325 /// \param FName Name of the function to print.
326 void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
327 printFunctionProfile(dbgs(), FName);
330 /// \brief Dump all the function profiles found.
331 void SampleModuleProfile::dump() {
332 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
335 dumpFunctionProfile(I->getKey());
338 /// \brief Load samples from a text file.
340 /// The file contains a list of samples for every function executed at
341 /// runtime. Each function profile has the following format:
343 /// function1:total_samples:total_head_samples
344 /// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
345 /// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
347 /// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
349 /// Function names must be mangled in order for the profile loader to
350 /// match them in the current translation unit. The two numbers in the
351 /// function header specify how many total samples were accumulated in
352 /// the function (first number), and the total number of samples accumulated
353 /// at the prologue of the function (second number). This head sample
354 /// count provides an indicator of how frequent is the function invoked.
356 /// Each sampled line may contain several items. Some are optional
359 /// a- Source line offset. This number represents the line number
360 /// in the function where the sample was collected. The line number
361 /// is always relative to the line where symbol of the function
362 /// is defined. So, if the function has its header at line 280,
363 /// the offset 13 is at line 293 in the file.
365 /// b- [OPTIONAL] Discriminator. This is used if the sampled program
366 /// was compiled with DWARF discriminator support
367 /// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators)
368 /// This is currently only emitted by GCC and we just ignore it.
370 /// FIXME: Handle discriminators, since they are needed to distinguish
371 /// multiple control flow within a single source LOC.
373 /// c- Number of samples. This is the number of samples collected by
374 /// the profiler at this source location.
376 /// d- [OPTIONAL] Potential call targets and samples. If present, this
377 /// line contains a call instruction. This models both direct and
378 /// indirect calls. Each called target is listed together with the
379 /// number of samples. For example,
381 /// 130: 7 foo:3 bar:2 baz:7
383 /// The above means that at relative line offset 130 there is a
384 /// call instruction that calls one of foo(), bar() and baz(). With
385 /// baz() being the relatively more frequent call target.
387 /// FIXME: This is currently unhandled, but it has a lot of
388 /// potential for aiding the inliner.
391 /// Since this is a flat profile, a function that shows up more than
392 /// once gets all its samples aggregated across all its instances.
394 /// FIXME: flat profiles are too imprecise to provide good optimization
395 /// opportunities. Convert them to context-sensitive profile.
397 /// This textual representation is useful to generate unit tests and
398 /// for debugging purposes, but it should not be used to generate
399 /// profiles for large programs, as the representation is extremely
401 void SampleModuleProfile::loadText() {
402 OwningPtr<MemoryBuffer> Buffer;
403 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
405 report_fatal_error("Could not open file " + Filename + ": " + EC.message());
406 line_iterator LineIt(*Buffer, '#');
408 // Read the profile of each function. Since each function may be
409 // mentioned more than once, and we are collecting flat profiles,
410 // accumulate samples as we parse them.
411 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+)$");
412 Regex LineSample("^([0-9]+)(\\.[0-9]+)?: ([0-9]+)(.*)$");
413 while (!LineIt.is_at_eof()) {
414 // Read the header of each function. The function header should
417 // function_name:total_samples:total_head_samples
419 // See above for an explanation of each field.
420 SmallVector<StringRef, 3> Matches;
421 if (!HeadRE.match(*LineIt, &Matches))
422 reportParseError(LineIt.line_number(),
423 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
424 assert(Matches.size() == 4);
425 StringRef FName = Matches[1];
426 unsigned NumSamples, NumHeadSamples;
427 Matches[2].getAsInteger(10, NumSamples);
428 Matches[3].getAsInteger(10, NumHeadSamples);
429 Profiles[FName] = SampleFunctionProfile();
430 SampleFunctionProfile &FProfile = Profiles[FName];
431 FProfile.addTotalSamples(NumSamples);
432 FProfile.addHeadSamples(NumHeadSamples);
435 // Now read the body. The body of the function ends when we reach
436 // EOF or when we see the start of the next function.
437 while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
438 if (!LineSample.match(*LineIt, &Matches))
440 LineIt.line_number(),
441 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
442 assert(Matches.size() == 5);
443 unsigned LineOffset, NumSamples;
444 Matches[1].getAsInteger(10, LineOffset);
446 // FIXME: Handle discriminator information (in Matches[2]).
448 Matches[3].getAsInteger(10, NumSamples);
450 // FIXME: Handle called targets (in Matches[4]).
452 // When dealing with instruction weights, we use the value
453 // zero to indicate the absence of a sample. If we read an
454 // actual zero from the profile file, return it as 1 to
455 // avoid the confusion later on.
458 FProfile.addBodySamples(LineOffset, NumSamples);
464 /// \brief Get the weight for an instruction.
466 /// The "weight" of an instruction \p Inst is the number of samples
467 /// collected on that instruction at runtime. To retrieve it, we
468 /// need to compute the line number of \p Inst relative to the start of its
469 /// function. We use HeaderLineno to compute the offset. We then
470 /// look up the samples collected for \p Inst using BodySamples.
472 /// \param Inst Instruction to query.
474 /// \returns The profiled weight of I.
475 uint32_t SampleFunctionProfile::getInstWeight(Instruction &Inst) {
476 unsigned Lineno = Inst.getDebugLoc().getLine();
477 if (Lineno < HeaderLineno)
479 unsigned LOffset = Lineno - HeaderLineno;
480 uint32_t Weight = BodySamples.lookup(LOffset);
481 DEBUG(dbgs() << " " << Lineno << ":" << Inst.getDebugLoc().getCol() << ":"
482 << Inst << " (line offset: " << LOffset
483 << " - weight: " << Weight << ")\n");
487 /// \brief Compute the weight of a basic block.
489 /// The weight of basic block \p B is the maximum weight of all the
490 /// instructions in B. The weight of \p B is computed and cached in
491 /// the BlockWeights map.
493 /// \param B The basic block to query.
495 /// \returns The computed weight of B.
496 uint32_t SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
497 // If we've computed B's weight before, return it.
498 std::pair<BlockWeightMap::iterator, bool> Entry =
499 BlockWeights.insert(std::make_pair(B, 0));
501 return Entry.first->second;
503 // Otherwise, compute and cache B's weight.
505 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
506 uint32_t InstWeight = getInstWeight(*I);
507 if (InstWeight > Weight)
510 Entry.first->second = Weight;
514 /// \brief Compute and store the weights of every basic block.
516 /// This populates the BlockWeights map by computing
517 /// the weights of every basic block in the CFG.
519 /// \param F The function to query.
520 bool SampleFunctionProfile::computeBlockWeights(Function &F) {
521 bool Changed = false;
522 DEBUG(dbgs() << "Block weights\n");
523 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
524 uint32_t Weight = getBlockWeight(B);
525 Changed |= (Weight > 0);
526 DEBUG(printBlockWeight(dbgs(), B));
532 /// \brief Find equivalence classes for the given block.
534 /// This finds all the blocks that are guaranteed to execute the same
535 /// number of times as \p BB1. To do this, it traverses all the the
536 /// descendants of \p BB1 in the dominator or post-dominator tree.
538 /// A block BB2 will be in the same equivalence class as \p BB1 if
539 /// the following holds:
541 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
542 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
543 /// dominate BB1 in the post-dominator tree.
545 /// 2- Both BB2 and \p BB1 must be in the same loop.
547 /// For every block BB2 that meets those two requirements, we set BB2's
548 /// equivalence class to \p BB1.
550 /// \param BB1 Block to check.
551 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
552 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
553 /// with blocks from \p BB1's dominator tree, then
554 /// this is the post-dominator tree, and vice versa.
555 void SampleFunctionProfile::findEquivalencesFor(
556 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
557 DominatorTreeBase<BasicBlock> *DomTree) {
558 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(),
559 E = Descendants.end();
561 BasicBlock *BB2 = *I;
562 bool IsDomParent = DomTree->dominates(BB2, BB1);
563 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
564 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
566 EquivalenceClass[BB2] = BB1;
568 // If BB2 is heavier than BB1, make BB2 have the same weight
571 // Note that we don't worry about the opposite situation here
572 // (when BB2 is lighter than BB1). We will deal with this
573 // during the propagation phase. Right now, we just want to
574 // make sure that BB1 has the largest weight of all the
575 // members of its equivalence set.
576 uint32_t &BB1Weight = BlockWeights[BB1];
577 uint32_t &BB2Weight = BlockWeights[BB2];
578 BB1Weight = std::max(BB1Weight, BB2Weight);
583 /// \brief Find equivalence classes.
585 /// Since samples may be missing from blocks, we can fill in the gaps by setting
586 /// the weights of all the blocks in the same equivalence class to the same
587 /// weight. To compute the concept of equivalence, we use dominance and loop
588 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
589 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
591 /// \param F The function to query.
592 void SampleFunctionProfile::findEquivalenceClasses(Function &F) {
593 SmallVector<BasicBlock *, 8> DominatedBBs;
594 DEBUG(dbgs() << "\nBlock equivalence classes\n");
595 // Find equivalence sets based on dominance and post-dominance information.
596 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
599 // Compute BB1's equivalence class once.
600 if (EquivalenceClass.count(BB1)) {
601 DEBUG(printBlockEquivalence(dbgs(), BB1));
605 // By default, blocks are in their own equivalence class.
606 EquivalenceClass[BB1] = BB1;
608 // Traverse all the blocks dominated by BB1. We are looking for
609 // every basic block BB2 such that:
611 // 1- BB1 dominates BB2.
612 // 2- BB2 post-dominates BB1.
613 // 3- BB1 and BB2 are in the same loop nest.
615 // If all those conditions hold, it means that BB2 is executed
616 // as many times as BB1, so they are placed in the same equivalence
617 // class by making BB2's equivalence class be BB1.
618 DominatedBBs.clear();
619 DT->getDescendants(BB1, DominatedBBs);
620 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
622 // Repeat the same logic for all the blocks post-dominated by BB1.
623 // We are looking for every basic block BB2 such that:
625 // 1- BB1 post-dominates BB2.
626 // 2- BB2 dominates BB1.
627 // 3- BB1 and BB2 are in the same loop nest.
629 // If all those conditions hold, BB2's equivalence class is BB1.
630 DominatedBBs.clear();
631 PDT->getDescendants(BB1, DominatedBBs);
632 findEquivalencesFor(BB1, DominatedBBs, DT);
634 DEBUG(printBlockEquivalence(dbgs(), BB1));
637 // Assign weights to equivalence classes.
639 // All the basic blocks in the same equivalence class will execute
640 // the same number of times. Since we know that the head block in
641 // each equivalence class has the largest weight, assign that weight
642 // to all the blocks in that equivalence class.
643 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
644 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
646 BasicBlock *EquivBB = EquivalenceClass[BB];
648 BlockWeights[BB] = BlockWeights[EquivBB];
649 DEBUG(printBlockWeight(dbgs(), BB));
653 /// \brief Visit the given edge to decide if it has a valid weight.
655 /// If \p E has not been visited before, we copy to \p UnknownEdge
656 /// and increment the count of unknown edges.
658 /// \param E Edge to visit.
659 /// \param NumUnknownEdges Current number of unknown edges.
660 /// \param UnknownEdge Set if E has not been visited before.
662 /// \returns E's weight, if known. Otherwise, return 0.
663 uint32_t SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
665 if (!VisitedEdges.count(E)) {
666 (*NumUnknownEdges)++;
671 return EdgeWeights[E];
674 /// \brief Propagate weights through incoming/outgoing edges.
676 /// If the weight of a basic block is known, and there is only one edge
677 /// with an unknown weight, we can calculate the weight of that edge.
679 /// Similarly, if all the edges have a known count, we can calculate the
680 /// count of the basic block, if needed.
682 /// \param F Function to process.
684 /// \returns True if new weights were assigned to edges or blocks.
685 bool SampleFunctionProfile::propagateThroughEdges(Function &F) {
686 bool Changed = false;
687 DEBUG(dbgs() << "\nPropagation through edges\n");
688 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
691 // Visit all the predecessor and successor edges to determine
692 // which ones have a weight assigned already. Note that it doesn't
693 // matter that we only keep track of a single unknown edge. The
694 // only case we are interested in handling is when only a single
695 // edge is unknown (see setEdgeOrBlockWeight).
696 for (unsigned i = 0; i < 2; i++) {
697 uint32_t TotalWeight = 0;
698 unsigned NumUnknownEdges = 0;
699 Edge UnknownEdge, SelfReferentialEdge;
702 // First, visit all predecessor edges.
703 for (size_t I = 0; I < Predecessors[BB].size(); I++) {
704 Edge E = std::make_pair(Predecessors[BB][I], BB);
705 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
706 if (E.first == E.second)
707 SelfReferentialEdge = E;
710 // On the second round, visit all successor edges.
711 for (size_t I = 0; I < Successors[BB].size(); I++) {
712 Edge E = std::make_pair(BB, Successors[BB][I]);
713 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
717 // After visiting all the edges, there are three cases that we
718 // can handle immediately:
720 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
721 // In this case, we simply check that the sum of all the edges
722 // is the same as BB's weight. If not, we change BB's weight
723 // to match. Additionally, if BB had not been visited before,
724 // we mark it visited.
726 // - Only one edge is unknown and BB has already been visited.
727 // In this case, we can compute the weight of the edge by
728 // subtracting the total block weight from all the known
729 // edge weights. If the edges weight more than BB, then the
730 // edge of the last remaining edge is set to zero.
732 // - There exists a self-referential edge and the weight of BB is
733 // known. In this case, this edge can be based on BB's weight.
734 // We add up all the other known edges and set the weight on
735 // the self-referential edge as we did in the previous case.
737 // In any other case, we must continue iterating. Eventually,
738 // all edges will get a weight, or iteration will stop when
739 // it reaches SampleProfileMaxPropagateIterations.
740 if (NumUnknownEdges <= 1) {
741 uint32_t &BBWeight = BlockWeights[BB];
742 if (NumUnknownEdges == 0) {
743 // If we already know the weight of all edges, the weight of the
744 // basic block can be computed. It should be no larger than the sum
745 // of all edge weights.
746 if (TotalWeight > BBWeight) {
747 BBWeight = TotalWeight;
749 DEBUG(dbgs() << "All edge weights for " << BB->getName()
750 << " known. Set weight for block: ";
751 printBlockWeight(dbgs(), BB););
753 if (VisitedBlocks.insert(BB))
755 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
756 // If there is a single unknown edge and the block has been
757 // visited, then we can compute E's weight.
758 if (BBWeight >= TotalWeight)
759 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
761 EdgeWeights[UnknownEdge] = 0;
762 VisitedEdges.insert(UnknownEdge);
764 DEBUG(dbgs() << "Set weight for edge: ";
765 printEdgeWeight(dbgs(), UnknownEdge));
767 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
768 uint32_t &BBWeight = BlockWeights[BB];
769 // We have a self-referential edge and the weight of BB is known.
770 if (BBWeight >= TotalWeight)
771 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
773 EdgeWeights[SelfReferentialEdge] = 0;
774 VisitedEdges.insert(SelfReferentialEdge);
776 DEBUG(dbgs() << "Set self-referential edge weight to: ";
777 printEdgeWeight(dbgs(), SelfReferentialEdge));
785 /// \brief Build in/out edge lists for each basic block in the CFG.
787 /// We are interested in unique edges. If a block B1 has multiple
788 /// edges to another block B2, we only add a single B1->B2 edge.
789 void SampleFunctionProfile::buildEdges(Function &F) {
790 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
793 // Add predecessors for B1.
794 SmallPtrSet<BasicBlock *, 16> Visited;
795 if (!Predecessors[B1].empty())
796 llvm_unreachable("Found a stale predecessors list in a basic block.");
797 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
798 BasicBlock *B2 = *PI;
799 if (Visited.insert(B2))
800 Predecessors[B1].push_back(B2);
803 // Add successors for B1.
805 if (!Successors[B1].empty())
806 llvm_unreachable("Found a stale successors list in a basic block.");
807 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
808 BasicBlock *B2 = *SI;
809 if (Visited.insert(B2))
810 Successors[B1].push_back(B2);
815 /// \brief Propagate weights into edges
817 /// The following rules are applied to every block B in the CFG:
819 /// - If B has a single predecessor/successor, then the weight
820 /// of that edge is the weight of the block.
822 /// - If all incoming or outgoing edges are known except one, and the
823 /// weight of the block is already known, the weight of the unknown
824 /// edge will be the weight of the block minus the sum of all the known
825 /// edges. If the sum of all the known edges is larger than B's weight,
826 /// we set the unknown edge weight to zero.
828 /// - If there is a self-referential edge, and the weight of the block is
829 /// known, the weight for that edge is set to the weight of the block
830 /// minus the weight of the other incoming edges to that block (if
832 void SampleFunctionProfile::propagateWeights(Function &F) {
836 // Before propagation starts, build, for each block, a list of
837 // unique predecessors and successors. This is necessary to handle
838 // identical edges in multiway branches. Since we visit all blocks and all
839 // edges of the CFG, it is cleaner to build these lists once at the start
843 // Propagate until we converge or we go past the iteration limit.
844 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
845 Changed = propagateThroughEdges(F);
848 // Generate MD_prof metadata for every branch instruction using the
849 // edge weights computed during propagation.
850 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
851 MDBuilder MDB(F.getContext());
852 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
854 TerminatorInst *TI = B->getTerminator();
855 if (TI->getNumSuccessors() == 1)
857 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
860 DEBUG(dbgs() << "\nGetting weights for branch at line "
861 << TI->getDebugLoc().getLine() << ":"
862 << TI->getDebugLoc().getCol() << ".\n");
863 SmallVector<uint32_t, 4> Weights;
864 bool AllWeightsZero = true;
865 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
866 BasicBlock *Succ = TI->getSuccessor(I);
867 Edge E = std::make_pair(B, Succ);
868 uint32_t Weight = EdgeWeights[E];
869 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
870 Weights.push_back(Weight);
872 AllWeightsZero = false;
875 // Only set weights if there is at least one non-zero weight.
876 // In any other case, let the analyzer set weights.
877 if (!AllWeightsZero) {
878 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
879 TI->setMetadata(llvm::LLVMContext::MD_prof,
880 MDB.createBranchWeights(Weights));
882 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
887 /// \brief Get the line number for the function header.
889 /// This looks up function \p F in the current compilation unit and
890 /// retrieves the line number where the function is defined. This is
891 /// line 0 for all the samples read from the profile file. Every line
892 /// number is relative to this line.
894 /// \param F Function object to query.
896 /// \returns the line number where \p F is defined.
897 unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
898 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
900 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) {
901 DICompileUnit CU(CUNodes->getOperand(I));
902 DIArray Subprograms = CU.getSubprograms();
903 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) {
904 DISubprogram Subprogram(Subprograms.getElement(J));
905 if (Subprogram.describes(&F))
906 return Subprogram.getLineNumber();
911 report_fatal_error("No debug information found in function " + F.getName() +
915 /// \brief Generate branch weight metadata for all branches in \p F.
917 /// Branch weights are computed out of instruction samples using a
918 /// propagation heuristic. Propagation proceeds in 3 phases:
920 /// 1- Assignment of block weights. All the basic blocks in the function
921 /// are initial assigned the same weight as their most frequently
922 /// executed instruction.
924 /// 2- Creation of equivalence classes. Since samples may be missing from
925 /// blocks, we can fill in the gaps by setting the weights of all the
926 /// blocks in the same equivalence class to the same weight. To compute
927 /// the concept of equivalence, we use dominance and loop information.
928 /// Two blocks B1 and B2 are in the same equivalence class if B1
929 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
931 /// 3- Propagation of block weights into edges. This uses a simple
932 /// propagation heuristic. The following rules are applied to every
933 /// block B in the CFG:
935 /// - If B has a single predecessor/successor, then the weight
936 /// of that edge is the weight of the block.
938 /// - If all the edges are known except one, and the weight of the
939 /// block is already known, the weight of the unknown edge will
940 /// be the weight of the block minus the sum of all the known
941 /// edges. If the sum of all the known edges is larger than B's weight,
942 /// we set the unknown edge weight to zero.
944 /// - If there is a self-referential edge, and the weight of the block is
945 /// known, the weight for that edge is set to the weight of the block
946 /// minus the weight of the other incoming edges to that block (if
949 /// Since this propagation is not guaranteed to finalize for every CFG, we
950 /// only allow it to proceed for a limited number of iterations (controlled
951 /// by -sample-profile-max-propagate-iterations).
953 /// FIXME: Try to replace this propagation heuristic with a scheme
954 /// that is guaranteed to finalize. A work-list approach similar to
955 /// the standard value propagation algorithm used by SSA-CCP might
958 /// Once all the branch weights are computed, we emit the MD_prof
959 /// metadata on B using the computed values for each of its branches.
961 /// \param F The function to query.
962 bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
963 PostDominatorTree *PostDomTree,
965 bool Changed = false;
967 // Initialize invariants used during computation and propagation.
968 HeaderLineno = getFunctionLoc(F);
969 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
970 << ": " << HeaderLineno << "\n");
975 // Compute basic block weights.
976 Changed |= computeBlockWeights(F);
979 // Find equivalence classes.
980 findEquivalenceClasses(F);
982 // Propagate weights to all edges.
989 char SampleProfileLoader::ID = 0;
990 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
991 "Sample Profile loader", false, false)
992 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
993 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
994 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
995 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
996 "Sample Profile loader", false, false)
998 bool SampleProfileLoader::doInitialization(Module &M) {
999 Profiler.reset(new SampleModuleProfile(Filename));
1000 Profiler->loadText();
1004 FunctionPass *llvm::createSampleProfileLoaderPass() {
1005 return new SampleProfileLoader(SampleProfileFile);
1008 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1009 return new SampleProfileLoader(Name);
1012 bool SampleProfileLoader::runOnFunction(Function &F) {
1013 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1014 PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
1015 LoopInfo *LI = &getAnalysis<LoopInfo>();
1016 SampleFunctionProfile &FunctionProfile = Profiler->getProfile(F);
1017 if (!FunctionProfile.empty())
1018 return FunctionProfile.emitAnnotations(F, DT, PDT, LI);