1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the SampleProfileLoader transformation. This pass 11 // reads a profile file generated by a sampling profiler (e.g. Linux Perf - 12 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the 13 // profile information in the given profile. 14 // 15 // This pass generates branch weight annotations on the IR: 16 // 17 // - prof: Represents branch weights. This annotation is added to branches 18 // to indicate the weights of each edge coming out of the branch. 19 // The weight of each edge is the weight of the target block for 20 // that edge. The weight of a block B is computed as the maximum 21 // number of samples found in B. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #include "llvm/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" 49 #include "llvm/Transforms/Utils/Cloning.h" 50 #include <cctype> 51 52 using namespace llvm; 53 using namespace sampleprof; 54 55 #define DEBUG_TYPE "sample-profile" 56 57 // Command line option to specify the file to read samples from. This is 58 // mainly used for debugging. 59 static cl::opt<std::string> SampleProfileFile( 60 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 61 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 62 static cl::opt<unsigned> SampleProfileMaxPropagateIterations( 63 "sample-profile-max-propagate-iterations", cl::init(100), 64 cl::desc("Maximum number of iterations to go through when propagating " 65 "sample block/edge weights through the CFG.")); 66 67 namespace { 68 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap; 69 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap; 70 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge; 71 typedef DenseMap<Edge, uint64_t> EdgeWeightMap; 72 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>> 73 BlockEdgeMap; 74 75 /// \brief Sample profile pass. 76 /// 77 /// This pass reads profile data from the file specified by 78 /// -sample-profile-file and annotates every affected function with the 79 /// profile information found in that file. 80 class SampleProfileLoader : public ModulePass { 81 public: 82 // Class identification, replacement for typeinfo 83 static char ID; 84 85 SampleProfileLoader(StringRef Name = SampleProfileFile) 86 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(), 87 Samples(nullptr), Filename(Name), ProfileIsValid(false) { 88 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry()); 89 } 90 91 bool doInitialization(Module &M) override; 92 93 void dump() { Reader->dump(); } 94 95 const char *getPassName() const override { return "Sample profile pass"; } 96 97 bool runOnModule(Module &M) override; 98 99 void getAnalysisUsage(AnalysisUsage &AU) const override { 100 AU.setPreservesCFG(); 101 } 102 103 protected: 104 bool runOnFunction(Function &F); 105 unsigned getFunctionLoc(Function &F); 106 bool emitAnnotations(Function &F); 107 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const; 108 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const; 109 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const; 110 const FunctionSamples *findFunctionSamples(const Instruction &I) const; 111 bool inlineHotFunctions(Function &F); 112 void printEdgeWeight(raw_ostream &OS, Edge E); 113 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const; 114 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB); 115 bool computeBlockWeights(Function &F); 116 void findEquivalenceClasses(Function &F); 117 void findEquivalencesFor(BasicBlock *BB1, 118 SmallVector<BasicBlock *, 8> Descendants, 119 DominatorTreeBase<BasicBlock> *DomTree); 120 void propagateWeights(Function &F); 121 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); 122 void buildEdges(Function &F); 123 bool propagateThroughEdges(Function &F); 124 void computeDominanceAndLoopInfo(Function &F); 125 unsigned getOffset(unsigned L, unsigned H) const; 126 127 /// \brief Map basic blocks to their computed weights. 128 /// 129 /// The weight of a basic block is defined to be the maximum 130 /// of all the instruction weights in that block. 131 BlockWeightMap BlockWeights; 132 133 /// \brief Map edges to their computed weights. 134 /// 135 /// Edge weights are computed by propagating basic block weights in 136 /// SampleProfile::propagateWeights. 137 EdgeWeightMap EdgeWeights; 138 139 /// \brief Set of visited blocks during propagation. 140 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks; 141 142 /// \brief Set of visited edges during propagation. 143 SmallSet<Edge, 128> VisitedEdges; 144 145 /// \brief Equivalence classes for block weights. 146 /// 147 /// Two blocks BB1 and BB2 are in the same equivalence class if they 148 /// dominate and post-dominate each other, and they are in the same loop 149 /// nest. When this happens, the two blocks are guaranteed to execute 150 /// the same number of times. 151 EquivalenceClassMap EquivalenceClass; 152 153 /// \brief Dominance, post-dominance and loop information. 154 std::unique_ptr<DominatorTree> DT; 155 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT; 156 std::unique_ptr<LoopInfo> LI; 157 158 /// \brief Predecessors for each basic block in the CFG. 159 BlockEdgeMap Predecessors; 160 161 /// \brief Successors for each basic block in the CFG. 162 BlockEdgeMap Successors; 163 164 /// \brief Profile reader object. 165 std::unique_ptr<SampleProfileReader> Reader; 166 167 /// \brief Samples collected for the body of this function. 168 FunctionSamples *Samples; 169 170 /// \brief Name of the profile file to load. 171 StringRef Filename; 172 173 /// \brief Flag indicating whether the profile input loaded successfully. 174 bool ProfileIsValid; 175 }; 176 } 177 178 /// \brief Returns the offset of lineno \p L to head_lineno \p H 179 /// 180 /// \param L Lineno 181 /// \param H Header lineno of the function 182 /// 183 /// \returns offset to the header lineno. 16 bits are used to represent offset. 184 /// We assume that a single function will not exceed 65535 LOC. 185 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const { 186 return (L - H) & 0xffff; 187 } 188 189 /// \brief Print the weight of edge \p E on stream \p OS. 190 /// 191 /// \param OS Stream to emit the output to. 192 /// \param E Edge to print. 193 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { 194 OS << "weight[" << E.first->getName() << "->" << E.second->getName() 195 << "]: " << EdgeWeights[E] << "\n"; 196 } 197 198 /// \brief Print the equivalence class of block \p BB on stream \p OS. 199 /// 200 /// \param OS Stream to emit the output to. 201 /// \param BB Block to print. 202 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, 203 const BasicBlock *BB) { 204 const BasicBlock *Equiv = EquivalenceClass[BB]; 205 OS << "equivalence[" << BB->getName() 206 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; 207 } 208 209 /// \brief Print the weight of block \p BB on stream \p OS. 210 /// 211 /// \param OS Stream to emit the output to. 212 /// \param BB Block to print. 213 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, 214 const BasicBlock *BB) const { 215 const auto &I = BlockWeights.find(BB); 216 uint64_t W = (I == BlockWeights.end() ? 0 : I->second); 217 OS << "weight[" << BB->getName() << "]: " << W << "\n"; 218 } 219 220 /// \brief Get the weight for an instruction. 221 /// 222 /// The "weight" of an instruction \p Inst is the number of samples 223 /// collected on that instruction at runtime. To retrieve it, we 224 /// need to compute the line number of \p Inst relative to the start of its 225 /// function. We use HeaderLineno to compute the offset. We then 226 /// look up the samples collected for \p Inst using BodySamples. 227 /// 228 /// \param Inst Instruction to query. 229 /// 230 /// \returns the weight of \p Inst. 231 ErrorOr<uint64_t> 232 SampleProfileLoader::getInstWeight(const Instruction &Inst) const { 233 DebugLoc DLoc = Inst.getDebugLoc(); 234 if (!DLoc) 235 return std::error_code(); 236 237 const FunctionSamples *FS = findFunctionSamples(Inst); 238 if (!FS) 239 return std::error_code(); 240 241 const DILocation *DIL = DLoc; 242 unsigned Lineno = DLoc.getLine(); 243 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine(); 244 245 ErrorOr<uint64_t> R = FS->findSamplesAt(getOffset(Lineno, HeaderLineno), 246 DIL->getDiscriminator()); 247 if (R) 248 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":" 249 << Inst << " (line offset: " << Lineno - HeaderLineno << "." 250 << DIL->getDiscriminator() << " - weight: " << R.get() 251 << ")\n"); 252 return R; 253 } 254 255 /// \brief Compute the weight of a basic block. 256 /// 257 /// The weight of basic block \p BB is the maximum weight of all the 258 /// instructions in BB. 259 /// 260 /// \param BB The basic block to query. 261 /// 262 /// \returns the weight for \p BB. 263 ErrorOr<uint64_t> 264 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const { 265 bool Found = false; 266 uint64_t Weight = 0; 267 for (auto &I : BB->getInstList()) { 268 const ErrorOr<uint64_t> &R = getInstWeight(I); 269 if (R && R.get() >= Weight) { 270 Weight = R.get(); 271 Found = true; 272 } 273 } 274 if (Found) 275 return Weight; 276 else 277 return std::error_code(); 278 } 279 280 /// \brief Compute and store the weights of every basic block. 281 /// 282 /// This populates the BlockWeights map by computing 283 /// the weights of every basic block in the CFG. 284 /// 285 /// \param F The function to query. 286 bool SampleProfileLoader::computeBlockWeights(Function &F) { 287 bool Changed = false; 288 DEBUG(dbgs() << "Block weights\n"); 289 for (const auto &BB : F) { 290 ErrorOr<uint64_t> Weight = getBlockWeight(&BB); 291 if (Weight) { 292 BlockWeights[&BB] = Weight.get(); 293 VisitedBlocks.insert(&BB); 294 Changed = true; 295 } 296 DEBUG(printBlockWeight(dbgs(), &BB)); 297 } 298 299 return Changed; 300 } 301 302 /// \brief Get the FunctionSamples for a call instruction. 303 /// 304 /// The FunctionSamples of a call instruction \p Inst is the inlined 305 /// instance in which that call instruction is calling to. It contains 306 /// all samples that resides in the inlined instance. We first find the 307 /// inlined instance in which the call instruction is from, then we 308 /// traverse its children to find the callsite with the matching 309 /// location and callee function name. 310 /// 311 /// \param Inst Call instruction to query. 312 /// 313 /// \returns The FunctionSamples pointer to the inlined instance. 314 const FunctionSamples * 315 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const { 316 const DILocation *DIL = Inst.getDebugLoc(); 317 if (!DIL) { 318 return nullptr; 319 } 320 DISubprogram *SP = DIL->getScope()->getSubprogram(); 321 if (!SP) 322 return nullptr; 323 324 Function *CalleeFunc = Inst.getCalledFunction(); 325 if (!CalleeFunc) { 326 return nullptr; 327 } 328 329 StringRef CalleeName = CalleeFunc->getName(); 330 const FunctionSamples *FS = findFunctionSamples(Inst); 331 if (FS == nullptr) 332 return nullptr; 333 334 return FS->findFunctionSamplesAt( 335 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()), 336 DIL->getDiscriminator(), CalleeName)); 337 } 338 339 /// \brief Get the FunctionSamples for an instruction. 340 /// 341 /// The FunctionSamples of an instruction \p Inst is the inlined instance 342 /// in which that instruction is coming from. We traverse the inline stack 343 /// of that instruction, and match it with the tree nodes in the profile. 344 /// 345 /// \param Inst Instruction to query. 346 /// 347 /// \returns the FunctionSamples pointer to the inlined instance. 348 const FunctionSamples * 349 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { 350 SmallVector<CallsiteLocation, 10> S; 351 const DILocation *DIL = Inst.getDebugLoc(); 352 if (!DIL) { 353 return Samples; 354 } 355 StringRef CalleeName; 356 for (const DILocation *DIL = Inst.getDebugLoc(); DIL; 357 DIL = DIL->getInlinedAt()) { 358 DISubprogram *SP = DIL->getScope()->getSubprogram(); 359 if (!SP) 360 return nullptr; 361 if (!CalleeName.empty()) { 362 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()), 363 DIL->getDiscriminator(), CalleeName)); 364 } 365 CalleeName = SP->getLinkageName(); 366 } 367 if (S.size() == 0) 368 return Samples; 369 const FunctionSamples *FS = Samples; 370 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) { 371 FS = FS->findFunctionSamplesAt(S[i]); 372 } 373 return FS; 374 } 375 376 /// \brief Iteratively inline hot callsites of a function. 377 /// 378 /// Iteratively traverse all callsites of the function \p F, and find if 379 /// the corresponding inlined instance exists and is hot in profile. If 380 /// it is hot enough, inline the callsites and adds new callsites of the 381 /// callee into the caller. 382 /// 383 /// TODO: investigate the possibility of not invoking InlineFunction directly. 384 /// 385 /// \param F function to perform iterative inlining. 386 /// 387 /// \returns True if there is any inline happened. 388 bool SampleProfileLoader::inlineHotFunctions(Function &F) { 389 bool Changed = false; 390 LLVMContext &Ctx = F.getContext(); 391 while (true) { 392 bool LocalChanged = false; 393 SmallVector<CallInst *, 10> CIS; 394 for (auto &BB : F) { 395 for (auto &I : BB.getInstList()) { 396 CallInst *CI = dyn_cast<CallInst>(&I); 397 if (CI) { 398 const FunctionSamples *FS = findCalleeFunctionSamples(*CI); 399 if (FS && FS->getTotalSamples() > 0) { 400 CIS.push_back(CI); 401 } 402 } 403 } 404 } 405 for (auto CI : CIS) { 406 InlineFunctionInfo IFI; 407 Function *CalledFunction = CI->getCalledFunction(); 408 DebugLoc DLoc = CI->getDebugLoc(); 409 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples(); 410 if (InlineFunction(CI, IFI)) { 411 LocalChanged = true; 412 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc, 413 Twine("inlined hot callee '") + 414 CalledFunction->getName() + "' with " + 415 Twine(NumSamples) + " samples into '" + 416 F.getName() + "'"); 417 } 418 } 419 if (LocalChanged) { 420 Changed = true; 421 } else { 422 break; 423 } 424 } 425 return Changed; 426 } 427 428 /// \brief Find equivalence classes for the given block. 429 /// 430 /// This finds all the blocks that are guaranteed to execute the same 431 /// number of times as \p BB1. To do this, it traverses all the 432 /// descendants of \p BB1 in the dominator or post-dominator tree. 433 /// 434 /// A block BB2 will be in the same equivalence class as \p BB1 if 435 /// the following holds: 436 /// 437 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 438 /// is a descendant of \p BB1 in the dominator tree, then BB2 should 439 /// dominate BB1 in the post-dominator tree. 440 /// 441 /// 2- Both BB2 and \p BB1 must be in the same loop. 442 /// 443 /// For every block BB2 that meets those two requirements, we set BB2's 444 /// equivalence class to \p BB1. 445 /// 446 /// \param BB1 Block to check. 447 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. 448 /// \param DomTree Opposite dominator tree. If \p Descendants is filled 449 /// with blocks from \p BB1's dominator tree, then 450 /// this is the post-dominator tree, and vice versa. 451 void SampleProfileLoader::findEquivalencesFor( 452 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants, 453 DominatorTreeBase<BasicBlock> *DomTree) { 454 const BasicBlock *EC = EquivalenceClass[BB1]; 455 uint64_t Weight = BlockWeights[EC]; 456 for (const auto *BB2 : Descendants) { 457 bool IsDomParent = DomTree->dominates(BB2, BB1); 458 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); 459 if (BB1 != BB2 && IsDomParent && IsInSameLoop) { 460 EquivalenceClass[BB2] = EC; 461 462 // If BB2 is heavier than BB1, make BB2 have the same weight 463 // as BB1. 464 // 465 // Note that we don't worry about the opposite situation here 466 // (when BB2 is lighter than BB1). We will deal with this 467 // during the propagation phase. Right now, we just want to 468 // make sure that BB1 has the largest weight of all the 469 // members of its equivalence set. 470 Weight = std::max(Weight, BlockWeights[BB2]); 471 } 472 } 473 BlockWeights[EC] = Weight; 474 } 475 476 /// \brief Find equivalence classes. 477 /// 478 /// Since samples may be missing from blocks, we can fill in the gaps by setting 479 /// the weights of all the blocks in the same equivalence class to the same 480 /// weight. To compute the concept of equivalence, we use dominance and loop 481 /// information. Two blocks B1 and B2 are in the same equivalence class if B1 482 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 483 /// 484 /// \param F The function to query. 485 void SampleProfileLoader::findEquivalenceClasses(Function &F) { 486 SmallVector<BasicBlock *, 8> DominatedBBs; 487 DEBUG(dbgs() << "\nBlock equivalence classes\n"); 488 // Find equivalence sets based on dominance and post-dominance information. 489 for (auto &BB : F) { 490 BasicBlock *BB1 = &BB; 491 492 // Compute BB1's equivalence class once. 493 if (EquivalenceClass.count(BB1)) { 494 DEBUG(printBlockEquivalence(dbgs(), BB1)); 495 continue; 496 } 497 498 // By default, blocks are in their own equivalence class. 499 EquivalenceClass[BB1] = BB1; 500 501 // Traverse all the blocks dominated by BB1. We are looking for 502 // every basic block BB2 such that: 503 // 504 // 1- BB1 dominates BB2. 505 // 2- BB2 post-dominates BB1. 506 // 3- BB1 and BB2 are in the same loop nest. 507 // 508 // If all those conditions hold, it means that BB2 is executed 509 // as many times as BB1, so they are placed in the same equivalence 510 // class by making BB2's equivalence class be BB1. 511 DominatedBBs.clear(); 512 DT->getDescendants(BB1, DominatedBBs); 513 findEquivalencesFor(BB1, DominatedBBs, PDT.get()); 514 515 DEBUG(printBlockEquivalence(dbgs(), BB1)); 516 } 517 518 // Assign weights to equivalence classes. 519 // 520 // All the basic blocks in the same equivalence class will execute 521 // the same number of times. Since we know that the head block in 522 // each equivalence class has the largest weight, assign that weight 523 // to all the blocks in that equivalence class. 524 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n"); 525 for (auto &BI : F) { 526 const BasicBlock *BB = &BI; 527 const BasicBlock *EquivBB = EquivalenceClass[BB]; 528 if (BB != EquivBB) 529 BlockWeights[BB] = BlockWeights[EquivBB]; 530 DEBUG(printBlockWeight(dbgs(), BB)); 531 } 532 } 533 534 /// \brief Visit the given edge to decide if it has a valid weight. 535 /// 536 /// If \p E has not been visited before, we copy to \p UnknownEdge 537 /// and increment the count of unknown edges. 538 /// 539 /// \param E Edge to visit. 540 /// \param NumUnknownEdges Current number of unknown edges. 541 /// \param UnknownEdge Set if E has not been visited before. 542 /// 543 /// \returns E's weight, if known. Otherwise, return 0. 544 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, 545 Edge *UnknownEdge) { 546 if (!VisitedEdges.count(E)) { 547 (*NumUnknownEdges)++; 548 *UnknownEdge = E; 549 return 0; 550 } 551 552 return EdgeWeights[E]; 553 } 554 555 /// \brief Propagate weights through incoming/outgoing edges. 556 /// 557 /// If the weight of a basic block is known, and there is only one edge 558 /// with an unknown weight, we can calculate the weight of that edge. 559 /// 560 /// Similarly, if all the edges have a known count, we can calculate the 561 /// count of the basic block, if needed. 562 /// 563 /// \param F Function to process. 564 /// 565 /// \returns True if new weights were assigned to edges or blocks. 566 bool SampleProfileLoader::propagateThroughEdges(Function &F) { 567 bool Changed = false; 568 DEBUG(dbgs() << "\nPropagation through edges\n"); 569 for (const auto &BI : F) { 570 const BasicBlock *BB = &BI; 571 const BasicBlock *EC = EquivalenceClass[BB]; 572 573 // Visit all the predecessor and successor edges to determine 574 // which ones have a weight assigned already. Note that it doesn't 575 // matter that we only keep track of a single unknown edge. The 576 // only case we are interested in handling is when only a single 577 // edge is unknown (see setEdgeOrBlockWeight). 578 for (unsigned i = 0; i < 2; i++) { 579 uint64_t TotalWeight = 0; 580 unsigned NumUnknownEdges = 0; 581 Edge UnknownEdge, SelfReferentialEdge; 582 583 if (i == 0) { 584 // First, visit all predecessor edges. 585 for (auto *Pred : Predecessors[BB]) { 586 Edge E = std::make_pair(Pred, BB); 587 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 588 if (E.first == E.second) 589 SelfReferentialEdge = E; 590 } 591 } else { 592 // On the second round, visit all successor edges. 593 for (auto *Succ : Successors[BB]) { 594 Edge E = std::make_pair(BB, Succ); 595 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 596 } 597 } 598 599 // After visiting all the edges, there are three cases that we 600 // can handle immediately: 601 // 602 // - All the edge weights are known (i.e., NumUnknownEdges == 0). 603 // In this case, we simply check that the sum of all the edges 604 // is the same as BB's weight. If not, we change BB's weight 605 // to match. Additionally, if BB had not been visited before, 606 // we mark it visited. 607 // 608 // - Only one edge is unknown and BB has already been visited. 609 // In this case, we can compute the weight of the edge by 610 // subtracting the total block weight from all the known 611 // edge weights. If the edges weight more than BB, then the 612 // edge of the last remaining edge is set to zero. 613 // 614 // - There exists a self-referential edge and the weight of BB is 615 // known. In this case, this edge can be based on BB's weight. 616 // We add up all the other known edges and set the weight on 617 // the self-referential edge as we did in the previous case. 618 // 619 // In any other case, we must continue iterating. Eventually, 620 // all edges will get a weight, or iteration will stop when 621 // it reaches SampleProfileMaxPropagateIterations. 622 if (NumUnknownEdges <= 1) { 623 uint64_t &BBWeight = BlockWeights[EC]; 624 if (NumUnknownEdges == 0) { 625 // If we already know the weight of all edges, the weight of the 626 // basic block can be computed. It should be no larger than the sum 627 // of all edge weights. 628 if (TotalWeight > BBWeight) { 629 BBWeight = TotalWeight; 630 Changed = true; 631 DEBUG(dbgs() << "All edge weights for " << BB->getName() 632 << " known. Set weight for block: "; 633 printBlockWeight(dbgs(), BB);); 634 } 635 if (VisitedBlocks.insert(EC).second) 636 Changed = true; 637 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { 638 // If there is a single unknown edge and the block has been 639 // visited, then we can compute E's weight. 640 if (BBWeight >= TotalWeight) 641 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; 642 else 643 EdgeWeights[UnknownEdge] = 0; 644 VisitedEdges.insert(UnknownEdge); 645 Changed = true; 646 DEBUG(dbgs() << "Set weight for edge: "; 647 printEdgeWeight(dbgs(), UnknownEdge)); 648 } 649 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { 650 uint64_t &BBWeight = BlockWeights[BB]; 651 // We have a self-referential edge and the weight of BB is known. 652 if (BBWeight >= TotalWeight) 653 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; 654 else 655 EdgeWeights[SelfReferentialEdge] = 0; 656 VisitedEdges.insert(SelfReferentialEdge); 657 Changed = true; 658 DEBUG(dbgs() << "Set self-referential edge weight to: "; 659 printEdgeWeight(dbgs(), SelfReferentialEdge)); 660 } 661 } 662 } 663 664 return Changed; 665 } 666 667 /// \brief Build in/out edge lists for each basic block in the CFG. 668 /// 669 /// We are interested in unique edges. If a block B1 has multiple 670 /// edges to another block B2, we only add a single B1->B2 edge. 671 void SampleProfileLoader::buildEdges(Function &F) { 672 for (auto &BI : F) { 673 BasicBlock *B1 = &BI; 674 675 // Add predecessors for B1. 676 SmallPtrSet<BasicBlock *, 16> Visited; 677 if (!Predecessors[B1].empty()) 678 llvm_unreachable("Found a stale predecessors list in a basic block."); 679 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { 680 BasicBlock *B2 = *PI; 681 if (Visited.insert(B2).second) 682 Predecessors[B1].push_back(B2); 683 } 684 685 // Add successors for B1. 686 Visited.clear(); 687 if (!Successors[B1].empty()) 688 llvm_unreachable("Found a stale successors list in a basic block."); 689 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { 690 BasicBlock *B2 = *SI; 691 if (Visited.insert(B2).second) 692 Successors[B1].push_back(B2); 693 } 694 } 695 } 696 697 /// \brief Propagate weights into edges 698 /// 699 /// The following rules are applied to every block BB in the CFG: 700 /// 701 /// - If BB has a single predecessor/successor, then the weight 702 /// of that edge is the weight of the block. 703 /// 704 /// - If all incoming or outgoing edges are known except one, and the 705 /// weight of the block is already known, the weight of the unknown 706 /// edge will be the weight of the block minus the sum of all the known 707 /// edges. If the sum of all the known edges is larger than BB's weight, 708 /// we set the unknown edge weight to zero. 709 /// 710 /// - If there is a self-referential edge, and the weight of the block is 711 /// known, the weight for that edge is set to the weight of the block 712 /// minus the weight of the other incoming edges to that block (if 713 /// known). 714 void SampleProfileLoader::propagateWeights(Function &F) { 715 bool Changed = true; 716 unsigned I = 0; 717 718 // Add an entry count to the function using the samples gathered 719 // at the function entry. 720 F.setEntryCount(Samples->getHeadSamples()); 721 722 // Before propagation starts, build, for each block, a list of 723 // unique predecessors and successors. This is necessary to handle 724 // identical edges in multiway branches. Since we visit all blocks and all 725 // edges of the CFG, it is cleaner to build these lists once at the start 726 // of the pass. 727 buildEdges(F); 728 729 // Propagate until we converge or we go past the iteration limit. 730 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 731 Changed = propagateThroughEdges(F); 732 } 733 734 // Generate MD_prof metadata for every branch instruction using the 735 // edge weights computed during propagation. 736 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 737 LLVMContext &Ctx = F.getContext(); 738 MDBuilder MDB(Ctx); 739 for (auto &BI : F) { 740 BasicBlock *BB = &BI; 741 TerminatorInst *TI = BB->getTerminator(); 742 if (TI->getNumSuccessors() == 1) 743 continue; 744 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 745 continue; 746 747 DEBUG(dbgs() << "\nGetting weights for branch at line " 748 << TI->getDebugLoc().getLine() << ".\n"); 749 SmallVector<uint32_t, 4> Weights; 750 uint32_t MaxWeight = 0; 751 DebugLoc MaxDestLoc; 752 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 753 BasicBlock *Succ = TI->getSuccessor(I); 754 Edge E = std::make_pair(BB, Succ); 755 uint64_t Weight = EdgeWeights[E]; 756 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 757 // Use uint32_t saturated arithmetic to adjust the incoming weights, 758 // if needed. Sample counts in profiles are 64-bit unsigned values, 759 // but internally branch weights are expressed as 32-bit values. 760 if (Weight > std::numeric_limits<uint32_t>::max()) { 761 DEBUG(dbgs() << " (saturated due to uint32_t overflow)"); 762 Weight = std::numeric_limits<uint32_t>::max(); 763 } 764 Weights.push_back(static_cast<uint32_t>(Weight)); 765 if (Weight != 0) { 766 if (Weight > MaxWeight) { 767 MaxWeight = Weight; 768 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc(); 769 } 770 } 771 } 772 773 // Only set weights if there is at least one non-zero weight. 774 // In any other case, let the analyzer set weights. 775 if (MaxWeight > 0) { 776 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 777 TI->setMetadata(llvm::LLVMContext::MD_prof, 778 MDB.createBranchWeights(Weights)); 779 DebugLoc BranchLoc = TI->getDebugLoc(); 780 emitOptimizationRemark( 781 Ctx, DEBUG_TYPE, F, MaxDestLoc, 782 Twine("most popular destination for conditional branches at ") + 783 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" + 784 Twine(BranchLoc.getLine()) + ":" + 785 Twine(BranchLoc.getCol())) 786 : Twine("<UNKNOWN LOCATION>"))); 787 } else { 788 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 789 } 790 } 791 } 792 793 /// \brief Get the line number for the function header. 794 /// 795 /// This looks up function \p F in the current compilation unit and 796 /// retrieves the line number where the function is defined. This is 797 /// line 0 for all the samples read from the profile file. Every line 798 /// number is relative to this line. 799 /// 800 /// \param F Function object to query. 801 /// 802 /// \returns the line number where \p F is defined. If it returns 0, 803 /// it means that there is no debug information available for \p F. 804 unsigned SampleProfileLoader::getFunctionLoc(Function &F) { 805 if (DISubprogram *S = getDISubprogram(&F)) 806 return S->getLine(); 807 808 // If the start of \p F is missing, emit a diagnostic to inform the user 809 // about the missed opportunity. 810 F.getContext().diagnose(DiagnosticInfoSampleProfile( 811 "No debug information found in function " + F.getName() + 812 ": Function profile not used", 813 DS_Warning)); 814 return 0; 815 } 816 817 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { 818 DT.reset(new DominatorTree); 819 DT->recalculate(F); 820 821 PDT.reset(new DominatorTreeBase<BasicBlock>(true)); 822 PDT->recalculate(F); 823 824 LI.reset(new LoopInfo); 825 LI->analyze(*DT); 826 } 827 828 /// \brief Generate branch weight metadata for all branches in \p F. 829 /// 830 /// Branch weights are computed out of instruction samples using a 831 /// propagation heuristic. Propagation proceeds in 3 phases: 832 /// 833 /// 1- Assignment of block weights. All the basic blocks in the function 834 /// are initial assigned the same weight as their most frequently 835 /// executed instruction. 836 /// 837 /// 2- Creation of equivalence classes. Since samples may be missing from 838 /// blocks, we can fill in the gaps by setting the weights of all the 839 /// blocks in the same equivalence class to the same weight. To compute 840 /// the concept of equivalence, we use dominance and loop information. 841 /// Two blocks B1 and B2 are in the same equivalence class if B1 842 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 843 /// 844 /// 3- Propagation of block weights into edges. This uses a simple 845 /// propagation heuristic. The following rules are applied to every 846 /// block BB in the CFG: 847 /// 848 /// - If BB has a single predecessor/successor, then the weight 849 /// of that edge is the weight of the block. 850 /// 851 /// - If all the edges are known except one, and the weight of the 852 /// block is already known, the weight of the unknown edge will 853 /// be the weight of the block minus the sum of all the known 854 /// edges. If the sum of all the known edges is larger than BB's weight, 855 /// we set the unknown edge weight to zero. 856 /// 857 /// - If there is a self-referential edge, and the weight of the block is 858 /// known, the weight for that edge is set to the weight of the block 859 /// minus the weight of the other incoming edges to that block (if 860 /// known). 861 /// 862 /// Since this propagation is not guaranteed to finalize for every CFG, we 863 /// only allow it to proceed for a limited number of iterations (controlled 864 /// by -sample-profile-max-propagate-iterations). 865 /// 866 /// FIXME: Try to replace this propagation heuristic with a scheme 867 /// that is guaranteed to finalize. A work-list approach similar to 868 /// the standard value propagation algorithm used by SSA-CCP might 869 /// work here. 870 /// 871 /// Once all the branch weights are computed, we emit the MD_prof 872 /// metadata on BB using the computed values for each of its branches. 873 /// 874 /// \param F The function to query. 875 /// 876 /// \returns true if \p F was modified. Returns false, otherwise. 877 bool SampleProfileLoader::emitAnnotations(Function &F) { 878 bool Changed = false; 879 880 if (getFunctionLoc(F) == 0) 881 return false; 882 883 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName() 884 << ": " << getFunctionLoc(F) << "\n"); 885 886 Changed |= inlineHotFunctions(F); 887 888 // Compute basic block weights. 889 Changed |= computeBlockWeights(F); 890 891 if (Changed) { 892 // Compute dominance and loop info needed for propagation. 893 computeDominanceAndLoopInfo(F); 894 895 // Find equivalence classes. 896 findEquivalenceClasses(F); 897 898 // Propagate weights to all edges. 899 propagateWeights(F); 900 } 901 902 return Changed; 903 } 904 905 char SampleProfileLoader::ID = 0; 906 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile", 907 "Sample Profile loader", false, false) 908 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators) 909 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile", 910 "Sample Profile loader", false, false) 911 912 bool SampleProfileLoader::doInitialization(Module &M) { 913 auto &Ctx = M.getContext(); 914 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx); 915 if (std::error_code EC = ReaderOrErr.getError()) { 916 std::string Msg = "Could not open profile: " + EC.message(); 917 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg)); 918 return false; 919 } 920 Reader = std::move(ReaderOrErr.get()); 921 ProfileIsValid = (Reader->read() == sampleprof_error::success); 922 return true; 923 } 924 925 ModulePass *llvm::createSampleProfileLoaderPass() { 926 return new SampleProfileLoader(SampleProfileFile); 927 } 928 929 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 930 return new SampleProfileLoader(Name); 931 } 932 933 bool SampleProfileLoader::runOnModule(Module &M) { 934 bool retval = false; 935 for (auto &F : M) 936 if (!F.isDeclaration()) 937 retval |= runOnFunction(F); 938 return retval; 939 } 940 941 bool SampleProfileLoader::runOnFunction(Function &F) { 942 if (!ProfileIsValid) 943 return false; 944 945 Samples = Reader->getSamplesFor(F); 946 if (!Samples->empty()) 947 return emitAnnotations(F); 948 return false; 949 } 950