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 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/InstIterator.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/Pass.h"
43 #include "llvm/ProfileData/SampleProfReader.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/IPO.h"
52 using namespace sampleprof;
54 #define DEBUG_TYPE "sample-profile"
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 typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap;
68 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
69 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
70 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
71 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
74 /// \brief Sample profile pass.
76 /// This pass reads profile data from the file specified by
77 /// -sample-profile-file and annotates every affected function with the
78 /// profile information found in that file.
79 class SampleProfileLoader : public ModulePass {
81 // Class identification, replacement for typeinfo
84 SampleProfileLoader(StringRef Name = SampleProfileFile)
85 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
86 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
87 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
90 bool doInitialization(Module &M) override;
92 void dump() { Reader->dump(); }
94 const char *getPassName() const override { return "Sample profile pass"; }
96 bool runOnModule(Module &M) override;
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
103 bool runOnFunction(Function &F);
104 unsigned getFunctionLoc(Function &F);
105 bool emitAnnotations(Function &F);
106 ErrorOr<unsigned> getInstWeight(const Instruction &I) const;
107 ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const;
108 void printEdgeWeight(raw_ostream &OS, Edge E);
109 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
110 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
111 bool computeBlockWeights(Function &F);
112 void findEquivalenceClasses(Function &F);
113 void findEquivalencesFor(BasicBlock *BB1,
114 SmallVector<BasicBlock *, 8> Descendants,
115 DominatorTreeBase<BasicBlock> *DomTree);
116 void propagateWeights(Function &F);
117 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
118 void buildEdges(Function &F);
119 bool propagateThroughEdges(Function &F);
120 void computeDominanceAndLoopInfo(Function &F);
122 /// \brief Line number for the function header. Used to compute absolute
123 /// line numbers from the relative line numbers found in the profile.
124 unsigned HeaderLineno;
126 /// \brief Map basic blocks to their computed weights.
128 /// The weight of a basic block is defined to be the maximum
129 /// of all the instruction weights in that block.
130 BlockWeightMap BlockWeights;
132 /// \brief Map edges to their computed weights.
134 /// Edge weights are computed by propagating basic block weights in
135 /// SampleProfile::propagateWeights.
136 EdgeWeightMap EdgeWeights;
138 /// \brief Set of visited blocks during propagation.
139 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
141 /// \brief Set of visited edges during propagation.
142 SmallSet<Edge, 128> VisitedEdges;
144 /// \brief Equivalence classes for block weights.
146 /// Two blocks BB1 and BB2 are in the same equivalence class if they
147 /// dominate and post-dominate each other, and they are in the same loop
148 /// nest. When this happens, the two blocks are guaranteed to execute
149 /// the same number of times.
150 EquivalenceClassMap EquivalenceClass;
152 /// \brief Dominance, post-dominance and loop information.
153 std::unique_ptr<DominatorTree> DT;
154 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
155 std::unique_ptr<LoopInfo> LI;
157 /// \brief Predecessors for each basic block in the CFG.
158 BlockEdgeMap Predecessors;
160 /// \brief Successors for each basic block in the CFG.
161 BlockEdgeMap Successors;
163 /// \brief Profile reader object.
164 std::unique_ptr<SampleProfileReader> Reader;
166 /// \brief Samples collected for the body of this function.
167 FunctionSamples *Samples;
169 /// \brief Name of the profile file to load.
172 /// \brief Flag indicating whether the profile input loaded successfully.
177 /// \brief Print the weight of edge \p E on stream \p OS.
179 /// \param OS Stream to emit the output to.
180 /// \param E Edge to print.
181 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
182 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
183 << "]: " << EdgeWeights[E] << "\n";
186 /// \brief Print the equivalence class of block \p BB on stream \p OS.
188 /// \param OS Stream to emit the output to.
189 /// \param BB Block to print.
190 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
191 const BasicBlock *BB) {
192 const BasicBlock *Equiv = EquivalenceClass[BB];
193 OS << "equivalence[" << BB->getName()
194 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
197 /// \brief Print the weight of block \p BB on stream \p OS.
199 /// \param OS Stream to emit the output to.
200 /// \param BB Block to print.
201 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
202 const BasicBlock *BB) const {
203 const auto &I = BlockWeights.find(BB);
204 unsigned W = (I == BlockWeights.end() ? 0 : I->second);
205 OS << "weight[" << BB->getName() << "]: " << W << "\n";
208 /// \brief Get the weight for an instruction.
210 /// The "weight" of an instruction \p Inst is the number of samples
211 /// collected on that instruction at runtime. To retrieve it, we
212 /// need to compute the line number of \p Inst relative to the start of its
213 /// function. We use HeaderLineno to compute the offset. We then
214 /// look up the samples collected for \p Inst using BodySamples.
216 /// \param Inst Instruction to query.
218 /// \returns the weight of \p Inst.
220 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
221 DebugLoc DLoc = Inst.getDebugLoc();
223 return std::error_code();
225 unsigned Lineno = DLoc.getLine();
226 if (Lineno < HeaderLineno)
227 return std::error_code();
229 const DILocation *DIL = DLoc;
230 ErrorOr<unsigned> R =
231 Samples->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator());
233 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
234 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
235 << DIL->getDiscriminator() << " - weight: " << R.get()
240 /// \brief Compute the weight of a basic block.
242 /// The weight of basic block \p BB is the maximum weight of all the
243 /// instructions in BB.
245 /// \param BB The basic block to query.
247 /// \returns the weight for \p BB.
249 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
252 for (auto &I : BB->getInstList()) {
253 const ErrorOr<unsigned> &R = getInstWeight(I);
254 if (R && R.get() >= Weight) {
262 return std::error_code();
265 /// \brief Compute and store the weights of every basic block.
267 /// This populates the BlockWeights map by computing
268 /// the weights of every basic block in the CFG.
270 /// \param F The function to query.
271 bool SampleProfileLoader::computeBlockWeights(Function &F) {
272 bool Changed = false;
273 DEBUG(dbgs() << "Block weights\n");
274 for (const auto &BB : F) {
275 ErrorOr<unsigned> Weight = getBlockWeight(&BB);
277 BlockWeights[&BB] = Weight.get();
280 DEBUG(printBlockWeight(dbgs(), &BB));
286 /// \brief Find equivalence classes for the given block.
288 /// This finds all the blocks that are guaranteed to execute the same
289 /// number of times as \p BB1. To do this, it traverses all the
290 /// descendants of \p BB1 in the dominator or post-dominator tree.
292 /// A block BB2 will be in the same equivalence class as \p BB1 if
293 /// the following holds:
295 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
296 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
297 /// dominate BB1 in the post-dominator tree.
299 /// 2- Both BB2 and \p BB1 must be in the same loop.
301 /// For every block BB2 that meets those two requirements, we set BB2's
302 /// equivalence class to \p BB1.
304 /// \param BB1 Block to check.
305 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
306 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
307 /// with blocks from \p BB1's dominator tree, then
308 /// this is the post-dominator tree, and vice versa.
309 void SampleProfileLoader::findEquivalencesFor(
310 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
311 DominatorTreeBase<BasicBlock> *DomTree) {
312 for (const auto *BB2 : Descendants) {
313 bool IsDomParent = DomTree->dominates(BB2, BB1);
314 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
315 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
317 EquivalenceClass[BB2] = BB1;
319 // If BB2 is heavier than BB1, make BB2 have the same weight
322 // Note that we don't worry about the opposite situation here
323 // (when BB2 is lighter than BB1). We will deal with this
324 // during the propagation phase. Right now, we just want to
325 // make sure that BB1 has the largest weight of all the
326 // members of its equivalence set.
327 unsigned &BB1Weight = BlockWeights[BB1];
328 unsigned &BB2Weight = BlockWeights[BB2];
329 BB1Weight = std::max(BB1Weight, BB2Weight);
334 /// \brief Find equivalence classes.
336 /// Since samples may be missing from blocks, we can fill in the gaps by setting
337 /// the weights of all the blocks in the same equivalence class to the same
338 /// weight. To compute the concept of equivalence, we use dominance and loop
339 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
340 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
342 /// \param F The function to query.
343 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
344 SmallVector<BasicBlock *, 8> DominatedBBs;
345 DEBUG(dbgs() << "\nBlock equivalence classes\n");
346 // Find equivalence sets based on dominance and post-dominance information.
348 BasicBlock *BB1 = &BB;
350 // Compute BB1's equivalence class once.
351 if (EquivalenceClass.count(BB1)) {
352 DEBUG(printBlockEquivalence(dbgs(), BB1));
356 // By default, blocks are in their own equivalence class.
357 EquivalenceClass[BB1] = BB1;
359 // Traverse all the blocks dominated by BB1. We are looking for
360 // every basic block BB2 such that:
362 // 1- BB1 dominates BB2.
363 // 2- BB2 post-dominates BB1.
364 // 3- BB1 and BB2 are in the same loop nest.
366 // If all those conditions hold, it means that BB2 is executed
367 // as many times as BB1, so they are placed in the same equivalence
368 // class by making BB2's equivalence class be BB1.
369 DominatedBBs.clear();
370 DT->getDescendants(BB1, DominatedBBs);
371 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
373 // Repeat the same logic for all the blocks post-dominated by BB1.
374 // We are looking for every basic block BB2 such that:
376 // 1- BB1 post-dominates BB2.
377 // 2- BB2 dominates BB1.
378 // 3- BB1 and BB2 are in the same loop nest.
380 // If all those conditions hold, BB2's equivalence class is BB1.
381 DominatedBBs.clear();
382 PDT->getDescendants(BB1, DominatedBBs);
383 findEquivalencesFor(BB1, DominatedBBs, DT.get());
385 DEBUG(printBlockEquivalence(dbgs(), BB1));
388 // Assign weights to equivalence classes.
390 // All the basic blocks in the same equivalence class will execute
391 // the same number of times. Since we know that the head block in
392 // each equivalence class has the largest weight, assign that weight
393 // to all the blocks in that equivalence class.
394 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
396 const BasicBlock *BB = &BI;
397 const BasicBlock *EquivBB = EquivalenceClass[BB];
399 BlockWeights[BB] = BlockWeights[EquivBB];
400 DEBUG(printBlockWeight(dbgs(), BB));
404 /// \brief Visit the given edge to decide if it has a valid weight.
406 /// If \p E has not been visited before, we copy to \p UnknownEdge
407 /// and increment the count of unknown edges.
409 /// \param E Edge to visit.
410 /// \param NumUnknownEdges Current number of unknown edges.
411 /// \param UnknownEdge Set if E has not been visited before.
413 /// \returns E's weight, if known. Otherwise, return 0.
414 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
416 if (!VisitedEdges.count(E)) {
417 (*NumUnknownEdges)++;
422 return EdgeWeights[E];
425 /// \brief Propagate weights through incoming/outgoing edges.
427 /// If the weight of a basic block is known, and there is only one edge
428 /// with an unknown weight, we can calculate the weight of that edge.
430 /// Similarly, if all the edges have a known count, we can calculate the
431 /// count of the basic block, if needed.
433 /// \param F Function to process.
435 /// \returns True if new weights were assigned to edges or blocks.
436 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
437 bool Changed = false;
438 DEBUG(dbgs() << "\nPropagation through edges\n");
440 BasicBlock *BB = &BI;
442 // Visit all the predecessor and successor edges to determine
443 // which ones have a weight assigned already. Note that it doesn't
444 // matter that we only keep track of a single unknown edge. The
445 // only case we are interested in handling is when only a single
446 // edge is unknown (see setEdgeOrBlockWeight).
447 for (unsigned i = 0; i < 2; i++) {
448 unsigned TotalWeight = 0;
449 unsigned NumUnknownEdges = 0;
450 Edge UnknownEdge, SelfReferentialEdge;
453 // First, visit all predecessor edges.
454 for (auto *Pred : Predecessors[BB]) {
455 Edge E = std::make_pair(Pred, BB);
456 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
457 if (E.first == E.second)
458 SelfReferentialEdge = E;
461 // On the second round, visit all successor edges.
462 for (auto *Succ : Successors[BB]) {
463 Edge E = std::make_pair(BB, Succ);
464 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
468 // After visiting all the edges, there are three cases that we
469 // can handle immediately:
471 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
472 // In this case, we simply check that the sum of all the edges
473 // is the same as BB's weight. If not, we change BB's weight
474 // to match. Additionally, if BB had not been visited before,
475 // we mark it visited.
477 // - Only one edge is unknown and BB has already been visited.
478 // In this case, we can compute the weight of the edge by
479 // subtracting the total block weight from all the known
480 // edge weights. If the edges weight more than BB, then the
481 // edge of the last remaining edge is set to zero.
483 // - There exists a self-referential edge and the weight of BB is
484 // known. In this case, this edge can be based on BB's weight.
485 // We add up all the other known edges and set the weight on
486 // the self-referential edge as we did in the previous case.
488 // In any other case, we must continue iterating. Eventually,
489 // all edges will get a weight, or iteration will stop when
490 // it reaches SampleProfileMaxPropagateIterations.
491 if (NumUnknownEdges <= 1) {
492 unsigned &BBWeight = BlockWeights[BB];
493 if (NumUnknownEdges == 0) {
494 // If we already know the weight of all edges, the weight of the
495 // basic block can be computed. It should be no larger than the sum
496 // of all edge weights.
497 if (TotalWeight > BBWeight) {
498 BBWeight = TotalWeight;
500 DEBUG(dbgs() << "All edge weights for " << BB->getName()
501 << " known. Set weight for block: ";
502 printBlockWeight(dbgs(), BB););
504 if (VisitedBlocks.insert(BB).second)
506 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
507 // If there is a single unknown edge and the block has been
508 // visited, then we can compute E's weight.
509 if (BBWeight >= TotalWeight)
510 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
512 EdgeWeights[UnknownEdge] = 0;
513 VisitedEdges.insert(UnknownEdge);
515 DEBUG(dbgs() << "Set weight for edge: ";
516 printEdgeWeight(dbgs(), UnknownEdge));
518 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
519 unsigned &BBWeight = BlockWeights[BB];
520 // We have a self-referential edge and the weight of BB is known.
521 if (BBWeight >= TotalWeight)
522 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
524 EdgeWeights[SelfReferentialEdge] = 0;
525 VisitedEdges.insert(SelfReferentialEdge);
527 DEBUG(dbgs() << "Set self-referential edge weight to: ";
528 printEdgeWeight(dbgs(), SelfReferentialEdge));
536 /// \brief Build in/out edge lists for each basic block in the CFG.
538 /// We are interested in unique edges. If a block B1 has multiple
539 /// edges to another block B2, we only add a single B1->B2 edge.
540 void SampleProfileLoader::buildEdges(Function &F) {
542 BasicBlock *B1 = &BI;
544 // Add predecessors for B1.
545 SmallPtrSet<BasicBlock *, 16> Visited;
546 if (!Predecessors[B1].empty())
547 llvm_unreachable("Found a stale predecessors list in a basic block.");
548 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
549 BasicBlock *B2 = *PI;
550 if (Visited.insert(B2).second)
551 Predecessors[B1].push_back(B2);
554 // Add successors for B1.
556 if (!Successors[B1].empty())
557 llvm_unreachable("Found a stale successors list in a basic block.");
558 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
559 BasicBlock *B2 = *SI;
560 if (Visited.insert(B2).second)
561 Successors[B1].push_back(B2);
566 /// \brief Propagate weights into edges
568 /// The following rules are applied to every block BB in the CFG:
570 /// - If BB has a single predecessor/successor, then the weight
571 /// of that edge is the weight of the block.
573 /// - If all incoming or outgoing edges are known except one, and the
574 /// weight of the block is already known, the weight of the unknown
575 /// edge will be the weight of the block minus the sum of all the known
576 /// edges. If the sum of all the known edges is larger than BB's weight,
577 /// we set the unknown edge weight to zero.
579 /// - If there is a self-referential edge, and the weight of the block is
580 /// known, the weight for that edge is set to the weight of the block
581 /// minus the weight of the other incoming edges to that block (if
583 void SampleProfileLoader::propagateWeights(Function &F) {
587 // Add an entry count to the function using the samples gathered
588 // at the function entry.
589 F.setEntryCount(Samples->getHeadSamples());
591 // Before propagation starts, build, for each block, a list of
592 // unique predecessors and successors. This is necessary to handle
593 // identical edges in multiway branches. Since we visit all blocks and all
594 // edges of the CFG, it is cleaner to build these lists once at the start
598 // Propagate until we converge or we go past the iteration limit.
599 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
600 Changed = propagateThroughEdges(F);
603 // Generate MD_prof metadata for every branch instruction using the
604 // edge weights computed during propagation.
605 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
606 MDBuilder MDB(F.getContext());
608 BasicBlock *BB = &BI;
609 TerminatorInst *TI = BB->getTerminator();
610 if (TI->getNumSuccessors() == 1)
612 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
615 DEBUG(dbgs() << "\nGetting weights for branch at line "
616 << TI->getDebugLoc().getLine() << ".\n");
617 SmallVector<unsigned, 4> Weights;
618 bool AllWeightsZero = true;
619 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
620 BasicBlock *Succ = TI->getSuccessor(I);
621 Edge E = std::make_pair(BB, Succ);
622 unsigned Weight = EdgeWeights[E];
623 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
624 Weights.push_back(Weight);
626 AllWeightsZero = false;
629 // Only set weights if there is at least one non-zero weight.
630 // In any other case, let the analyzer set weights.
631 if (!AllWeightsZero) {
632 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
633 TI->setMetadata(llvm::LLVMContext::MD_prof,
634 MDB.createBranchWeights(Weights));
636 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
641 /// \brief Get the line number for the function header.
643 /// This looks up function \p F in the current compilation unit and
644 /// retrieves the line number where the function is defined. This is
645 /// line 0 for all the samples read from the profile file. Every line
646 /// number is relative to this line.
648 /// \param F Function object to query.
650 /// \returns the line number where \p F is defined. If it returns 0,
651 /// it means that there is no debug information available for \p F.
652 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
653 if (DISubprogram *S = getDISubprogram(&F))
656 // If could not find the start of \p F, emit a diagnostic to inform the user
657 // about the missed opportunity.
658 F.getContext().diagnose(DiagnosticInfoSampleProfile(
659 "No debug information found in function " + F.getName() +
660 ": Function profile not used",
665 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
666 DT.reset(new DominatorTree);
669 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
672 LI.reset(new LoopInfo);
676 /// \brief Generate branch weight metadata for all branches in \p F.
678 /// Branch weights are computed out of instruction samples using a
679 /// propagation heuristic. Propagation proceeds in 3 phases:
681 /// 1- Assignment of block weights. All the basic blocks in the function
682 /// are initial assigned the same weight as their most frequently
683 /// executed instruction.
685 /// 2- Creation of equivalence classes. Since samples may be missing from
686 /// blocks, we can fill in the gaps by setting the weights of all the
687 /// blocks in the same equivalence class to the same weight. To compute
688 /// the concept of equivalence, we use dominance and loop information.
689 /// Two blocks B1 and B2 are in the same equivalence class if B1
690 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
692 /// 3- Propagation of block weights into edges. This uses a simple
693 /// propagation heuristic. The following rules are applied to every
694 /// block BB in the CFG:
696 /// - If BB has a single predecessor/successor, then the weight
697 /// of that edge is the weight of the block.
699 /// - If all the edges are known except one, and the weight of the
700 /// block is already known, the weight of the unknown edge will
701 /// be the weight of the block minus the sum of all the known
702 /// edges. If the sum of all the known edges is larger than BB's weight,
703 /// we set the unknown edge weight to zero.
705 /// - If there is a self-referential edge, and the weight of the block is
706 /// known, the weight for that edge is set to the weight of the block
707 /// minus the weight of the other incoming edges to that block (if
710 /// Since this propagation is not guaranteed to finalize for every CFG, we
711 /// only allow it to proceed for a limited number of iterations (controlled
712 /// by -sample-profile-max-propagate-iterations).
714 /// FIXME: Try to replace this propagation heuristic with a scheme
715 /// that is guaranteed to finalize. A work-list approach similar to
716 /// the standard value propagation algorithm used by SSA-CCP might
719 /// Once all the branch weights are computed, we emit the MD_prof
720 /// metadata on BB using the computed values for each of its branches.
722 /// \param F The function to query.
724 /// \returns true if \p F was modified. Returns false, otherwise.
725 bool SampleProfileLoader::emitAnnotations(Function &F) {
726 bool Changed = false;
728 // Initialize invariants used during computation and propagation.
729 HeaderLineno = getFunctionLoc(F);
730 if (HeaderLineno == 0)
733 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
734 << ": " << HeaderLineno << "\n");
736 // Compute basic block weights.
737 Changed |= computeBlockWeights(F);
740 // Compute dominance and loop info needed for propagation.
741 computeDominanceAndLoopInfo(F);
743 // Find equivalence classes.
744 findEquivalenceClasses(F);
746 // Propagate weights to all edges.
753 char SampleProfileLoader::ID = 0;
754 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
755 "Sample Profile loader", false, false)
756 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
757 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
758 "Sample Profile loader", false, false)
760 bool SampleProfileLoader::doInitialization(Module &M) {
761 auto &Ctx = M.getContext();
762 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
763 if (std::error_code EC = ReaderOrErr.getError()) {
764 std::string Msg = "Could not open profile: " + EC.message();
765 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
768 Reader = std::move(ReaderOrErr.get());
769 ProfileIsValid = (Reader->read() == sampleprof_error::success);
773 ModulePass *llvm::createSampleProfileLoaderPass() {
774 return new SampleProfileLoader(SampleProfileFile);
777 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
778 return new SampleProfileLoader(Name);
781 bool SampleProfileLoader::runOnModule(Module &M) {
784 if (!F.isDeclaration())
785 retval |= runOnFunction(F);
789 bool SampleProfileLoader::runOnFunction(Function &F) {
793 Samples = Reader->getSamplesFor(F);
794 if (!Samples->empty())
795 return emitAnnotations(F);