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/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/Analysis/PostDominators.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/InstIterator.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/LineIterator.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Regex.h"
51 #include "llvm/Support/raw_ostream.h"
56 // Command line option to specify the file to read samples from. This is
57 // mainly used for debugging.
58 static 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);
61 static 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."));
67 /// \brief Represents the relative location of an instruction.
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.
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++;").
76 struct InstructionLocation {
77 InstructionLocation(int L, unsigned D) : LineOffset(L), Discriminator(D) {}
79 unsigned Discriminator;
84 template <> 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());
91 static inline InstructionLocation getTombstoneKey() {
92 return InstructionLocation(OffsetInfo::getTombstoneKey(),
93 DiscriminatorInfo::getTombstoneKey());
95 static inline unsigned getHashValue(InstructionLocation Val) {
96 return DenseMapInfo<std::pair<int, unsigned> >::getHashValue(
97 std::pair<int, unsigned>(Val.LineOffset, Val.Discriminator));
99 static inline bool isEqual(InstructionLocation LHS, InstructionLocation RHS) {
100 return LHS.LineOffset == RHS.LineOffset &&
101 LHS.Discriminator == RHS.Discriminator;
107 typedef DenseMap<InstructionLocation, unsigned> BodySampleMap;
108 typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
109 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
110 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
111 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
112 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
114 /// \brief Representation of the runtime profile for a function.
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.
119 class SampleFunctionProfile {
121 SampleFunctionProfile()
122 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
125 unsigned getFunctionLoc(Function &F);
126 bool emitAnnotations(Function &F, DominatorTree *DomTree,
127 PostDominatorTree *PostDomTree, LoopInfo *Loops);
128 unsigned getInstWeight(Instruction &I);
129 unsigned getBlockWeight(BasicBlock *B);
130 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
131 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
132 void addBodySamples(int LineOffset, unsigned Discriminator, unsigned Num) {
133 assert(LineOffset >= 0);
134 BodySamples[InstructionLocation(LineOffset, Discriminator)] += Num;
136 void print(raw_ostream &OS);
137 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);
146 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
147 void buildEdges(Function &F);
148 bool propagateThroughEdges(Function &F);
149 bool empty() { return BodySamples.empty(); }
152 /// \brief Total number of samples collected inside this function.
154 /// Samples are cumulative, they include all the samples collected
155 /// inside this function and all its inlined callees.
156 unsigned TotalSamples;
158 /// \brief Total number of samples collected at the head of the function.
159 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
160 unsigned TotalHeadSamples;
162 /// \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
166 unsigned HeaderLineno;
168 /// \brief Map line offsets to collected samples.
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;
175 /// \brief Map basic blocks to their computed weights.
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;
181 /// \brief Map edges to their computed weights.
183 /// Edge weights are computed by propagating basic block weights in
184 /// SampleProfile::propagateWeights.
185 EdgeWeightMap EdgeWeights;
187 /// \brief Set of visited blocks during propagation.
188 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
190 /// \brief Set of visited edges during propagation.
191 SmallSet<Edge, 128> VisitedEdges;
193 /// \brief Equivalence classes for block weights.
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;
201 /// \brief Dominance, post-dominance and loop information.
203 PostDominatorTree *PDT;
206 /// \brief Predecessors for each basic block in the CFG.
207 BlockEdgeMap Predecessors;
209 /// \brief Successors for each basic block in the CFG.
210 BlockEdgeMap Successors;
212 /// \brief LLVM context holding the debug data we need.
216 /// \brief Sample-based profile reader.
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
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.
228 /// From the profile file, we are interested in collecting the
229 /// following information:
231 /// * A list of functions included in the profile (mangled names).
233 /// * For each function F:
234 /// 1. The total number of samples collected in F.
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.
239 class SampleModuleProfile {
241 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
245 void loadNative() { llvm_unreachable("not implemented"); }
246 void printFunctionProfile(raw_ostream &OS, StringRef FName);
247 void dumpFunctionProfile(StringRef FName);
248 SampleFunctionProfile &getProfile(const Function &F) {
249 return Profiles[F.getName()];
252 /// \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");
258 /// \brief Map every function to its associated profile.
260 /// The profile of every function executed at runtime is collected
261 /// in the structure SampleFunctionProfile. This maps function objects
262 /// to their corresponding profiles.
263 StringMap<SampleFunctionProfile> Profiles;
265 /// \brief Path name to the file holding the profile data.
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.
274 /// \brief Sample profile pass.
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.
279 class SampleProfileLoader : public FunctionPass {
281 // Class identification, replacement for typeinfo
284 SampleProfileLoader(StringRef Name = SampleProfileFile)
285 : FunctionPass(ID), Profiler(), Filename(Name) {
286 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
289 bool doInitialization(Module &M) override;
291 void dump() { Profiler->dump(); }
293 const char *getPassName() const override { return "Sample profile pass"; }
295 bool runOnFunction(Function &F) override;
297 void getAnalysisUsage(AnalysisUsage &AU) const override {
298 AU.setPreservesCFG();
299 AU.addRequired<LoopInfo>();
300 AU.addRequired<DominatorTreeWrapperPass>();
301 AU.addRequired<PostDominatorTree>();
305 /// \brief Profile reader object.
306 std::unique_ptr<SampleModuleProfile> Profiler;
308 /// \brief Name of the profile file to load.
313 /// \brief Print this function profile on stream \p OS.
315 /// \param OS Stream to emit the output to.
316 void SampleFunctionProfile::print(raw_ostream &OS) {
317 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
318 << " sampled lines\n";
319 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
320 SE = BodySamples.end();
322 OS << "\tline offset: " << SI->first.LineOffset
323 << ", discriminator: " << SI->first.Discriminator
324 << ", number of samples: " << SI->second << "\n";
328 /// \brief Print the weight of edge \p E on stream \p OS.
330 /// \param OS Stream to emit the output to.
331 /// \param E Edge to print.
332 void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
333 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
334 << "]: " << EdgeWeights[E] << "\n";
337 /// \brief Print the equivalence class of block \p BB on stream \p OS.
339 /// \param OS Stream to emit the output to.
340 /// \param BB Block to print.
341 void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
343 BasicBlock *Equiv = EquivalenceClass[BB];
344 OS << "equivalence[" << BB->getName()
345 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
348 /// \brief Print the weight of block \p BB on stream \p OS.
350 /// \param OS Stream to emit the output to.
351 /// \param BB Block to print.
352 void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
353 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
356 /// \brief Print the function profile for \p FName on stream \p OS.
358 /// \param OS Stream to emit the output to.
359 /// \param FName Name of the function to print.
360 void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
362 OS << "Function: " << FName << ":\n";
363 Profiles[FName].print(OS);
366 /// \brief Dump the function profile for \p FName.
368 /// \param FName Name of the function to print.
369 void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
370 printFunctionProfile(dbgs(), FName);
373 /// \brief Dump all the function profiles found.
374 void SampleModuleProfile::dump() {
375 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
378 dumpFunctionProfile(I->getKey());
381 /// \brief Load samples from a text file.
383 /// The file contains a list of samples for every function executed at
384 /// runtime. Each function profile has the following format:
386 /// 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 ... ]
390 /// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
392 /// Function names must be mangled in order for the profile loader to
393 /// 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.
399 /// Each sampled line may contain several items. Some are optional
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.
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)
412 /// c- Number of samples. This is the number of samples collected by
413 /// the profiler at this source location.
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,
420 /// 130: 7 foo:3 bar:2 baz:7
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.
426 /// FIXME: This is currently unhandled, but it has a lot of
427 /// potential for aiding the inliner.
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.
433 /// FIXME: flat profiles are too imprecise to provide good optimization
434 /// opportunities. Convert them to context-sensitive profile.
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
440 void SampleModuleProfile::loadText() {
441 std::unique_ptr<MemoryBuffer> Buffer;
442 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
444 report_fatal_error("Could not open file " + Filename + ": " + EC.message());
445 line_iterator LineIt(*Buffer, '#');
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.
450 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+)$");
451 Regex LineSample("^([0-9]+)\\.?([0-9]+)?: ([0-9]+)(.*)$");
452 while (!LineIt.is_at_eof()) {
453 // Read the header of each function. The function header should
456 // function_name:total_samples:total_head_samples
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);
464 StringRef FName = Matches[1];
465 unsigned NumSamples, NumHeadSamples;
466 Matches[2].getAsInteger(10, NumSamples);
467 Matches[3].getAsInteger(10, NumHeadSamples);
468 Profiles[FName] = SampleFunctionProfile();
469 SampleFunctionProfile &FProfile = Profiles[FName];
470 FProfile.addTotalSamples(NumSamples);
471 FProfile.addHeadSamples(NumHeadSamples);
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))
479 LineIt.line_number(),
480 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
481 assert(Matches.size() == 5);
482 unsigned LineOffset, NumSamples, Discriminator = 0;
483 Matches[1].getAsInteger(10, LineOffset);
484 if (Matches[2] != "")
485 Matches[2].getAsInteger(10, Discriminator);
486 Matches[3].getAsInteger(10, NumSamples);
488 // FIXME: Handle called targets (in Matches[4]).
490 // 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.
496 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
502 /// \brief Get the weight for an instruction.
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.
510 /// \param Inst Instruction to query.
512 /// \returns The profiled weight of I.
513 unsigned SampleFunctionProfile::getInstWeight(Instruction &Inst) {
514 DebugLoc DLoc = Inst.getDebugLoc();
515 unsigned Lineno = DLoc.getLine();
516 if (Lineno < HeaderLineno)
519 DILocation DIL(DLoc.getAsMDNode(*Ctx));
520 int LOffset = Lineno - HeaderLineno;
521 unsigned Discriminator = DIL.getDiscriminator();
523 BodySamples.lookup(InstructionLocation(LOffset, Discriminator));
524 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst
525 << " (line offset: " << LOffset << "." << Discriminator
526 << " - weight: " << Weight << ")\n");
530 /// \brief Compute the weight of a basic block.
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.
536 /// \param B The basic block to query.
538 /// \returns The computed weight of B.
539 unsigned SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
540 // 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));
544 return Entry.first->second;
546 // Otherwise, compute and cache B's weight.
548 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
549 unsigned InstWeight = getInstWeight(*I);
550 if (InstWeight > Weight)
553 Entry.first->second = Weight;
557 /// \brief Compute and store the weights of every basic block.
559 /// This populates the BlockWeights map by computing
560 /// the weights of every basic block in the CFG.
562 /// \param F The function to query.
563 bool 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) {
567 unsigned Weight = getBlockWeight(B);
568 Changed |= (Weight > 0);
569 DEBUG(printBlockWeight(dbgs(), B));
575 /// \brief Find equivalence classes for the given block.
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.
581 /// A block BB2 will be in the same equivalence class as \p BB1 if
582 /// the following holds:
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.
588 /// 2- Both BB2 and \p BB1 must be in the same loop.
590 /// For every block BB2 that meets those two requirements, we set BB2's
591 /// equivalence class to \p BB1.
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.
598 void 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();
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 &&
609 EquivalenceClass[BB2] = BB1;
611 // If BB2 is heavier than BB1, make BB2 have the same weight
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.
619 unsigned &BB1Weight = BlockWeights[BB1];
620 unsigned &BB2Weight = BlockWeights[BB2];
621 BB1Weight = std::max(BB1Weight, BB2Weight);
626 /// \brief Find equivalence classes.
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.
634 /// \param F The function to query.
635 void 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) {
642 // Compute BB1's equivalence class once.
643 if (EquivalenceClass.count(BB1)) {
644 DEBUG(printBlockEquivalence(dbgs(), BB1));
648 // By default, blocks are in their own equivalence class.
649 EquivalenceClass[BB1] = BB1;
651 // Traverse all the blocks dominated by BB1. We are looking for
652 // every basic block BB2 such that:
654 // 1- BB1 dominates BB2.
655 // 2- BB2 post-dominates BB1.
656 // 3- BB1 and BB2 are in the same loop nest.
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);
665 // Repeat the same logic for all the blocks post-dominated by BB1.
666 // We are looking for every basic block BB2 such that:
668 // 1- BB1 post-dominates BB2.
669 // 2- BB2 dominates BB1.
670 // 3- BB1 and BB2 are in the same loop nest.
672 // If all those conditions hold, BB2's equivalence class is BB1.
673 DominatedBBs.clear();
674 PDT->getDescendants(BB1, DominatedBBs);
675 findEquivalencesFor(BB1, DominatedBBs, DT);
677 DEBUG(printBlockEquivalence(dbgs(), BB1));
680 // Assign weights to equivalence classes.
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) {
689 BasicBlock *EquivBB = EquivalenceClass[BB];
691 BlockWeights[BB] = BlockWeights[EquivBB];
692 DEBUG(printBlockWeight(dbgs(), BB));
696 /// \brief Visit the given edge to decide if it has a valid weight.
698 /// If \p E has not been visited before, we copy to \p UnknownEdge
699 /// and increment the count of unknown edges.
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.
705 /// \returns E's weight, if known. Otherwise, return 0.
706 unsigned SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
708 if (!VisitedEdges.count(E)) {
709 (*NumUnknownEdges)++;
714 return EdgeWeights[E];
717 /// \brief Propagate weights through incoming/outgoing edges.
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.
722 /// Similarly, if all the edges have a known count, we can calculate the
723 /// count of the basic block, if needed.
725 /// \param F Function to process.
727 /// \returns True if new weights were assigned to edges or blocks.
728 bool 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) {
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++) {
740 unsigned TotalWeight = 0;
741 unsigned NumUnknownEdges = 0;
742 Edge UnknownEdge, SelfReferentialEdge;
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;
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);
760 // After visiting all the edges, there are three cases that we
761 // can handle immediately:
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.
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.
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.
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) {
784 unsigned &BBWeight = BlockWeights[BB];
785 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;
792 DEBUG(dbgs() << "All edge weights for " << BB->getName()
793 << " known. Set weight for block: ";
794 printBlockWeight(dbgs(), BB););
796 if (VisitedBlocks.insert(BB))
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;
804 EdgeWeights[UnknownEdge] = 0;
805 VisitedEdges.insert(UnknownEdge);
807 DEBUG(dbgs() << "Set weight for edge: ";
808 printEdgeWeight(dbgs(), UnknownEdge));
810 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
811 unsigned &BBWeight = BlockWeights[BB];
812 // We have a self-referential edge and the weight of BB is known.
813 if (BBWeight >= TotalWeight)
814 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
816 EdgeWeights[SelfReferentialEdge] = 0;
817 VisitedEdges.insert(SelfReferentialEdge);
819 DEBUG(dbgs() << "Set self-referential edge weight to: ";
820 printEdgeWeight(dbgs(), SelfReferentialEdge));
828 /// \brief Build in/out edge lists for each basic block in the CFG.
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.
832 void SampleFunctionProfile::buildEdges(Function &F) {
833 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
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);
846 // Add successors for B1.
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);
858 /// \brief Propagate weights into edges
860 /// The following rules are applied to every block B in the CFG:
862 /// - If B has a single predecessor/successor, then the weight
863 /// of that edge is the weight of the block.
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.
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
875 void SampleFunctionProfile::propagateWeights(Function &F) {
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
886 // Propagate until we converge or we go past the iteration limit.
887 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
888 Changed = propagateThroughEdges(F);
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) {
897 TerminatorInst *TI = B->getTerminator();
898 if (TI->getNumSuccessors() == 1)
900 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
903 DEBUG(dbgs() << "\nGetting weights for branch at line "
904 << TI->getDebugLoc().getLine() << ".\n");
905 SmallVector<unsigned, 4> Weights;
906 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);
910 unsigned Weight = EdgeWeights[E];
911 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
912 Weights.push_back(Weight);
914 AllWeightsZero = false;
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));
924 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
929 /// \brief Get the line number for the function header.
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.
936 /// \param F Function object to query.
938 /// \returns the line number where \p F is defined.
939 unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
940 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
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();
953 report_fatal_error("No debug information found in function " + F.getName() +
957 /// \brief Generate branch weight metadata for all branches in \p F.
959 /// Branch weights are computed out of instruction samples using a
960 /// propagation heuristic. Propagation proceeds in 3 phases:
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.
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.
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:
977 /// - If B has a single predecessor/successor, then the weight
978 /// of that edge is the weight of the block.
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.
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
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).
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
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.
1003 /// \param F The function to query.
1004 bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
1005 PostDominatorTree *PostDomTree,
1007 bool Changed = false;
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");
1016 Ctx = &F.getParent()->getContext();
1018 // Compute basic block weights.
1019 Changed |= computeBlockWeights(F);
1022 // Find equivalence classes.
1023 findEquivalenceClasses(F);
1025 // Propagate weights to all edges.
1026 propagateWeights(F);
1032 char SampleProfileLoader::ID = 0;
1033 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1034 "Sample Profile loader", false, false)
1035 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1036 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
1037 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
1038 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1039 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1040 "Sample Profile loader", false, false)
1042 bool SampleProfileLoader::doInitialization(Module &M) {
1043 Profiler.reset(new SampleModuleProfile(Filename));
1044 Profiler->loadText();
1048 FunctionPass *llvm::createSampleProfileLoaderPass() {
1049 return new SampleProfileLoader(SampleProfileFile);
1052 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1053 return new SampleProfileLoader(Name);
1056 bool SampleProfileLoader::runOnFunction(Function &F) {
1057 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1058 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);