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/Transforms/IPO/SampleProfile.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/DenseSet.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/StringMap.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/ADT/Twine.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/InlineCost.h" 38 #include "llvm/Analysis/LoopInfo.h" 39 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 40 #include "llvm/Analysis/ProfileSummaryInfo.h" 41 #include "llvm/Analysis/TargetTransformInfo.h" 42 #include "llvm/IR/BasicBlock.h" 43 #include "llvm/IR/CFG.h" 44 #include "llvm/IR/CallSite.h" 45 #include "llvm/IR/DebugInfoMetadata.h" 46 #include "llvm/IR/DebugLoc.h" 47 #include "llvm/IR/DiagnosticInfo.h" 48 #include "llvm/IR/Dominators.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalValue.h" 51 #include "llvm/IR/InstrTypes.h" 52 #include "llvm/IR/Instruction.h" 53 #include "llvm/IR/Instructions.h" 54 #include "llvm/IR/IntrinsicInst.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/MDBuilder.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/PassManager.h" 59 #include "llvm/IR/ValueSymbolTable.h" 60 #include "llvm/Pass.h" 61 #include "llvm/ProfileData/InstrProf.h" 62 #include "llvm/ProfileData/SampleProf.h" 63 #include "llvm/ProfileData/SampleProfReader.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/ErrorOr.h" 69 #include "llvm/Support/GenericDomTree.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include "llvm/Transforms/IPO.h" 72 #include "llvm/Transforms/Instrumentation.h" 73 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 74 #include "llvm/Transforms/Utils/Cloning.h" 75 #include <algorithm> 76 #include <cassert> 77 #include <cstdint> 78 #include <functional> 79 #include <limits> 80 #include <map> 81 #include <memory> 82 #include <string> 83 #include <system_error> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 using namespace sampleprof; 89 using ProfileCount = Function::ProfileCount; 90 #define DEBUG_TYPE "sample-profile" 91 92 // Command line option to specify the file to read samples from. This is 93 // mainly used for debugging. 94 static cl::opt<std::string> SampleProfileFile( 95 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 96 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 97 98 static cl::opt<unsigned> SampleProfileMaxPropagateIterations( 99 "sample-profile-max-propagate-iterations", cl::init(100), 100 cl::desc("Maximum number of iterations to go through when propagating " 101 "sample block/edge weights through the CFG.")); 102 103 static cl::opt<unsigned> SampleProfileRecordCoverage( 104 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"), 105 cl::desc("Emit a warning if less than N% of records in the input profile " 106 "are matched to the IR.")); 107 108 static cl::opt<unsigned> SampleProfileSampleCoverage( 109 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"), 110 cl::desc("Emit a warning if less than N% of samples in the input profile " 111 "are matched to the IR.")); 112 113 namespace { 114 115 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>; 116 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>; 117 using Edge = std::pair<const BasicBlock *, const BasicBlock *>; 118 using EdgeWeightMap = DenseMap<Edge, uint64_t>; 119 using BlockEdgeMap = 120 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>; 121 122 class SampleCoverageTracker { 123 public: 124 SampleCoverageTracker() = default; 125 126 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset, 127 uint32_t Discriminator, uint64_t Samples); 128 unsigned computeCoverage(unsigned Used, unsigned Total) const; 129 unsigned countUsedRecords(const FunctionSamples *FS, 130 ProfileSummaryInfo *PSI) const; 131 unsigned countBodyRecords(const FunctionSamples *FS, 132 ProfileSummaryInfo *PSI) const; 133 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; } 134 uint64_t countBodySamples(const FunctionSamples *FS, 135 ProfileSummaryInfo *PSI) const; 136 137 void clear() { 138 SampleCoverage.clear(); 139 TotalUsedSamples = 0; 140 } 141 142 private: 143 using BodySampleCoverageMap = std::map<LineLocation, unsigned>; 144 using FunctionSamplesCoverageMap = 145 DenseMap<const FunctionSamples *, BodySampleCoverageMap>; 146 147 /// Coverage map for sampling records. 148 /// 149 /// This map keeps a record of sampling records that have been matched to 150 /// an IR instruction. This is used to detect some form of staleness in 151 /// profiles (see flag -sample-profile-check-coverage). 152 /// 153 /// Each entry in the map corresponds to a FunctionSamples instance. This is 154 /// another map that counts how many times the sample record at the 155 /// given location has been used. 156 FunctionSamplesCoverageMap SampleCoverage; 157 158 /// Number of samples used from the profile. 159 /// 160 /// When a sampling record is used for the first time, the samples from 161 /// that record are added to this accumulator. Coverage is later computed 162 /// based on the total number of samples available in this function and 163 /// its callsites. 164 /// 165 /// Note that this accumulator tracks samples used from a single function 166 /// and all the inlined callsites. Strictly, we should have a map of counters 167 /// keyed by FunctionSamples pointers, but these stats are cleared after 168 /// every function, so we just need to keep a single counter. 169 uint64_t TotalUsedSamples = 0; 170 }; 171 172 /// Sample profile pass. 173 /// 174 /// This pass reads profile data from the file specified by 175 /// -sample-profile-file and annotates every affected function with the 176 /// profile information found in that file. 177 class SampleProfileLoader { 178 public: 179 SampleProfileLoader( 180 StringRef Name, bool IsThinLTOPreLink, 181 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 182 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo) 183 : GetAC(std::move(GetAssumptionCache)), 184 GetTTI(std::move(GetTargetTransformInfo)), Filename(Name), 185 IsThinLTOPreLink(IsThinLTOPreLink) {} 186 187 bool doInitialization(Module &M); 188 bool runOnModule(Module &M, ModuleAnalysisManager *AM, 189 ProfileSummaryInfo *_PSI); 190 191 void dump() { Reader->dump(); } 192 193 protected: 194 bool runOnFunction(Function &F, ModuleAnalysisManager *AM); 195 unsigned getFunctionLoc(Function &F); 196 bool emitAnnotations(Function &F); 197 ErrorOr<uint64_t> getInstWeight(const Instruction &I); 198 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB); 199 const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const; 200 std::vector<const FunctionSamples *> 201 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const; 202 const FunctionSamples *findFunctionSamples(const Instruction &I) const; 203 bool inlineCallInstruction(Instruction *I); 204 bool inlineHotFunctions(Function &F, 205 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 206 void printEdgeWeight(raw_ostream &OS, Edge E); 207 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const; 208 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB); 209 bool computeBlockWeights(Function &F); 210 void findEquivalenceClasses(Function &F); 211 template <bool IsPostDom> 212 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants, 213 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree); 214 215 void propagateWeights(Function &F); 216 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); 217 void buildEdges(Function &F); 218 bool propagateThroughEdges(Function &F, bool UpdateBlockCount); 219 void computeDominanceAndLoopInfo(Function &F); 220 void clearFunctionData(); 221 222 /// Map basic blocks to their computed weights. 223 /// 224 /// The weight of a basic block is defined to be the maximum 225 /// of all the instruction weights in that block. 226 BlockWeightMap BlockWeights; 227 228 /// Map edges to their computed weights. 229 /// 230 /// Edge weights are computed by propagating basic block weights in 231 /// SampleProfile::propagateWeights. 232 EdgeWeightMap EdgeWeights; 233 234 /// Set of visited blocks during propagation. 235 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks; 236 237 /// Set of visited edges during propagation. 238 SmallSet<Edge, 32> VisitedEdges; 239 240 /// Equivalence classes for block weights. 241 /// 242 /// Two blocks BB1 and BB2 are in the same equivalence class if they 243 /// dominate and post-dominate each other, and they are in the same loop 244 /// nest. When this happens, the two blocks are guaranteed to execute 245 /// the same number of times. 246 EquivalenceClassMap EquivalenceClass; 247 248 /// Map from function name to Function *. Used to find the function from 249 /// the function name. If the function name contains suffix, additional 250 /// entry is added to map from the stripped name to the function if there 251 /// is one-to-one mapping. 252 StringMap<Function *> SymbolMap; 253 254 /// Dominance, post-dominance and loop information. 255 std::unique_ptr<DominatorTree> DT; 256 std::unique_ptr<PostDomTreeBase<BasicBlock>> PDT; 257 std::unique_ptr<LoopInfo> LI; 258 259 std::function<AssumptionCache &(Function &)> GetAC; 260 std::function<TargetTransformInfo &(Function &)> GetTTI; 261 262 /// Predecessors for each basic block in the CFG. 263 BlockEdgeMap Predecessors; 264 265 /// Successors for each basic block in the CFG. 266 BlockEdgeMap Successors; 267 268 SampleCoverageTracker CoverageTracker; 269 270 /// Profile reader object. 271 std::unique_ptr<SampleProfileReader> Reader; 272 273 /// Samples collected for the body of this function. 274 FunctionSamples *Samples = nullptr; 275 276 /// Name of the profile file to load. 277 std::string Filename; 278 279 /// Flag indicating whether the profile input loaded successfully. 280 bool ProfileIsValid = false; 281 282 /// Flag indicating if the pass is invoked in ThinLTO compile phase. 283 /// 284 /// In this phase, in annotation, we should not promote indirect calls. 285 /// Instead, we will mark GUIDs that needs to be annotated to the function. 286 bool IsThinLTOPreLink; 287 288 /// Profile Summary Info computed from sample profile. 289 ProfileSummaryInfo *PSI = nullptr; 290 291 /// Total number of samples collected in this profile. 292 /// 293 /// This is the sum of all the samples collected in all the functions executed 294 /// at runtime. 295 uint64_t TotalCollectedSamples = 0; 296 297 /// Optimization Remark Emitter used to emit diagnostic remarks. 298 OptimizationRemarkEmitter *ORE = nullptr; 299 }; 300 301 class SampleProfileLoaderLegacyPass : public ModulePass { 302 public: 303 // Class identification, replacement for typeinfo 304 static char ID; 305 306 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile, 307 bool IsThinLTOPreLink = false) 308 : ModulePass(ID), SampleLoader(Name, IsThinLTOPreLink, 309 [&](Function &F) -> AssumptionCache & { 310 return ACT->getAssumptionCache(F); 311 }, 312 [&](Function &F) -> TargetTransformInfo & { 313 return TTIWP->getTTI(F); 314 }) { 315 initializeSampleProfileLoaderLegacyPassPass( 316 *PassRegistry::getPassRegistry()); 317 } 318 319 void dump() { SampleLoader.dump(); } 320 321 bool doInitialization(Module &M) override { 322 return SampleLoader.doInitialization(M); 323 } 324 325 StringRef getPassName() const override { return "Sample profile pass"; } 326 bool runOnModule(Module &M) override; 327 328 void getAnalysisUsage(AnalysisUsage &AU) const override { 329 AU.addRequired<AssumptionCacheTracker>(); 330 AU.addRequired<TargetTransformInfoWrapperPass>(); 331 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 332 } 333 334 private: 335 SampleProfileLoader SampleLoader; 336 AssumptionCacheTracker *ACT = nullptr; 337 TargetTransformInfoWrapperPass *TTIWP = nullptr; 338 }; 339 340 } // end anonymous namespace 341 342 /// Return true if the given callsite is hot wrt to hot cutoff threshold. 343 /// 344 /// Functions that were inlined in the original binary will be represented 345 /// in the inline stack in the sample profile. If the profile shows that 346 /// the original inline decision was "good" (i.e., the callsite is executed 347 /// frequently), then we will recreate the inline decision and apply the 348 /// profile from the inlined callsite. 349 /// 350 /// To decide whether an inlined callsite is hot, we compare the callsite 351 /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is 352 /// regarded as hot if the count is above the cutoff value. 353 static bool callsiteIsHot(const FunctionSamples *CallsiteFS, 354 ProfileSummaryInfo *PSI) { 355 if (!CallsiteFS) 356 return false; // The callsite was not inlined in the original binary. 357 358 assert(PSI && "PSI is expected to be non null"); 359 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples(); 360 return PSI->isHotCount(CallsiteTotalSamples); 361 } 362 363 /// Mark as used the sample record for the given function samples at 364 /// (LineOffset, Discriminator). 365 /// 366 /// \returns true if this is the first time we mark the given record. 367 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS, 368 uint32_t LineOffset, 369 uint32_t Discriminator, 370 uint64_t Samples) { 371 LineLocation Loc(LineOffset, Discriminator); 372 unsigned &Count = SampleCoverage[FS][Loc]; 373 bool FirstTime = (++Count == 1); 374 if (FirstTime) 375 TotalUsedSamples += Samples; 376 return FirstTime; 377 } 378 379 /// Return the number of sample records that were applied from this profile. 380 /// 381 /// This count does not include records from cold inlined callsites. 382 unsigned 383 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS, 384 ProfileSummaryInfo *PSI) const { 385 auto I = SampleCoverage.find(FS); 386 387 // The size of the coverage map for FS represents the number of records 388 // that were marked used at least once. 389 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0; 390 391 // If there are inlined callsites in this function, count the samples found 392 // in the respective bodies. However, do not bother counting callees with 0 393 // total samples, these are callees that were never invoked at runtime. 394 for (const auto &I : FS->getCallsiteSamples()) 395 for (const auto &J : I.second) { 396 const FunctionSamples *CalleeSamples = &J.second; 397 if (callsiteIsHot(CalleeSamples, PSI)) 398 Count += countUsedRecords(CalleeSamples, PSI); 399 } 400 401 return Count; 402 } 403 404 /// Return the number of sample records in the body of this profile. 405 /// 406 /// This count does not include records from cold inlined callsites. 407 unsigned 408 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS, 409 ProfileSummaryInfo *PSI) const { 410 unsigned Count = FS->getBodySamples().size(); 411 412 // Only count records in hot callsites. 413 for (const auto &I : FS->getCallsiteSamples()) 414 for (const auto &J : I.second) { 415 const FunctionSamples *CalleeSamples = &J.second; 416 if (callsiteIsHot(CalleeSamples, PSI)) 417 Count += countBodyRecords(CalleeSamples, PSI); 418 } 419 420 return Count; 421 } 422 423 /// Return the number of samples collected in the body of this profile. 424 /// 425 /// This count does not include samples from cold inlined callsites. 426 uint64_t 427 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS, 428 ProfileSummaryInfo *PSI) const { 429 uint64_t Total = 0; 430 for (const auto &I : FS->getBodySamples()) 431 Total += I.second.getSamples(); 432 433 // Only count samples in hot callsites. 434 for (const auto &I : FS->getCallsiteSamples()) 435 for (const auto &J : I.second) { 436 const FunctionSamples *CalleeSamples = &J.second; 437 if (callsiteIsHot(CalleeSamples, PSI)) 438 Total += countBodySamples(CalleeSamples, PSI); 439 } 440 441 return Total; 442 } 443 444 /// Return the fraction of sample records used in this profile. 445 /// 446 /// The returned value is an unsigned integer in the range 0-100 indicating 447 /// the percentage of sample records that were used while applying this 448 /// profile to the associated function. 449 unsigned SampleCoverageTracker::computeCoverage(unsigned Used, 450 unsigned Total) const { 451 assert(Used <= Total && 452 "number of used records cannot exceed the total number of records"); 453 return Total > 0 ? Used * 100 / Total : 100; 454 } 455 456 /// Clear all the per-function data used to load samples and propagate weights. 457 void SampleProfileLoader::clearFunctionData() { 458 BlockWeights.clear(); 459 EdgeWeights.clear(); 460 VisitedBlocks.clear(); 461 VisitedEdges.clear(); 462 EquivalenceClass.clear(); 463 DT = nullptr; 464 PDT = nullptr; 465 LI = nullptr; 466 Predecessors.clear(); 467 Successors.clear(); 468 CoverageTracker.clear(); 469 } 470 471 #ifndef NDEBUG 472 /// Print the weight of edge \p E on stream \p OS. 473 /// 474 /// \param OS Stream to emit the output to. 475 /// \param E Edge to print. 476 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { 477 OS << "weight[" << E.first->getName() << "->" << E.second->getName() 478 << "]: " << EdgeWeights[E] << "\n"; 479 } 480 481 /// Print the equivalence class of block \p BB on stream \p OS. 482 /// 483 /// \param OS Stream to emit the output to. 484 /// \param BB Block to print. 485 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, 486 const BasicBlock *BB) { 487 const BasicBlock *Equiv = EquivalenceClass[BB]; 488 OS << "equivalence[" << BB->getName() 489 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; 490 } 491 492 /// Print the weight of block \p BB on stream \p OS. 493 /// 494 /// \param OS Stream to emit the output to. 495 /// \param BB Block to print. 496 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, 497 const BasicBlock *BB) const { 498 const auto &I = BlockWeights.find(BB); 499 uint64_t W = (I == BlockWeights.end() ? 0 : I->second); 500 OS << "weight[" << BB->getName() << "]: " << W << "\n"; 501 } 502 #endif 503 504 /// Get the weight for an instruction. 505 /// 506 /// The "weight" of an instruction \p Inst is the number of samples 507 /// collected on that instruction at runtime. To retrieve it, we 508 /// need to compute the line number of \p Inst relative to the start of its 509 /// function. We use HeaderLineno to compute the offset. We then 510 /// look up the samples collected for \p Inst using BodySamples. 511 /// 512 /// \param Inst Instruction to query. 513 /// 514 /// \returns the weight of \p Inst. 515 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) { 516 const DebugLoc &DLoc = Inst.getDebugLoc(); 517 if (!DLoc) 518 return std::error_code(); 519 520 const FunctionSamples *FS = findFunctionSamples(Inst); 521 if (!FS) 522 return std::error_code(); 523 524 // Ignore all intrinsics and branch instructions. 525 // Branch instruction usually contains debug info from sources outside of 526 // the residing basic block, thus we ignore them during annotation. 527 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst)) 528 return std::error_code(); 529 530 // If a direct call/invoke instruction is inlined in profile 531 // (findCalleeFunctionSamples returns non-empty result), but not inlined here, 532 // it means that the inlined callsite has no sample, thus the call 533 // instruction should have 0 count. 534 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) && 535 !ImmutableCallSite(&Inst).isIndirectCall() && 536 findCalleeFunctionSamples(Inst)) 537 return 0; 538 539 const DILocation *DIL = DLoc; 540 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 541 uint32_t Discriminator = DIL->getBaseDiscriminator(); 542 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator); 543 if (R) { 544 bool FirstMark = 545 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get()); 546 if (FirstMark) { 547 ORE->emit([&]() { 548 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst); 549 Remark << "Applied " << ore::NV("NumSamples", *R); 550 Remark << " samples from profile (offset: "; 551 Remark << ore::NV("LineOffset", LineOffset); 552 if (Discriminator) { 553 Remark << "."; 554 Remark << ore::NV("Discriminator", Discriminator); 555 } 556 Remark << ")"; 557 return Remark; 558 }); 559 } 560 LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "." 561 << DIL->getBaseDiscriminator() << ":" << Inst 562 << " (line offset: " << LineOffset << "." 563 << DIL->getBaseDiscriminator() << " - weight: " << R.get() 564 << ")\n"); 565 } 566 return R; 567 } 568 569 /// Compute the weight of a basic block. 570 /// 571 /// The weight of basic block \p BB is the maximum weight of all the 572 /// instructions in BB. 573 /// 574 /// \param BB The basic block to query. 575 /// 576 /// \returns the weight for \p BB. 577 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) { 578 uint64_t Max = 0; 579 bool HasWeight = false; 580 for (auto &I : BB->getInstList()) { 581 const ErrorOr<uint64_t> &R = getInstWeight(I); 582 if (R) { 583 Max = std::max(Max, R.get()); 584 HasWeight = true; 585 } 586 } 587 return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code(); 588 } 589 590 /// Compute and store the weights of every basic block. 591 /// 592 /// This populates the BlockWeights map by computing 593 /// the weights of every basic block in the CFG. 594 /// 595 /// \param F The function to query. 596 bool SampleProfileLoader::computeBlockWeights(Function &F) { 597 bool Changed = false; 598 LLVM_DEBUG(dbgs() << "Block weights\n"); 599 for (const auto &BB : F) { 600 ErrorOr<uint64_t> Weight = getBlockWeight(&BB); 601 if (Weight) { 602 BlockWeights[&BB] = Weight.get(); 603 VisitedBlocks.insert(&BB); 604 Changed = true; 605 } 606 LLVM_DEBUG(printBlockWeight(dbgs(), &BB)); 607 } 608 609 return Changed; 610 } 611 612 /// Get the FunctionSamples for a call instruction. 613 /// 614 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined 615 /// instance in which that call instruction is calling to. It contains 616 /// all samples that resides in the inlined instance. We first find the 617 /// inlined instance in which the call instruction is from, then we 618 /// traverse its children to find the callsite with the matching 619 /// location. 620 /// 621 /// \param Inst Call/Invoke instruction to query. 622 /// 623 /// \returns The FunctionSamples pointer to the inlined instance. 624 const FunctionSamples * 625 SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const { 626 const DILocation *DIL = Inst.getDebugLoc(); 627 if (!DIL) { 628 return nullptr; 629 } 630 631 StringRef CalleeName; 632 if (const CallInst *CI = dyn_cast<CallInst>(&Inst)) 633 if (Function *Callee = CI->getCalledFunction()) 634 CalleeName = Callee->getName(); 635 636 const FunctionSamples *FS = findFunctionSamples(Inst); 637 if (FS == nullptr) 638 return nullptr; 639 640 return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL), 641 DIL->getBaseDiscriminator()), 642 CalleeName); 643 } 644 645 /// Returns a vector of FunctionSamples that are the indirect call targets 646 /// of \p Inst. The vector is sorted by the total number of samples. Stores 647 /// the total call count of the indirect call in \p Sum. 648 std::vector<const FunctionSamples *> 649 SampleProfileLoader::findIndirectCallFunctionSamples( 650 const Instruction &Inst, uint64_t &Sum) const { 651 const DILocation *DIL = Inst.getDebugLoc(); 652 std::vector<const FunctionSamples *> R; 653 654 if (!DIL) { 655 return R; 656 } 657 658 const FunctionSamples *FS = findFunctionSamples(Inst); 659 if (FS == nullptr) 660 return R; 661 662 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 663 uint32_t Discriminator = DIL->getBaseDiscriminator(); 664 665 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator); 666 Sum = 0; 667 if (T) 668 for (const auto &T_C : T.get()) 669 Sum += T_C.second; 670 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation( 671 FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) { 672 if (M->empty()) 673 return R; 674 for (const auto &NameFS : *M) { 675 Sum += NameFS.second.getEntrySamples(); 676 R.push_back(&NameFS.second); 677 } 678 llvm::sort(R.begin(), R.end(), 679 [](const FunctionSamples *L, const FunctionSamples *R) { 680 return L->getEntrySamples() > R->getEntrySamples(); 681 }); 682 } 683 return R; 684 } 685 686 /// Get the FunctionSamples for an instruction. 687 /// 688 /// The FunctionSamples of an instruction \p Inst is the inlined instance 689 /// in which that instruction is coming from. We traverse the inline stack 690 /// of that instruction, and match it with the tree nodes in the profile. 691 /// 692 /// \param Inst Instruction to query. 693 /// 694 /// \returns the FunctionSamples pointer to the inlined instance. 695 const FunctionSamples * 696 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { 697 SmallVector<std::pair<LineLocation, StringRef>, 10> S; 698 const DILocation *DIL = Inst.getDebugLoc(); 699 if (!DIL) 700 return Samples; 701 702 return Samples->findFunctionSamples(DIL); 703 } 704 705 bool SampleProfileLoader::inlineCallInstruction(Instruction *I) { 706 assert(isa<CallInst>(I) || isa<InvokeInst>(I)); 707 CallSite CS(I); 708 Function *CalledFunction = CS.getCalledFunction(); 709 assert(CalledFunction); 710 DebugLoc DLoc = I->getDebugLoc(); 711 BasicBlock *BB = I->getParent(); 712 InlineParams Params = getInlineParams(); 713 Params.ComputeFullInlineCost = true; 714 // Checks if there is anything in the reachable portion of the callee at 715 // this callsite that makes this inlining potentially illegal. Need to 716 // set ComputeFullInlineCost, otherwise getInlineCost may return early 717 // when cost exceeds threshold without checking all IRs in the callee. 718 // The acutal cost does not matter because we only checks isNever() to 719 // see if it is legal to inline the callsite. 720 InlineCost Cost = getInlineCost(CS, Params, GetTTI(*CalledFunction), GetAC, 721 None, nullptr, nullptr); 722 if (Cost.isNever()) { 723 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB) 724 << "incompatible inlining"); 725 return false; 726 } 727 InlineFunctionInfo IFI(nullptr, &GetAC); 728 if (InlineFunction(CS, IFI)) { 729 // The call to InlineFunction erases I, so we can't pass it here. 730 ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB) 731 << "inlined hot callee '" << ore::NV("Callee", CalledFunction) 732 << "' into '" << ore::NV("Caller", BB->getParent()) << "'"); 733 return true; 734 } 735 return false; 736 } 737 738 /// Iteratively inline hot callsites of a function. 739 /// 740 /// Iteratively traverse all callsites of the function \p F, and find if 741 /// the corresponding inlined instance exists and is hot in profile. If 742 /// it is hot enough, inline the callsites and adds new callsites of the 743 /// callee into the caller. If the call is an indirect call, first promote 744 /// it to direct call. Each indirect call is limited with a single target. 745 /// 746 /// \param F function to perform iterative inlining. 747 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are 748 /// inlined in the profiled binary. 749 /// 750 /// \returns True if there is any inline happened. 751 bool SampleProfileLoader::inlineHotFunctions( 752 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 753 DenseSet<Instruction *> PromotedInsns; 754 bool Changed = false; 755 while (true) { 756 bool LocalChanged = false; 757 SmallVector<Instruction *, 10> CIS; 758 for (auto &BB : F) { 759 bool Hot = false; 760 SmallVector<Instruction *, 10> Candidates; 761 for (auto &I : BB.getInstList()) { 762 const FunctionSamples *FS = nullptr; 763 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) && 764 !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) { 765 Candidates.push_back(&I); 766 if (callsiteIsHot(FS, PSI)) 767 Hot = true; 768 } 769 } 770 if (Hot) { 771 CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end()); 772 } 773 } 774 for (auto I : CIS) { 775 Function *CalledFunction = CallSite(I).getCalledFunction(); 776 // Do not inline recursive calls. 777 if (CalledFunction == &F) 778 continue; 779 if (CallSite(I).isIndirectCall()) { 780 if (PromotedInsns.count(I)) 781 continue; 782 uint64_t Sum; 783 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) { 784 if (IsThinLTOPreLink) { 785 FS->findInlinedFunctions(InlinedGUIDs, F.getParent(), 786 PSI->getOrCompHotCountThreshold()); 787 continue; 788 } 789 auto CalleeFunctionName = FS->getName(); 790 // If it is a recursive call, we do not inline it as it could bloat 791 // the code exponentially. There is way to better handle this, e.g. 792 // clone the caller first, and inline the cloned caller if it is 793 // recursive. As llvm does not inline recursive calls, we will 794 // simply ignore it instead of handling it explicitly. 795 if (CalleeFunctionName == F.getName()) 796 continue; 797 798 const char *Reason = "Callee function not available"; 799 auto R = SymbolMap.find(CalleeFunctionName); 800 if (R != SymbolMap.end() && R->getValue() && 801 !R->getValue()->isDeclaration() && 802 R->getValue()->getSubprogram() && 803 isLegalToPromote(CallSite(I), R->getValue(), &Reason)) { 804 uint64_t C = FS->getEntrySamples(); 805 Instruction *DI = 806 pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE); 807 Sum -= C; 808 PromotedInsns.insert(I); 809 // If profile mismatches, we should not attempt to inline DI. 810 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) && 811 inlineCallInstruction(DI)) 812 LocalChanged = true; 813 } else { 814 LLVM_DEBUG(dbgs() 815 << "\nFailed to promote indirect call to " 816 << CalleeFunctionName << " because " << Reason << "\n"); 817 } 818 } 819 } else if (CalledFunction && CalledFunction->getSubprogram() && 820 !CalledFunction->isDeclaration()) { 821 if (inlineCallInstruction(I)) 822 LocalChanged = true; 823 } else if (IsThinLTOPreLink) { 824 findCalleeFunctionSamples(*I)->findInlinedFunctions( 825 InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold()); 826 } 827 } 828 if (LocalChanged) { 829 Changed = true; 830 } else { 831 break; 832 } 833 } 834 return Changed; 835 } 836 837 /// Find equivalence classes for the given block. 838 /// 839 /// This finds all the blocks that are guaranteed to execute the same 840 /// number of times as \p BB1. To do this, it traverses all the 841 /// descendants of \p BB1 in the dominator or post-dominator tree. 842 /// 843 /// A block BB2 will be in the same equivalence class as \p BB1 if 844 /// the following holds: 845 /// 846 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 847 /// is a descendant of \p BB1 in the dominator tree, then BB2 should 848 /// dominate BB1 in the post-dominator tree. 849 /// 850 /// 2- Both BB2 and \p BB1 must be in the same loop. 851 /// 852 /// For every block BB2 that meets those two requirements, we set BB2's 853 /// equivalence class to \p BB1. 854 /// 855 /// \param BB1 Block to check. 856 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. 857 /// \param DomTree Opposite dominator tree. If \p Descendants is filled 858 /// with blocks from \p BB1's dominator tree, then 859 /// this is the post-dominator tree, and vice versa. 860 template <bool IsPostDom> 861 void SampleProfileLoader::findEquivalencesFor( 862 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants, 863 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) { 864 const BasicBlock *EC = EquivalenceClass[BB1]; 865 uint64_t Weight = BlockWeights[EC]; 866 for (const auto *BB2 : Descendants) { 867 bool IsDomParent = DomTree->dominates(BB2, BB1); 868 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); 869 if (BB1 != BB2 && IsDomParent && IsInSameLoop) { 870 EquivalenceClass[BB2] = EC; 871 // If BB2 is visited, then the entire EC should be marked as visited. 872 if (VisitedBlocks.count(BB2)) { 873 VisitedBlocks.insert(EC); 874 } 875 876 // If BB2 is heavier than BB1, make BB2 have the same weight 877 // as BB1. 878 // 879 // Note that we don't worry about the opposite situation here 880 // (when BB2 is lighter than BB1). We will deal with this 881 // during the propagation phase. Right now, we just want to 882 // make sure that BB1 has the largest weight of all the 883 // members of its equivalence set. 884 Weight = std::max(Weight, BlockWeights[BB2]); 885 } 886 } 887 if (EC == &EC->getParent()->getEntryBlock()) { 888 BlockWeights[EC] = Samples->getHeadSamples() + 1; 889 } else { 890 BlockWeights[EC] = Weight; 891 } 892 } 893 894 /// Find equivalence classes. 895 /// 896 /// Since samples may be missing from blocks, we can fill in the gaps by setting 897 /// the weights of all the blocks in the same equivalence class to the same 898 /// weight. To compute the concept of equivalence, we use dominance and loop 899 /// information. Two blocks B1 and B2 are in the same equivalence class if B1 900 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 901 /// 902 /// \param F The function to query. 903 void SampleProfileLoader::findEquivalenceClasses(Function &F) { 904 SmallVector<BasicBlock *, 8> DominatedBBs; 905 LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n"); 906 // Find equivalence sets based on dominance and post-dominance information. 907 for (auto &BB : F) { 908 BasicBlock *BB1 = &BB; 909 910 // Compute BB1's equivalence class once. 911 if (EquivalenceClass.count(BB1)) { 912 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); 913 continue; 914 } 915 916 // By default, blocks are in their own equivalence class. 917 EquivalenceClass[BB1] = BB1; 918 919 // Traverse all the blocks dominated by BB1. We are looking for 920 // every basic block BB2 such that: 921 // 922 // 1- BB1 dominates BB2. 923 // 2- BB2 post-dominates BB1. 924 // 3- BB1 and BB2 are in the same loop nest. 925 // 926 // If all those conditions hold, it means that BB2 is executed 927 // as many times as BB1, so they are placed in the same equivalence 928 // class by making BB2's equivalence class be BB1. 929 DominatedBBs.clear(); 930 DT->getDescendants(BB1, DominatedBBs); 931 findEquivalencesFor(BB1, DominatedBBs, PDT.get()); 932 933 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); 934 } 935 936 // Assign weights to equivalence classes. 937 // 938 // All the basic blocks in the same equivalence class will execute 939 // the same number of times. Since we know that the head block in 940 // each equivalence class has the largest weight, assign that weight 941 // to all the blocks in that equivalence class. 942 LLVM_DEBUG( 943 dbgs() << "\nAssign the same weight to all blocks in the same class\n"); 944 for (auto &BI : F) { 945 const BasicBlock *BB = &BI; 946 const BasicBlock *EquivBB = EquivalenceClass[BB]; 947 if (BB != EquivBB) 948 BlockWeights[BB] = BlockWeights[EquivBB]; 949 LLVM_DEBUG(printBlockWeight(dbgs(), BB)); 950 } 951 } 952 953 /// Visit the given edge to decide if it has a valid weight. 954 /// 955 /// If \p E has not been visited before, we copy to \p UnknownEdge 956 /// and increment the count of unknown edges. 957 /// 958 /// \param E Edge to visit. 959 /// \param NumUnknownEdges Current number of unknown edges. 960 /// \param UnknownEdge Set if E has not been visited before. 961 /// 962 /// \returns E's weight, if known. Otherwise, return 0. 963 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, 964 Edge *UnknownEdge) { 965 if (!VisitedEdges.count(E)) { 966 (*NumUnknownEdges)++; 967 *UnknownEdge = E; 968 return 0; 969 } 970 971 return EdgeWeights[E]; 972 } 973 974 /// Propagate weights through incoming/outgoing edges. 975 /// 976 /// If the weight of a basic block is known, and there is only one edge 977 /// with an unknown weight, we can calculate the weight of that edge. 978 /// 979 /// Similarly, if all the edges have a known count, we can calculate the 980 /// count of the basic block, if needed. 981 /// 982 /// \param F Function to process. 983 /// \param UpdateBlockCount Whether we should update basic block counts that 984 /// has already been annotated. 985 /// 986 /// \returns True if new weights were assigned to edges or blocks. 987 bool SampleProfileLoader::propagateThroughEdges(Function &F, 988 bool UpdateBlockCount) { 989 bool Changed = false; 990 LLVM_DEBUG(dbgs() << "\nPropagation through edges\n"); 991 for (const auto &BI : F) { 992 const BasicBlock *BB = &BI; 993 const BasicBlock *EC = EquivalenceClass[BB]; 994 995 // Visit all the predecessor and successor edges to determine 996 // which ones have a weight assigned already. Note that it doesn't 997 // matter that we only keep track of a single unknown edge. The 998 // only case we are interested in handling is when only a single 999 // edge is unknown (see setEdgeOrBlockWeight). 1000 for (unsigned i = 0; i < 2; i++) { 1001 uint64_t TotalWeight = 0; 1002 unsigned NumUnknownEdges = 0, NumTotalEdges = 0; 1003 Edge UnknownEdge, SelfReferentialEdge, SingleEdge; 1004 1005 if (i == 0) { 1006 // First, visit all predecessor edges. 1007 NumTotalEdges = Predecessors[BB].size(); 1008 for (auto *Pred : Predecessors[BB]) { 1009 Edge E = std::make_pair(Pred, BB); 1010 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 1011 if (E.first == E.second) 1012 SelfReferentialEdge = E; 1013 } 1014 if (NumTotalEdges == 1) { 1015 SingleEdge = std::make_pair(Predecessors[BB][0], BB); 1016 } 1017 } else { 1018 // On the second round, visit all successor edges. 1019 NumTotalEdges = Successors[BB].size(); 1020 for (auto *Succ : Successors[BB]) { 1021 Edge E = std::make_pair(BB, Succ); 1022 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 1023 } 1024 if (NumTotalEdges == 1) { 1025 SingleEdge = std::make_pair(BB, Successors[BB][0]); 1026 } 1027 } 1028 1029 // After visiting all the edges, there are three cases that we 1030 // can handle immediately: 1031 // 1032 // - All the edge weights are known (i.e., NumUnknownEdges == 0). 1033 // In this case, we simply check that the sum of all the edges 1034 // is the same as BB's weight. If not, we change BB's weight 1035 // to match. Additionally, if BB had not been visited before, 1036 // we mark it visited. 1037 // 1038 // - Only one edge is unknown and BB has already been visited. 1039 // In this case, we can compute the weight of the edge by 1040 // subtracting the total block weight from all the known 1041 // edge weights. If the edges weight more than BB, then the 1042 // edge of the last remaining edge is set to zero. 1043 // 1044 // - There exists a self-referential edge and the weight of BB is 1045 // known. In this case, this edge can be based on BB's weight. 1046 // We add up all the other known edges and set the weight on 1047 // the self-referential edge as we did in the previous case. 1048 // 1049 // In any other case, we must continue iterating. Eventually, 1050 // all edges will get a weight, or iteration will stop when 1051 // it reaches SampleProfileMaxPropagateIterations. 1052 if (NumUnknownEdges <= 1) { 1053 uint64_t &BBWeight = BlockWeights[EC]; 1054 if (NumUnknownEdges == 0) { 1055 if (!VisitedBlocks.count(EC)) { 1056 // If we already know the weight of all edges, the weight of the 1057 // basic block can be computed. It should be no larger than the sum 1058 // of all edge weights. 1059 if (TotalWeight > BBWeight) { 1060 BBWeight = TotalWeight; 1061 Changed = true; 1062 LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName() 1063 << " known. Set weight for block: "; 1064 printBlockWeight(dbgs(), BB);); 1065 } 1066 } else if (NumTotalEdges == 1 && 1067 EdgeWeights[SingleEdge] < BlockWeights[EC]) { 1068 // If there is only one edge for the visited basic block, use the 1069 // block weight to adjust edge weight if edge weight is smaller. 1070 EdgeWeights[SingleEdge] = BlockWeights[EC]; 1071 Changed = true; 1072 } 1073 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { 1074 // If there is a single unknown edge and the block has been 1075 // visited, then we can compute E's weight. 1076 if (BBWeight >= TotalWeight) 1077 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; 1078 else 1079 EdgeWeights[UnknownEdge] = 0; 1080 const BasicBlock *OtherEC; 1081 if (i == 0) 1082 OtherEC = EquivalenceClass[UnknownEdge.first]; 1083 else 1084 OtherEC = EquivalenceClass[UnknownEdge.second]; 1085 // Edge weights should never exceed the BB weights it connects. 1086 if (VisitedBlocks.count(OtherEC) && 1087 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC]) 1088 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC]; 1089 VisitedEdges.insert(UnknownEdge); 1090 Changed = true; 1091 LLVM_DEBUG(dbgs() << "Set weight for edge: "; 1092 printEdgeWeight(dbgs(), UnknownEdge)); 1093 } 1094 } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) { 1095 // If a block Weights 0, all its in/out edges should weight 0. 1096 if (i == 0) { 1097 for (auto *Pred : Predecessors[BB]) { 1098 Edge E = std::make_pair(Pred, BB); 1099 EdgeWeights[E] = 0; 1100 VisitedEdges.insert(E); 1101 } 1102 } else { 1103 for (auto *Succ : Successors[BB]) { 1104 Edge E = std::make_pair(BB, Succ); 1105 EdgeWeights[E] = 0; 1106 VisitedEdges.insert(E); 1107 } 1108 } 1109 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { 1110 uint64_t &BBWeight = BlockWeights[BB]; 1111 // We have a self-referential edge and the weight of BB is known. 1112 if (BBWeight >= TotalWeight) 1113 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; 1114 else 1115 EdgeWeights[SelfReferentialEdge] = 0; 1116 VisitedEdges.insert(SelfReferentialEdge); 1117 Changed = true; 1118 LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: "; 1119 printEdgeWeight(dbgs(), SelfReferentialEdge)); 1120 } 1121 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) { 1122 BlockWeights[EC] = TotalWeight; 1123 VisitedBlocks.insert(EC); 1124 Changed = true; 1125 } 1126 } 1127 } 1128 1129 return Changed; 1130 } 1131 1132 /// Build in/out edge lists for each basic block in the CFG. 1133 /// 1134 /// We are interested in unique edges. If a block B1 has multiple 1135 /// edges to another block B2, we only add a single B1->B2 edge. 1136 void SampleProfileLoader::buildEdges(Function &F) { 1137 for (auto &BI : F) { 1138 BasicBlock *B1 = &BI; 1139 1140 // Add predecessors for B1. 1141 SmallPtrSet<BasicBlock *, 16> Visited; 1142 if (!Predecessors[B1].empty()) 1143 llvm_unreachable("Found a stale predecessors list in a basic block."); 1144 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { 1145 BasicBlock *B2 = *PI; 1146 if (Visited.insert(B2).second) 1147 Predecessors[B1].push_back(B2); 1148 } 1149 1150 // Add successors for B1. 1151 Visited.clear(); 1152 if (!Successors[B1].empty()) 1153 llvm_unreachable("Found a stale successors list in a basic block."); 1154 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { 1155 BasicBlock *B2 = *SI; 1156 if (Visited.insert(B2).second) 1157 Successors[B1].push_back(B2); 1158 } 1159 } 1160 } 1161 1162 /// Returns the sorted CallTargetMap \p M by count in descending order. 1163 static SmallVector<InstrProfValueData, 2> SortCallTargets( 1164 const SampleRecord::CallTargetMap &M) { 1165 SmallVector<InstrProfValueData, 2> R; 1166 for (auto I = M.begin(); I != M.end(); ++I) 1167 R.push_back({Function::getGUID(I->getKey()), I->getValue()}); 1168 llvm::sort(R.begin(), R.end(), 1169 [](const InstrProfValueData &L, const InstrProfValueData &R) { 1170 if (L.Count == R.Count) 1171 return L.Value > R.Value; 1172 else 1173 return L.Count > R.Count; 1174 }); 1175 return R; 1176 } 1177 1178 /// Propagate weights into edges 1179 /// 1180 /// The following rules are applied to every block BB in the CFG: 1181 /// 1182 /// - If BB has a single predecessor/successor, then the weight 1183 /// of that edge is the weight of the block. 1184 /// 1185 /// - If all incoming or outgoing edges are known except one, and the 1186 /// weight of the block is already known, the weight of the unknown 1187 /// edge will be the weight of the block minus the sum of all the known 1188 /// edges. If the sum of all the known edges is larger than BB's weight, 1189 /// we set the unknown edge weight to zero. 1190 /// 1191 /// - If there is a self-referential edge, and the weight of the block is 1192 /// known, the weight for that edge is set to the weight of the block 1193 /// minus the weight of the other incoming edges to that block (if 1194 /// known). 1195 void SampleProfileLoader::propagateWeights(Function &F) { 1196 bool Changed = true; 1197 unsigned I = 0; 1198 1199 // If BB weight is larger than its corresponding loop's header BB weight, 1200 // use the BB weight to replace the loop header BB weight. 1201 for (auto &BI : F) { 1202 BasicBlock *BB = &BI; 1203 Loop *L = LI->getLoopFor(BB); 1204 if (!L) { 1205 continue; 1206 } 1207 BasicBlock *Header = L->getHeader(); 1208 if (Header && BlockWeights[BB] > BlockWeights[Header]) { 1209 BlockWeights[Header] = BlockWeights[BB]; 1210 } 1211 } 1212 1213 // Before propagation starts, build, for each block, a list of 1214 // unique predecessors and successors. This is necessary to handle 1215 // identical edges in multiway branches. Since we visit all blocks and all 1216 // edges of the CFG, it is cleaner to build these lists once at the start 1217 // of the pass. 1218 buildEdges(F); 1219 1220 // Propagate until we converge or we go past the iteration limit. 1221 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1222 Changed = propagateThroughEdges(F, false); 1223 } 1224 1225 // The first propagation propagates BB counts from annotated BBs to unknown 1226 // BBs. The 2nd propagation pass resets edges weights, and use all BB weights 1227 // to propagate edge weights. 1228 VisitedEdges.clear(); 1229 Changed = true; 1230 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1231 Changed = propagateThroughEdges(F, false); 1232 } 1233 1234 // The 3rd propagation pass allows adjust annotated BB weights that are 1235 // obviously wrong. 1236 Changed = true; 1237 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1238 Changed = propagateThroughEdges(F, true); 1239 } 1240 1241 // Generate MD_prof metadata for every branch instruction using the 1242 // edge weights computed during propagation. 1243 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 1244 LLVMContext &Ctx = F.getContext(); 1245 MDBuilder MDB(Ctx); 1246 for (auto &BI : F) { 1247 BasicBlock *BB = &BI; 1248 1249 if (BlockWeights[BB]) { 1250 for (auto &I : BB->getInstList()) { 1251 if (!isa<CallInst>(I) && !isa<InvokeInst>(I)) 1252 continue; 1253 CallSite CS(&I); 1254 if (!CS.getCalledFunction()) { 1255 const DebugLoc &DLoc = I.getDebugLoc(); 1256 if (!DLoc) 1257 continue; 1258 const DILocation *DIL = DLoc; 1259 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 1260 uint32_t Discriminator = DIL->getBaseDiscriminator(); 1261 1262 const FunctionSamples *FS = findFunctionSamples(I); 1263 if (!FS) 1264 continue; 1265 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator); 1266 if (!T || T.get().empty()) 1267 continue; 1268 SmallVector<InstrProfValueData, 2> SortedCallTargets = 1269 SortCallTargets(T.get()); 1270 uint64_t Sum; 1271 findIndirectCallFunctionSamples(I, Sum); 1272 annotateValueSite(*I.getParent()->getParent()->getParent(), I, 1273 SortedCallTargets, Sum, IPVK_IndirectCallTarget, 1274 SortedCallTargets.size()); 1275 } else if (!dyn_cast<IntrinsicInst>(&I)) { 1276 SmallVector<uint32_t, 1> Weights; 1277 Weights.push_back(BlockWeights[BB]); 1278 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1279 } 1280 } 1281 } 1282 TerminatorInst *TI = BB->getTerminator(); 1283 if (TI->getNumSuccessors() == 1) 1284 continue; 1285 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 1286 continue; 1287 1288 DebugLoc BranchLoc = TI->getDebugLoc(); 1289 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line " 1290 << ((BranchLoc) ? Twine(BranchLoc.getLine()) 1291 : Twine("<UNKNOWN LOCATION>")) 1292 << ".\n"); 1293 SmallVector<uint32_t, 4> Weights; 1294 uint32_t MaxWeight = 0; 1295 Instruction *MaxDestInst; 1296 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 1297 BasicBlock *Succ = TI->getSuccessor(I); 1298 Edge E = std::make_pair(BB, Succ); 1299 uint64_t Weight = EdgeWeights[E]; 1300 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 1301 // Use uint32_t saturated arithmetic to adjust the incoming weights, 1302 // if needed. Sample counts in profiles are 64-bit unsigned values, 1303 // but internally branch weights are expressed as 32-bit values. 1304 if (Weight > std::numeric_limits<uint32_t>::max()) { 1305 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)"); 1306 Weight = std::numeric_limits<uint32_t>::max(); 1307 } 1308 // Weight is added by one to avoid propagation errors introduced by 1309 // 0 weights. 1310 Weights.push_back(static_cast<uint32_t>(Weight + 1)); 1311 if (Weight != 0) { 1312 if (Weight > MaxWeight) { 1313 MaxWeight = Weight; 1314 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime(); 1315 } 1316 } 1317 } 1318 1319 uint64_t TempWeight; 1320 // Only set weights if there is at least one non-zero weight. 1321 // In any other case, let the analyzer set weights. 1322 // Do not set weights if the weights are present. In ThinLTO, the profile 1323 // annotation is done twice. If the first annotation already set the 1324 // weights, the second pass does not need to set it. 1325 if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) { 1326 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 1327 TI->setMetadata(LLVMContext::MD_prof, 1328 MDB.createBranchWeights(Weights)); 1329 ORE->emit([&]() { 1330 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst) 1331 << "most popular destination for conditional branches at " 1332 << ore::NV("CondBranchesLoc", BranchLoc); 1333 }); 1334 } else { 1335 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 1336 } 1337 } 1338 } 1339 1340 /// Get the line number for the function header. 1341 /// 1342 /// This looks up function \p F in the current compilation unit and 1343 /// retrieves the line number where the function is defined. This is 1344 /// line 0 for all the samples read from the profile file. Every line 1345 /// number is relative to this line. 1346 /// 1347 /// \param F Function object to query. 1348 /// 1349 /// \returns the line number where \p F is defined. If it returns 0, 1350 /// it means that there is no debug information available for \p F. 1351 unsigned SampleProfileLoader::getFunctionLoc(Function &F) { 1352 if (DISubprogram *S = F.getSubprogram()) 1353 return S->getLine(); 1354 1355 // If the start of \p F is missing, emit a diagnostic to inform the user 1356 // about the missed opportunity. 1357 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1358 "No debug information found in function " + F.getName() + 1359 ": Function profile not used", 1360 DS_Warning)); 1361 return 0; 1362 } 1363 1364 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { 1365 DT.reset(new DominatorTree); 1366 DT->recalculate(F); 1367 1368 PDT.reset(new PostDomTreeBase<BasicBlock>()); 1369 PDT->recalculate(F); 1370 1371 LI.reset(new LoopInfo); 1372 LI->analyze(*DT); 1373 } 1374 1375 /// Generate branch weight metadata for all branches in \p F. 1376 /// 1377 /// Branch weights are computed out of instruction samples using a 1378 /// propagation heuristic. Propagation proceeds in 3 phases: 1379 /// 1380 /// 1- Assignment of block weights. All the basic blocks in the function 1381 /// are initial assigned the same weight as their most frequently 1382 /// executed instruction. 1383 /// 1384 /// 2- Creation of equivalence classes. Since samples may be missing from 1385 /// blocks, we can fill in the gaps by setting the weights of all the 1386 /// blocks in the same equivalence class to the same weight. To compute 1387 /// the concept of equivalence, we use dominance and loop information. 1388 /// Two blocks B1 and B2 are in the same equivalence class if B1 1389 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 1390 /// 1391 /// 3- Propagation of block weights into edges. This uses a simple 1392 /// propagation heuristic. The following rules are applied to every 1393 /// block BB in the CFG: 1394 /// 1395 /// - If BB has a single predecessor/successor, then the weight 1396 /// of that edge is the weight of the block. 1397 /// 1398 /// - If all the edges are known except one, and the weight of the 1399 /// block is already known, the weight of the unknown edge will 1400 /// be the weight of the block minus the sum of all the known 1401 /// edges. If the sum of all the known edges is larger than BB's weight, 1402 /// we set the unknown edge weight to zero. 1403 /// 1404 /// - If there is a self-referential edge, and the weight of the block is 1405 /// known, the weight for that edge is set to the weight of the block 1406 /// minus the weight of the other incoming edges to that block (if 1407 /// known). 1408 /// 1409 /// Since this propagation is not guaranteed to finalize for every CFG, we 1410 /// only allow it to proceed for a limited number of iterations (controlled 1411 /// by -sample-profile-max-propagate-iterations). 1412 /// 1413 /// FIXME: Try to replace this propagation heuristic with a scheme 1414 /// that is guaranteed to finalize. A work-list approach similar to 1415 /// the standard value propagation algorithm used by SSA-CCP might 1416 /// work here. 1417 /// 1418 /// Once all the branch weights are computed, we emit the MD_prof 1419 /// metadata on BB using the computed values for each of its branches. 1420 /// 1421 /// \param F The function to query. 1422 /// 1423 /// \returns true if \p F was modified. Returns false, otherwise. 1424 bool SampleProfileLoader::emitAnnotations(Function &F) { 1425 bool Changed = false; 1426 1427 if (getFunctionLoc(F) == 0) 1428 return false; 1429 1430 LLVM_DEBUG(dbgs() << "Line number for the first instruction in " 1431 << F.getName() << ": " << getFunctionLoc(F) << "\n"); 1432 1433 DenseSet<GlobalValue::GUID> InlinedGUIDs; 1434 Changed |= inlineHotFunctions(F, InlinedGUIDs); 1435 1436 // Compute basic block weights. 1437 Changed |= computeBlockWeights(F); 1438 1439 if (Changed) { 1440 // Add an entry count to the function using the samples gathered at the 1441 // function entry. 1442 // Sets the GUIDs that are inlined in the profiled binary. This is used 1443 // for ThinLink to make correct liveness analysis, and also make the IR 1444 // match the profiled binary before annotation. 1445 F.setEntryCount( 1446 ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real), 1447 &InlinedGUIDs); 1448 1449 // Compute dominance and loop info needed for propagation. 1450 computeDominanceAndLoopInfo(F); 1451 1452 // Find equivalence classes. 1453 findEquivalenceClasses(F); 1454 1455 // Propagate weights to all edges. 1456 propagateWeights(F); 1457 } 1458 1459 // If coverage checking was requested, compute it now. 1460 if (SampleProfileRecordCoverage) { 1461 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI); 1462 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI); 1463 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); 1464 if (Coverage < SampleProfileRecordCoverage) { 1465 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1466 F.getSubprogram()->getFilename(), getFunctionLoc(F), 1467 Twine(Used) + " of " + Twine(Total) + " available profile records (" + 1468 Twine(Coverage) + "%) were applied", 1469 DS_Warning)); 1470 } 1471 } 1472 1473 if (SampleProfileSampleCoverage) { 1474 uint64_t Used = CoverageTracker.getTotalUsedSamples(); 1475 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI); 1476 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); 1477 if (Coverage < SampleProfileSampleCoverage) { 1478 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1479 F.getSubprogram()->getFilename(), getFunctionLoc(F), 1480 Twine(Used) + " of " + Twine(Total) + " available profile samples (" + 1481 Twine(Coverage) + "%) were applied", 1482 DS_Warning)); 1483 } 1484 } 1485 return Changed; 1486 } 1487 1488 char SampleProfileLoaderLegacyPass::ID = 0; 1489 1490 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", 1491 "Sample Profile loader", false, false) 1492 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1493 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1494 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1495 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", 1496 "Sample Profile loader", false, false) 1497 1498 bool SampleProfileLoader::doInitialization(Module &M) { 1499 auto &Ctx = M.getContext(); 1500 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx); 1501 if (std::error_code EC = ReaderOrErr.getError()) { 1502 std::string Msg = "Could not open profile: " + EC.message(); 1503 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1504 return false; 1505 } 1506 Reader = std::move(ReaderOrErr.get()); 1507 ProfileIsValid = (Reader->read() == sampleprof_error::success); 1508 return true; 1509 } 1510 1511 ModulePass *llvm::createSampleProfileLoaderPass() { 1512 return new SampleProfileLoaderLegacyPass(SampleProfileFile); 1513 } 1514 1515 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 1516 return new SampleProfileLoaderLegacyPass(Name); 1517 } 1518 1519 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM, 1520 ProfileSummaryInfo *_PSI) { 1521 if (!ProfileIsValid) 1522 return false; 1523 1524 PSI = _PSI; 1525 if (M.getProfileSummary() == nullptr) 1526 M.setProfileSummary(Reader->getSummary().getMD(M.getContext())); 1527 1528 // Compute the total number of samples collected in this profile. 1529 for (const auto &I : Reader->getProfiles()) 1530 TotalCollectedSamples += I.second.getTotalSamples(); 1531 1532 // Populate the symbol map. 1533 for (const auto &N_F : M.getValueSymbolTable()) { 1534 StringRef OrigName = N_F.getKey(); 1535 Function *F = dyn_cast<Function>(N_F.getValue()); 1536 if (F == nullptr) 1537 continue; 1538 SymbolMap[OrigName] = F; 1539 auto pos = OrigName.find('.'); 1540 if (pos != StringRef::npos) { 1541 StringRef NewName = OrigName.substr(0, pos); 1542 auto r = SymbolMap.insert(std::make_pair(NewName, F)); 1543 // Failiing to insert means there is already an entry in SymbolMap, 1544 // thus there are multiple functions that are mapped to the same 1545 // stripped name. In this case of name conflicting, set the value 1546 // to nullptr to avoid confusion. 1547 if (!r.second) 1548 r.first->second = nullptr; 1549 } 1550 } 1551 1552 bool retval = false; 1553 for (auto &F : M) 1554 if (!F.isDeclaration()) { 1555 clearFunctionData(); 1556 retval |= runOnFunction(F, AM); 1557 } 1558 return retval; 1559 } 1560 1561 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { 1562 ACT = &getAnalysis<AssumptionCacheTracker>(); 1563 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>(); 1564 ProfileSummaryInfo *PSI = 1565 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1566 return SampleLoader.runOnModule(M, nullptr, PSI); 1567 } 1568 1569 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) { 1570 // Initialize the entry count to -1, which will be treated conservatively 1571 // by getEntryCount as the same as unknown (None). If we have samples this 1572 // will be overwritten in emitAnnotations. 1573 F.setEntryCount(ProfileCount(-1, Function::PCT_Real)); 1574 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE; 1575 if (AM) { 1576 auto &FAM = 1577 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent()) 1578 .getManager(); 1579 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1580 } else { 1581 OwnedORE = make_unique<OptimizationRemarkEmitter>(&F); 1582 ORE = OwnedORE.get(); 1583 } 1584 Samples = Reader->getSamplesFor(F); 1585 if (Samples && !Samples->empty()) 1586 return emitAnnotations(F); 1587 return false; 1588 } 1589 1590 PreservedAnalyses SampleProfileLoaderPass::run(Module &M, 1591 ModuleAnalysisManager &AM) { 1592 FunctionAnalysisManager &FAM = 1593 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1594 1595 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 1596 return FAM.getResult<AssumptionAnalysis>(F); 1597 }; 1598 auto GetTTI = [&](Function &F) -> TargetTransformInfo & { 1599 return FAM.getResult<TargetIRAnalysis>(F); 1600 }; 1601 1602 SampleProfileLoader SampleLoader( 1603 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName, 1604 IsThinLTOPreLink, GetAssumptionCache, GetTTI); 1605 1606 SampleLoader.doInitialization(M); 1607 1608 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 1609 if (!SampleLoader.runOnModule(M, &AM, PSI)) 1610 return PreservedAnalyses::all(); 1611 1612 return PreservedAnalyses::none(); 1613 } 1614