LLVM API Documentation
00001 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the SampleProfileLoader transformation. This pass 00011 // reads a profile file generated by a sampling profiler (e.g. Linux Perf - 00012 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the 00013 // profile information in the given profile. 00014 // 00015 // This pass generates branch weight annotations on the IR: 00016 // 00017 // - prof: Represents branch weights. This annotation is added to branches 00018 // to indicate the weights of each edge coming out of the branch. 00019 // The weight of each edge is the weight of the target block for 00020 // that edge. The weight of a block B is computed as the maximum 00021 // number of samples found in B. 00022 // 00023 //===----------------------------------------------------------------------===// 00024 00025 #include "llvm/Transforms/Scalar.h" 00026 #include "llvm/ADT/DenseMap.h" 00027 #include "llvm/ADT/SmallPtrSet.h" 00028 #include "llvm/ADT/SmallSet.h" 00029 #include "llvm/ADT/StringRef.h" 00030 #include "llvm/Analysis/LoopInfo.h" 00031 #include "llvm/Analysis/PostDominators.h" 00032 #include "llvm/IR/Constants.h" 00033 #include "llvm/IR/DebugInfo.h" 00034 #include "llvm/IR/DiagnosticInfo.h" 00035 #include "llvm/IR/Dominators.h" 00036 #include "llvm/IR/Function.h" 00037 #include "llvm/IR/InstIterator.h" 00038 #include "llvm/IR/Instructions.h" 00039 #include "llvm/IR/LLVMContext.h" 00040 #include "llvm/IR/MDBuilder.h" 00041 #include "llvm/IR/Metadata.h" 00042 #include "llvm/IR/Module.h" 00043 #include "llvm/Pass.h" 00044 #include "llvm/ProfileData/SampleProfReader.h" 00045 #include "llvm/Support/CommandLine.h" 00046 #include "llvm/Support/Debug.h" 00047 #include "llvm/Support/raw_ostream.h" 00048 #include <cctype> 00049 00050 using namespace llvm; 00051 using namespace sampleprof; 00052 00053 #define DEBUG_TYPE "sample-profile" 00054 00055 // Command line option to specify the file to read samples from. This is 00056 // mainly used for debugging. 00057 static cl::opt<std::string> SampleProfileFile( 00058 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 00059 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 00060 static cl::opt<unsigned> SampleProfileMaxPropagateIterations( 00061 "sample-profile-max-propagate-iterations", cl::init(100), 00062 cl::desc("Maximum number of iterations to go through when propagating " 00063 "sample block/edge weights through the CFG.")); 00064 00065 namespace { 00066 typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap; 00067 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap; 00068 typedef std::pair<BasicBlock *, BasicBlock *> Edge; 00069 typedef DenseMap<Edge, unsigned> EdgeWeightMap; 00070 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap; 00071 00072 /// \brief Sample profile pass. 00073 /// 00074 /// This pass reads profile data from the file specified by 00075 /// -sample-profile-file and annotates every affected function with the 00076 /// profile information found in that file. 00077 class SampleProfileLoader : public FunctionPass { 00078 public: 00079 // Class identification, replacement for typeinfo 00080 static char ID; 00081 00082 SampleProfileLoader(StringRef Name = SampleProfileFile) 00083 : FunctionPass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Ctx(nullptr), 00084 Reader(), Samples(nullptr), Filename(Name), ProfileIsValid(false) { 00085 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry()); 00086 } 00087 00088 bool doInitialization(Module &M) override; 00089 00090 void dump() { Reader->dump(); } 00091 00092 const char *getPassName() const override { return "Sample profile pass"; } 00093 00094 bool runOnFunction(Function &F) override; 00095 00096 void getAnalysisUsage(AnalysisUsage &AU) const override { 00097 AU.setPreservesCFG(); 00098 AU.addRequired<LoopInfo>(); 00099 AU.addRequired<DominatorTreeWrapperPass>(); 00100 AU.addRequired<PostDominatorTree>(); 00101 } 00102 00103 protected: 00104 unsigned getFunctionLoc(Function &F); 00105 bool emitAnnotations(Function &F); 00106 unsigned getInstWeight(Instruction &I); 00107 unsigned getBlockWeight(BasicBlock *B); 00108 void printEdgeWeight(raw_ostream &OS, Edge E); 00109 void printBlockWeight(raw_ostream &OS, BasicBlock *BB); 00110 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB); 00111 bool computeBlockWeights(Function &F); 00112 void findEquivalenceClasses(Function &F); 00113 void findEquivalencesFor(BasicBlock *BB1, 00114 SmallVector<BasicBlock *, 8> Descendants, 00115 DominatorTreeBase<BasicBlock> *DomTree); 00116 void propagateWeights(Function &F); 00117 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); 00118 void buildEdges(Function &F); 00119 bool propagateThroughEdges(Function &F); 00120 00121 /// \brief Line number for the function header. Used to compute absolute 00122 /// line numbers from the relative line numbers found in the profile. 00123 unsigned HeaderLineno; 00124 00125 /// \brief Map basic blocks to their computed weights. 00126 /// 00127 /// The weight of a basic block is defined to be the maximum 00128 /// of all the instruction weights in that block. 00129 BlockWeightMap BlockWeights; 00130 00131 /// \brief Map edges to their computed weights. 00132 /// 00133 /// Edge weights are computed by propagating basic block weights in 00134 /// SampleProfile::propagateWeights. 00135 EdgeWeightMap EdgeWeights; 00136 00137 /// \brief Set of visited blocks during propagation. 00138 SmallPtrSet<BasicBlock *, 128> VisitedBlocks; 00139 00140 /// \brief Set of visited edges during propagation. 00141 SmallSet<Edge, 128> VisitedEdges; 00142 00143 /// \brief Equivalence classes for block weights. 00144 /// 00145 /// Two blocks BB1 and BB2 are in the same equivalence class if they 00146 /// dominate and post-dominate each other, and they are in the same loop 00147 /// nest. When this happens, the two blocks are guaranteed to execute 00148 /// the same number of times. 00149 EquivalenceClassMap EquivalenceClass; 00150 00151 /// \brief Dominance, post-dominance and loop information. 00152 DominatorTree *DT; 00153 PostDominatorTree *PDT; 00154 LoopInfo *LI; 00155 00156 /// \brief Predecessors for each basic block in the CFG. 00157 BlockEdgeMap Predecessors; 00158 00159 /// \brief Successors for each basic block in the CFG. 00160 BlockEdgeMap Successors; 00161 00162 /// \brief LLVM context holding the debug data we need. 00163 LLVMContext *Ctx; 00164 00165 /// \brief Profile reader object. 00166 std::unique_ptr<SampleProfileReader> Reader; 00167 00168 /// \brief Samples collected for the body of this function. 00169 FunctionSamples *Samples; 00170 00171 /// \brief Name of the profile file to load. 00172 StringRef Filename; 00173 00174 /// \brief Flag indicating whether the profile input loaded successfully. 00175 bool ProfileIsValid; 00176 }; 00177 } 00178 00179 /// \brief Print the weight of edge \p E on stream \p OS. 00180 /// 00181 /// \param OS Stream to emit the output to. 00182 /// \param E Edge to print. 00183 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { 00184 OS << "weight[" << E.first->getName() << "->" << E.second->getName() 00185 << "]: " << EdgeWeights[E] << "\n"; 00186 } 00187 00188 /// \brief Print the equivalence class of block \p BB on stream \p OS. 00189 /// 00190 /// \param OS Stream to emit the output to. 00191 /// \param BB Block to print. 00192 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, 00193 BasicBlock *BB) { 00194 BasicBlock *Equiv = EquivalenceClass[BB]; 00195 OS << "equivalence[" << BB->getName() 00196 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; 00197 } 00198 00199 /// \brief Print the weight of block \p BB on stream \p OS. 00200 /// 00201 /// \param OS Stream to emit the output to. 00202 /// \param BB Block to print. 00203 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, BasicBlock *BB) { 00204 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n"; 00205 } 00206 00207 /// \brief Get the weight for an instruction. 00208 /// 00209 /// The "weight" of an instruction \p Inst is the number of samples 00210 /// collected on that instruction at runtime. To retrieve it, we 00211 /// need to compute the line number of \p Inst relative to the start of its 00212 /// function. We use HeaderLineno to compute the offset. We then 00213 /// look up the samples collected for \p Inst using BodySamples. 00214 /// 00215 /// \param Inst Instruction to query. 00216 /// 00217 /// \returns The profiled weight of I. 00218 unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) { 00219 DebugLoc DLoc = Inst.getDebugLoc(); 00220 unsigned Lineno = DLoc.getLine(); 00221 if (Lineno < HeaderLineno) 00222 return 0; 00223 00224 DILocation DIL(DLoc.getAsMDNode(*Ctx)); 00225 int LOffset = Lineno - HeaderLineno; 00226 unsigned Discriminator = DIL.getDiscriminator(); 00227 unsigned Weight = Samples->samplesAt(LOffset, Discriminator); 00228 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst 00229 << " (line offset: " << LOffset << "." << Discriminator 00230 << " - weight: " << Weight << ")\n"); 00231 return Weight; 00232 } 00233 00234 /// \brief Compute the weight of a basic block. 00235 /// 00236 /// The weight of basic block \p B is the maximum weight of all the 00237 /// instructions in B. The weight of \p B is computed and cached in 00238 /// the BlockWeights map. 00239 /// 00240 /// \param B The basic block to query. 00241 /// 00242 /// \returns The computed weight of B. 00243 unsigned SampleProfileLoader::getBlockWeight(BasicBlock *B) { 00244 // If we've computed B's weight before, return it. 00245 std::pair<BlockWeightMap::iterator, bool> Entry = 00246 BlockWeights.insert(std::make_pair(B, 0)); 00247 if (!Entry.second) 00248 return Entry.first->second; 00249 00250 // Otherwise, compute and cache B's weight. 00251 unsigned Weight = 0; 00252 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) { 00253 unsigned InstWeight = getInstWeight(*I); 00254 if (InstWeight > Weight) 00255 Weight = InstWeight; 00256 } 00257 Entry.first->second = Weight; 00258 return Weight; 00259 } 00260 00261 /// \brief Compute and store the weights of every basic block. 00262 /// 00263 /// This populates the BlockWeights map by computing 00264 /// the weights of every basic block in the CFG. 00265 /// 00266 /// \param F The function to query. 00267 bool SampleProfileLoader::computeBlockWeights(Function &F) { 00268 bool Changed = false; 00269 DEBUG(dbgs() << "Block weights\n"); 00270 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) { 00271 unsigned Weight = getBlockWeight(B); 00272 Changed |= (Weight > 0); 00273 DEBUG(printBlockWeight(dbgs(), B)); 00274 } 00275 00276 return Changed; 00277 } 00278 00279 /// \brief Find equivalence classes for the given block. 00280 /// 00281 /// This finds all the blocks that are guaranteed to execute the same 00282 /// number of times as \p BB1. To do this, it traverses all the the 00283 /// descendants of \p BB1 in the dominator or post-dominator tree. 00284 /// 00285 /// A block BB2 will be in the same equivalence class as \p BB1 if 00286 /// the following holds: 00287 /// 00288 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 00289 /// is a descendant of \p BB1 in the dominator tree, then BB2 should 00290 /// dominate BB1 in the post-dominator tree. 00291 /// 00292 /// 2- Both BB2 and \p BB1 must be in the same loop. 00293 /// 00294 /// For every block BB2 that meets those two requirements, we set BB2's 00295 /// equivalence class to \p BB1. 00296 /// 00297 /// \param BB1 Block to check. 00298 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. 00299 /// \param DomTree Opposite dominator tree. If \p Descendants is filled 00300 /// with blocks from \p BB1's dominator tree, then 00301 /// this is the post-dominator tree, and vice versa. 00302 void SampleProfileLoader::findEquivalencesFor( 00303 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants, 00304 DominatorTreeBase<BasicBlock> *DomTree) { 00305 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(), 00306 E = Descendants.end(); 00307 I != E; ++I) { 00308 BasicBlock *BB2 = *I; 00309 bool IsDomParent = DomTree->dominates(BB2, BB1); 00310 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); 00311 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent && 00312 IsInSameLoop) { 00313 EquivalenceClass[BB2] = BB1; 00314 00315 // If BB2 is heavier than BB1, make BB2 have the same weight 00316 // as BB1. 00317 // 00318 // Note that we don't worry about the opposite situation here 00319 // (when BB2 is lighter than BB1). We will deal with this 00320 // during the propagation phase. Right now, we just want to 00321 // make sure that BB1 has the largest weight of all the 00322 // members of its equivalence set. 00323 unsigned &BB1Weight = BlockWeights[BB1]; 00324 unsigned &BB2Weight = BlockWeights[BB2]; 00325 BB1Weight = std::max(BB1Weight, BB2Weight); 00326 } 00327 } 00328 } 00329 00330 /// \brief Find equivalence classes. 00331 /// 00332 /// Since samples may be missing from blocks, we can fill in the gaps by setting 00333 /// the weights of all the blocks in the same equivalence class to the same 00334 /// weight. To compute the concept of equivalence, we use dominance and loop 00335 /// information. Two blocks B1 and B2 are in the same equivalence class if B1 00336 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 00337 /// 00338 /// \param F The function to query. 00339 void SampleProfileLoader::findEquivalenceClasses(Function &F) { 00340 SmallVector<BasicBlock *, 8> DominatedBBs; 00341 DEBUG(dbgs() << "\nBlock equivalence classes\n"); 00342 // Find equivalence sets based on dominance and post-dominance information. 00343 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) { 00344 BasicBlock *BB1 = B; 00345 00346 // Compute BB1's equivalence class once. 00347 if (EquivalenceClass.count(BB1)) { 00348 DEBUG(printBlockEquivalence(dbgs(), BB1)); 00349 continue; 00350 } 00351 00352 // By default, blocks are in their own equivalence class. 00353 EquivalenceClass[BB1] = BB1; 00354 00355 // Traverse all the blocks dominated by BB1. We are looking for 00356 // every basic block BB2 such that: 00357 // 00358 // 1- BB1 dominates BB2. 00359 // 2- BB2 post-dominates BB1. 00360 // 3- BB1 and BB2 are in the same loop nest. 00361 // 00362 // If all those conditions hold, it means that BB2 is executed 00363 // as many times as BB1, so they are placed in the same equivalence 00364 // class by making BB2's equivalence class be BB1. 00365 DominatedBBs.clear(); 00366 DT->getDescendants(BB1, DominatedBBs); 00367 findEquivalencesFor(BB1, DominatedBBs, PDT->DT); 00368 00369 // Repeat the same logic for all the blocks post-dominated by BB1. 00370 // We are looking for every basic block BB2 such that: 00371 // 00372 // 1- BB1 post-dominates BB2. 00373 // 2- BB2 dominates BB1. 00374 // 3- BB1 and BB2 are in the same loop nest. 00375 // 00376 // If all those conditions hold, BB2's equivalence class is BB1. 00377 DominatedBBs.clear(); 00378 PDT->getDescendants(BB1, DominatedBBs); 00379 findEquivalencesFor(BB1, DominatedBBs, DT); 00380 00381 DEBUG(printBlockEquivalence(dbgs(), BB1)); 00382 } 00383 00384 // Assign weights to equivalence classes. 00385 // 00386 // All the basic blocks in the same equivalence class will execute 00387 // the same number of times. Since we know that the head block in 00388 // each equivalence class has the largest weight, assign that weight 00389 // to all the blocks in that equivalence class. 00390 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n"); 00391 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) { 00392 BasicBlock *BB = B; 00393 BasicBlock *EquivBB = EquivalenceClass[BB]; 00394 if (BB != EquivBB) 00395 BlockWeights[BB] = BlockWeights[EquivBB]; 00396 DEBUG(printBlockWeight(dbgs(), BB)); 00397 } 00398 } 00399 00400 /// \brief Visit the given edge to decide if it has a valid weight. 00401 /// 00402 /// If \p E has not been visited before, we copy to \p UnknownEdge 00403 /// and increment the count of unknown edges. 00404 /// 00405 /// \param E Edge to visit. 00406 /// \param NumUnknownEdges Current number of unknown edges. 00407 /// \param UnknownEdge Set if E has not been visited before. 00408 /// 00409 /// \returns E's weight, if known. Otherwise, return 0. 00410 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, 00411 Edge *UnknownEdge) { 00412 if (!VisitedEdges.count(E)) { 00413 (*NumUnknownEdges)++; 00414 *UnknownEdge = E; 00415 return 0; 00416 } 00417 00418 return EdgeWeights[E]; 00419 } 00420 00421 /// \brief Propagate weights through incoming/outgoing edges. 00422 /// 00423 /// If the weight of a basic block is known, and there is only one edge 00424 /// with an unknown weight, we can calculate the weight of that edge. 00425 /// 00426 /// Similarly, if all the edges have a known count, we can calculate the 00427 /// count of the basic block, if needed. 00428 /// 00429 /// \param F Function to process. 00430 /// 00431 /// \returns True if new weights were assigned to edges or blocks. 00432 bool SampleProfileLoader::propagateThroughEdges(Function &F) { 00433 bool Changed = false; 00434 DEBUG(dbgs() << "\nPropagation through edges\n"); 00435 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) { 00436 BasicBlock *BB = BI; 00437 00438 // Visit all the predecessor and successor edges to determine 00439 // which ones have a weight assigned already. Note that it doesn't 00440 // matter that we only keep track of a single unknown edge. The 00441 // only case we are interested in handling is when only a single 00442 // edge is unknown (see setEdgeOrBlockWeight). 00443 for (unsigned i = 0; i < 2; i++) { 00444 unsigned TotalWeight = 0; 00445 unsigned NumUnknownEdges = 0; 00446 Edge UnknownEdge, SelfReferentialEdge; 00447 00448 if (i == 0) { 00449 // First, visit all predecessor edges. 00450 for (size_t I = 0; I < Predecessors[BB].size(); I++) { 00451 Edge E = std::make_pair(Predecessors[BB][I], BB); 00452 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 00453 if (E.first == E.second) 00454 SelfReferentialEdge = E; 00455 } 00456 } else { 00457 // On the second round, visit all successor edges. 00458 for (size_t I = 0; I < Successors[BB].size(); I++) { 00459 Edge E = std::make_pair(BB, Successors[BB][I]); 00460 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 00461 } 00462 } 00463 00464 // After visiting all the edges, there are three cases that we 00465 // can handle immediately: 00466 // 00467 // - All the edge weights are known (i.e., NumUnknownEdges == 0). 00468 // In this case, we simply check that the sum of all the edges 00469 // is the same as BB's weight. If not, we change BB's weight 00470 // to match. Additionally, if BB had not been visited before, 00471 // we mark it visited. 00472 // 00473 // - Only one edge is unknown and BB has already been visited. 00474 // In this case, we can compute the weight of the edge by 00475 // subtracting the total block weight from all the known 00476 // edge weights. If the edges weight more than BB, then the 00477 // edge of the last remaining edge is set to zero. 00478 // 00479 // - There exists a self-referential edge and the weight of BB is 00480 // known. In this case, this edge can be based on BB's weight. 00481 // We add up all the other known edges and set the weight on 00482 // the self-referential edge as we did in the previous case. 00483 // 00484 // In any other case, we must continue iterating. Eventually, 00485 // all edges will get a weight, or iteration will stop when 00486 // it reaches SampleProfileMaxPropagateIterations. 00487 if (NumUnknownEdges <= 1) { 00488 unsigned &BBWeight = BlockWeights[BB]; 00489 if (NumUnknownEdges == 0) { 00490 // If we already know the weight of all edges, the weight of the 00491 // basic block can be computed. It should be no larger than the sum 00492 // of all edge weights. 00493 if (TotalWeight > BBWeight) { 00494 BBWeight = TotalWeight; 00495 Changed = true; 00496 DEBUG(dbgs() << "All edge weights for " << BB->getName() 00497 << " known. Set weight for block: "; 00498 printBlockWeight(dbgs(), BB);); 00499 } 00500 if (VisitedBlocks.insert(BB)) 00501 Changed = true; 00502 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) { 00503 // If there is a single unknown edge and the block has been 00504 // visited, then we can compute E's weight. 00505 if (BBWeight >= TotalWeight) 00506 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; 00507 else 00508 EdgeWeights[UnknownEdge] = 0; 00509 VisitedEdges.insert(UnknownEdge); 00510 Changed = true; 00511 DEBUG(dbgs() << "Set weight for edge: "; 00512 printEdgeWeight(dbgs(), UnknownEdge)); 00513 } 00514 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) { 00515 unsigned &BBWeight = BlockWeights[BB]; 00516 // We have a self-referential edge and the weight of BB is known. 00517 if (BBWeight >= TotalWeight) 00518 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; 00519 else 00520 EdgeWeights[SelfReferentialEdge] = 0; 00521 VisitedEdges.insert(SelfReferentialEdge); 00522 Changed = true; 00523 DEBUG(dbgs() << "Set self-referential edge weight to: "; 00524 printEdgeWeight(dbgs(), SelfReferentialEdge)); 00525 } 00526 } 00527 } 00528 00529 return Changed; 00530 } 00531 00532 /// \brief Build in/out edge lists for each basic block in the CFG. 00533 /// 00534 /// We are interested in unique edges. If a block B1 has multiple 00535 /// edges to another block B2, we only add a single B1->B2 edge. 00536 void SampleProfileLoader::buildEdges(Function &F) { 00537 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 00538 BasicBlock *B1 = I; 00539 00540 // Add predecessors for B1. 00541 SmallPtrSet<BasicBlock *, 16> Visited; 00542 if (!Predecessors[B1].empty()) 00543 llvm_unreachable("Found a stale predecessors list in a basic block."); 00544 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { 00545 BasicBlock *B2 = *PI; 00546 if (Visited.insert(B2)) 00547 Predecessors[B1].push_back(B2); 00548 } 00549 00550 // Add successors for B1. 00551 Visited.clear(); 00552 if (!Successors[B1].empty()) 00553 llvm_unreachable("Found a stale successors list in a basic block."); 00554 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { 00555 BasicBlock *B2 = *SI; 00556 if (Visited.insert(B2)) 00557 Successors[B1].push_back(B2); 00558 } 00559 } 00560 } 00561 00562 /// \brief Propagate weights into edges 00563 /// 00564 /// The following rules are applied to every block B in the CFG: 00565 /// 00566 /// - If B has a single predecessor/successor, then the weight 00567 /// of that edge is the weight of the block. 00568 /// 00569 /// - If all incoming or outgoing edges are known except one, and the 00570 /// weight of the block is already known, the weight of the unknown 00571 /// edge will be the weight of the block minus the sum of all the known 00572 /// edges. If the sum of all the known edges is larger than B's weight, 00573 /// we set the unknown edge weight to zero. 00574 /// 00575 /// - If there is a self-referential edge, and the weight of the block is 00576 /// known, the weight for that edge is set to the weight of the block 00577 /// minus the weight of the other incoming edges to that block (if 00578 /// known). 00579 void SampleProfileLoader::propagateWeights(Function &F) { 00580 bool Changed = true; 00581 unsigned i = 0; 00582 00583 // Before propagation starts, build, for each block, a list of 00584 // unique predecessors and successors. This is necessary to handle 00585 // identical edges in multiway branches. Since we visit all blocks and all 00586 // edges of the CFG, it is cleaner to build these lists once at the start 00587 // of the pass. 00588 buildEdges(F); 00589 00590 // Propagate until we converge or we go past the iteration limit. 00591 while (Changed && i++ < SampleProfileMaxPropagateIterations) { 00592 Changed = propagateThroughEdges(F); 00593 } 00594 00595 // Generate MD_prof metadata for every branch instruction using the 00596 // edge weights computed during propagation. 00597 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 00598 MDBuilder MDB(F.getContext()); 00599 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 00600 BasicBlock *B = I; 00601 TerminatorInst *TI = B->getTerminator(); 00602 if (TI->getNumSuccessors() == 1) 00603 continue; 00604 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 00605 continue; 00606 00607 DEBUG(dbgs() << "\nGetting weights for branch at line " 00608 << TI->getDebugLoc().getLine() << ".\n"); 00609 SmallVector<unsigned, 4> Weights; 00610 bool AllWeightsZero = true; 00611 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 00612 BasicBlock *Succ = TI->getSuccessor(I); 00613 Edge E = std::make_pair(B, Succ); 00614 unsigned Weight = EdgeWeights[E]; 00615 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 00616 Weights.push_back(Weight); 00617 if (Weight != 0) 00618 AllWeightsZero = false; 00619 } 00620 00621 // Only set weights if there is at least one non-zero weight. 00622 // In any other case, let the analyzer set weights. 00623 if (!AllWeightsZero) { 00624 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 00625 TI->setMetadata(llvm::LLVMContext::MD_prof, 00626 MDB.createBranchWeights(Weights)); 00627 } else { 00628 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 00629 } 00630 } 00631 } 00632 00633 /// \brief Get the line number for the function header. 00634 /// 00635 /// This looks up function \p F in the current compilation unit and 00636 /// retrieves the line number where the function is defined. This is 00637 /// line 0 for all the samples read from the profile file. Every line 00638 /// number is relative to this line. 00639 /// 00640 /// \param F Function object to query. 00641 /// 00642 /// \returns the line number where \p F is defined. If it returns 0, 00643 /// it means that there is no debug information available for \p F. 00644 unsigned SampleProfileLoader::getFunctionLoc(Function &F) { 00645 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu"); 00646 if (CUNodes) { 00647 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) { 00648 DICompileUnit CU(CUNodes->getOperand(I)); 00649 DIArray Subprograms = CU.getSubprograms(); 00650 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) { 00651 DISubprogram Subprogram(Subprograms.getElement(J)); 00652 if (Subprogram.describes(&F)) 00653 return Subprogram.getLineNumber(); 00654 } 00655 } 00656 } 00657 00658 F.getContext().diagnose(DiagnosticInfoSampleProfile( 00659 "No debug information found in function " + F.getName())); 00660 return 0; 00661 } 00662 00663 /// \brief Generate branch weight metadata for all branches in \p F. 00664 /// 00665 /// Branch weights are computed out of instruction samples using a 00666 /// propagation heuristic. Propagation proceeds in 3 phases: 00667 /// 00668 /// 1- Assignment of block weights. All the basic blocks in the function 00669 /// are initial assigned the same weight as their most frequently 00670 /// executed instruction. 00671 /// 00672 /// 2- Creation of equivalence classes. Since samples may be missing from 00673 /// blocks, we can fill in the gaps by setting the weights of all the 00674 /// blocks in the same equivalence class to the same weight. To compute 00675 /// the concept of equivalence, we use dominance and loop information. 00676 /// Two blocks B1 and B2 are in the same equivalence class if B1 00677 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 00678 /// 00679 /// 3- Propagation of block weights into edges. This uses a simple 00680 /// propagation heuristic. The following rules are applied to every 00681 /// block B in the CFG: 00682 /// 00683 /// - If B has a single predecessor/successor, then the weight 00684 /// of that edge is the weight of the block. 00685 /// 00686 /// - If all the edges are known except one, and the weight of the 00687 /// block is already known, the weight of the unknown edge will 00688 /// be the weight of the block minus the sum of all the known 00689 /// edges. If the sum of all the known edges is larger than B's weight, 00690 /// we set the unknown edge weight to zero. 00691 /// 00692 /// - If there is a self-referential edge, and the weight of the block is 00693 /// known, the weight for that edge is set to the weight of the block 00694 /// minus the weight of the other incoming edges to that block (if 00695 /// known). 00696 /// 00697 /// Since this propagation is not guaranteed to finalize for every CFG, we 00698 /// only allow it to proceed for a limited number of iterations (controlled 00699 /// by -sample-profile-max-propagate-iterations). 00700 /// 00701 /// FIXME: Try to replace this propagation heuristic with a scheme 00702 /// that is guaranteed to finalize. A work-list approach similar to 00703 /// the standard value propagation algorithm used by SSA-CCP might 00704 /// work here. 00705 /// 00706 /// Once all the branch weights are computed, we emit the MD_prof 00707 /// metadata on B using the computed values for each of its branches. 00708 /// 00709 /// \param F The function to query. 00710 /// 00711 /// \returns true if \p F was modified. Returns false, otherwise. 00712 bool SampleProfileLoader::emitAnnotations(Function &F) { 00713 bool Changed = false; 00714 00715 // Initialize invariants used during computation and propagation. 00716 HeaderLineno = getFunctionLoc(F); 00717 if (HeaderLineno == 0) 00718 return false; 00719 00720 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName() 00721 << ": " << HeaderLineno << "\n"); 00722 00723 // Compute basic block weights. 00724 Changed |= computeBlockWeights(F); 00725 00726 if (Changed) { 00727 // Find equivalence classes. 00728 findEquivalenceClasses(F); 00729 00730 // Propagate weights to all edges. 00731 propagateWeights(F); 00732 } 00733 00734 return Changed; 00735 } 00736 00737 char SampleProfileLoader::ID = 0; 00738 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile", 00739 "Sample Profile loader", false, false) 00740 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 00741 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree) 00742 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 00743 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators) 00744 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile", 00745 "Sample Profile loader", false, false) 00746 00747 bool SampleProfileLoader::doInitialization(Module &M) { 00748 Reader.reset(new SampleProfileReader(M, Filename)); 00749 ProfileIsValid = Reader->load(); 00750 return true; 00751 } 00752 00753 FunctionPass *llvm::createSampleProfileLoaderPass() { 00754 return new SampleProfileLoader(SampleProfileFile); 00755 } 00756 00757 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) { 00758 return new SampleProfileLoader(Name); 00759 } 00760 00761 bool SampleProfileLoader::runOnFunction(Function &F) { 00762 if (!ProfileIsValid) 00763 return false; 00764 00765 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 00766 PDT = &getAnalysis<PostDominatorTree>(); 00767 LI = &getAnalysis<LoopInfo>(); 00768 Ctx = &F.getParent()->getContext(); 00769 Samples = Reader->getSamplesFor(F); 00770 if (!Samples->empty()) 00771 return emitAnnotations(F); 00772 return false; 00773 }