1 //===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the SampleProfileProber transformation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 14 #include "llvm/ADT/Statistic.h" 15 #include "llvm/Analysis/BlockFrequencyInfo.h" 16 #include "llvm/Analysis/EHUtils.h" 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/IR/BasicBlock.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DebugInfoMetadata.h" 21 #include "llvm/IR/IRBuilder.h" 22 #include "llvm/IR/Instruction.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/IR/MDBuilder.h" 25 #include "llvm/IR/PseudoProbe.h" 26 #include "llvm/ProfileData/SampleProf.h" 27 #include "llvm/Support/CRC.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Target/TargetMachine.h" 30 #include "llvm/Transforms/Instrumentation.h" 31 #include "llvm/Transforms/Utils/ModuleUtils.h" 32 #include <unordered_set> 33 #include <vector> 34 35 using namespace llvm; 36 #define DEBUG_TYPE "pseudo-probe" 37 38 STATISTIC(ArtificialDbgLine, 39 "Number of probes that have an artificial debug line"); 40 41 static cl::opt<bool> 42 VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden, 43 cl::desc("Do pseudo probe verification")); 44 45 static cl::list<std::string> VerifyPseudoProbeFuncList( 46 "verify-pseudo-probe-funcs", cl::Hidden, 47 cl::desc("The option to specify the name of the functions to verify.")); 48 49 static cl::opt<bool> 50 UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden, 51 cl::desc("Update pseudo probe distribution factor")); 52 53 static uint64_t getCallStackHash(const DILocation *DIL) { 54 uint64_t Hash = 0; 55 const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr; 56 while (InlinedAt) { 57 Hash ^= MD5Hash(std::to_string(InlinedAt->getLine())); 58 Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn())); 59 auto Name = InlinedAt->getSubprogramLinkageName(); 60 Hash ^= MD5Hash(Name); 61 InlinedAt = InlinedAt->getInlinedAt(); 62 } 63 return Hash; 64 } 65 66 static uint64_t computeCallStackHash(const Instruction &Inst) { 67 return getCallStackHash(Inst.getDebugLoc()); 68 } 69 70 bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) { 71 // Skip function declaration. 72 if (F->isDeclaration()) 73 return false; 74 // Skip function that will not be emitted into object file. The prevailing 75 // defintion will be verified instead. 76 if (F->hasAvailableExternallyLinkage()) 77 return false; 78 // Do a name matching. 79 static std::unordered_set<std::string> VerifyFuncNames( 80 VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end()); 81 return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str()); 82 } 83 84 void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) { 85 if (VerifyPseudoProbe) { 86 PIC.registerAfterPassCallback( 87 [this](StringRef P, Any IR, const PreservedAnalyses &) { 88 this->runAfterPass(P, IR); 89 }); 90 } 91 } 92 93 // Callback to run after each transformation for the new pass manager. 94 void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) { 95 std::string Banner = 96 "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n"; 97 dbgs() << Banner; 98 if (const auto **M = any_cast<const Module *>(&IR)) 99 runAfterPass(*M); 100 else if (const auto **F = any_cast<const Function *>(&IR)) 101 runAfterPass(*F); 102 else if (const auto **C = any_cast<const LazyCallGraph::SCC *>(&IR)) 103 runAfterPass(*C); 104 else if (const auto **L = any_cast<const Loop *>(&IR)) 105 runAfterPass(*L); 106 else 107 llvm_unreachable("Unknown IR unit"); 108 } 109 110 void PseudoProbeVerifier::runAfterPass(const Module *M) { 111 for (const Function &F : *M) 112 runAfterPass(&F); 113 } 114 115 void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) { 116 for (const LazyCallGraph::Node &N : *C) 117 runAfterPass(&N.getFunction()); 118 } 119 120 void PseudoProbeVerifier::runAfterPass(const Function *F) { 121 if (!shouldVerifyFunction(F)) 122 return; 123 ProbeFactorMap ProbeFactors; 124 for (const auto &BB : *F) 125 collectProbeFactors(&BB, ProbeFactors); 126 verifyProbeFactors(F, ProbeFactors); 127 } 128 129 void PseudoProbeVerifier::runAfterPass(const Loop *L) { 130 const Function *F = L->getHeader()->getParent(); 131 runAfterPass(F); 132 } 133 134 void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block, 135 ProbeFactorMap &ProbeFactors) { 136 for (const auto &I : *Block) { 137 if (std::optional<PseudoProbe> Probe = extractProbe(I)) { 138 uint64_t Hash = computeCallStackHash(I); 139 ProbeFactors[{Probe->Id, Hash}] += Probe->Factor; 140 } 141 } 142 } 143 144 void PseudoProbeVerifier::verifyProbeFactors( 145 const Function *F, const ProbeFactorMap &ProbeFactors) { 146 bool BannerPrinted = false; 147 auto &PrevProbeFactors = FunctionProbeFactors[F->getName()]; 148 for (const auto &I : ProbeFactors) { 149 float CurProbeFactor = I.second; 150 if (PrevProbeFactors.count(I.first)) { 151 float PrevProbeFactor = PrevProbeFactors[I.first]; 152 if (std::abs(CurProbeFactor - PrevProbeFactor) > 153 DistributionFactorVariance) { 154 if (!BannerPrinted) { 155 dbgs() << "Function " << F->getName() << ":\n"; 156 BannerPrinted = true; 157 } 158 dbgs() << "Probe " << I.first.first << "\tprevious factor " 159 << format("%0.2f", PrevProbeFactor) << "\tcurrent factor " 160 << format("%0.2f", CurProbeFactor) << "\n"; 161 } 162 } 163 164 // Update 165 PrevProbeFactors[I.first] = I.second; 166 } 167 } 168 169 SampleProfileProber::SampleProfileProber(Function &Func, 170 const std::string &CurModuleUniqueId) 171 : F(&Func), CurModuleUniqueId(CurModuleUniqueId) { 172 BlockProbeIds.clear(); 173 CallProbeIds.clear(); 174 LastProbeId = (uint32_t)PseudoProbeReservedId::Last; 175 computeProbeIdForBlocks(); 176 computeProbeIdForCallsites(); 177 computeCFGHash(); 178 } 179 180 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index 181 // value of each BB in the CFG. The higher 32 bits record the number of edges 182 // preceded by the number of indirect calls. 183 // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash(). 184 void SampleProfileProber::computeCFGHash() { 185 std::vector<uint8_t> Indexes; 186 JamCRC JC; 187 for (auto &BB : *F) { 188 auto *TI = BB.getTerminator(); 189 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { 190 auto *Succ = TI->getSuccessor(I); 191 auto Index = getBlockId(Succ); 192 for (int J = 0; J < 4; J++) 193 Indexes.push_back((uint8_t)(Index >> (J * 8))); 194 } 195 } 196 197 JC.update(Indexes); 198 199 FunctionHash = (uint64_t)CallProbeIds.size() << 48 | 200 (uint64_t)Indexes.size() << 32 | JC.getCRC(); 201 // Reserve bit 60-63 for other information purpose. 202 FunctionHash &= 0x0FFFFFFFFFFFFFFF; 203 assert(FunctionHash && "Function checksum should not be zero"); 204 LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName() 205 << ":\n" 206 << " CRC = " << JC.getCRC() << ", Edges = " 207 << Indexes.size() << ", ICSites = " << CallProbeIds.size() 208 << ", Hash = " << FunctionHash << "\n"); 209 } 210 211 void SampleProfileProber::computeProbeIdForBlocks() { 212 DenseSet<BasicBlock *> KnownColdBlocks; 213 computeEHOnlyBlocks(*F, KnownColdBlocks); 214 // Insert pseudo probe to non-cold blocks only. This will reduce IR size as 215 // well as the binary size while retaining the profile quality. 216 for (auto &BB : *F) { 217 ++LastProbeId; 218 if (!KnownColdBlocks.contains(&BB)) 219 BlockProbeIds[&BB] = LastProbeId; 220 } 221 } 222 223 void SampleProfileProber::computeProbeIdForCallsites() { 224 for (auto &BB : *F) { 225 for (auto &I : BB) { 226 if (!isa<CallBase>(I)) 227 continue; 228 if (isa<IntrinsicInst>(&I)) 229 continue; 230 CallProbeIds[&I] = ++LastProbeId; 231 } 232 } 233 } 234 235 uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const { 236 auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB)); 237 return I == BlockProbeIds.end() ? 0 : I->second; 238 } 239 240 uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const { 241 auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call)); 242 return Iter == CallProbeIds.end() ? 0 : Iter->second; 243 } 244 245 void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) { 246 Module *M = F.getParent(); 247 MDBuilder MDB(F.getContext()); 248 // Since the GUID from probe desc and inline stack are computed seperately, we 249 // need to make sure their names are consistent, so here also use the name 250 // from debug info. 251 StringRef FName = F.getName(); 252 if (auto *SP = F.getSubprogram()) { 253 FName = SP->getLinkageName(); 254 if (FName.empty()) 255 FName = SP->getName(); 256 } 257 uint64_t Guid = Function::getGUID(FName); 258 259 // Assign an artificial debug line to a probe that doesn't come with a real 260 // line. A probe not having a debug line will get an incomplete inline 261 // context. This will cause samples collected on the probe to be counted 262 // into the base profile instead of a context profile. The line number 263 // itself is not important though. 264 auto AssignDebugLoc = [&](Instruction *I) { 265 assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) && 266 "Expecting pseudo probe or call instructions"); 267 if (!I->getDebugLoc()) { 268 if (auto *SP = F.getSubprogram()) { 269 auto DIL = DILocation::get(SP->getContext(), 0, 0, SP); 270 I->setDebugLoc(DIL); 271 ArtificialDbgLine++; 272 LLVM_DEBUG({ 273 dbgs() << "\nIn Function " << F.getName() 274 << " Probe gets an artificial debug line\n"; 275 I->dump(); 276 }); 277 } 278 } 279 }; 280 281 // Probe basic blocks. 282 for (auto &I : BlockProbeIds) { 283 BasicBlock *BB = I.first; 284 uint32_t Index = I.second; 285 // Insert a probe before an instruction with a valid debug line number which 286 // will be assigned to the probe. The line number will be used later to 287 // model the inline context when the probe is inlined into other functions. 288 // Debug instructions, phi nodes and lifetime markers do not have an valid 289 // line number. Real instructions generated by optimizations may not come 290 // with a line number either. 291 auto HasValidDbgLine = [](Instruction *J) { 292 return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) && 293 !J->isLifetimeStartOrEnd() && J->getDebugLoc(); 294 }; 295 296 Instruction *J = &*BB->getFirstInsertionPt(); 297 while (J != BB->getTerminator() && !HasValidDbgLine(J)) { 298 J = J->getNextNode(); 299 } 300 301 IRBuilder<> Builder(J); 302 assert(Builder.GetInsertPoint() != BB->end() && 303 "Cannot get the probing point"); 304 Function *ProbeFn = 305 llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe); 306 Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index), 307 Builder.getInt32(0), 308 Builder.getInt64(PseudoProbeFullDistributionFactor)}; 309 auto *Probe = Builder.CreateCall(ProbeFn, Args); 310 AssignDebugLoc(Probe); 311 // Reset the dwarf discriminator if the debug location comes with any. The 312 // discriminator field may be used by FS-AFDO later in the pipeline. 313 if (auto DIL = Probe->getDebugLoc()) { 314 if (DIL->getDiscriminator()) { 315 DIL = DIL->cloneWithDiscriminator(0); 316 Probe->setDebugLoc(DIL); 317 } 318 } 319 } 320 321 // Probe both direct calls and indirect calls. Direct calls are probed so that 322 // their probe ID can be used as an call site identifier to represent a 323 // calling context. 324 for (auto &I : CallProbeIds) { 325 auto *Call = I.first; 326 uint32_t Index = I.second; 327 uint32_t Type = cast<CallBase>(Call)->getCalledFunction() 328 ? (uint32_t)PseudoProbeType::DirectCall 329 : (uint32_t)PseudoProbeType::IndirectCall; 330 AssignDebugLoc(Call); 331 if (auto DIL = Call->getDebugLoc()) { 332 // Levarge the 32-bit discriminator field of debug data to store the ID 333 // and type of a callsite probe. This gets rid of the dependency on 334 // plumbing a customized metadata through the codegen pipeline. 335 uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData( 336 Index, Type, 0, 337 PseudoProbeDwarfDiscriminator::FullDistributionFactor); 338 DIL = DIL->cloneWithDiscriminator(V); 339 Call->setDebugLoc(DIL); 340 } 341 } 342 343 // Create module-level metadata that contains function info necessary to 344 // synthesize probe-based sample counts, which are 345 // - FunctionGUID 346 // - FunctionHash. 347 // - FunctionName 348 auto Hash = getFunctionHash(); 349 auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, FName); 350 auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName); 351 assert(NMD && "llvm.pseudo_probe_desc should be pre-created"); 352 NMD->addOperand(MD); 353 } 354 355 PreservedAnalyses SampleProfileProbePass::run(Module &M, 356 ModuleAnalysisManager &AM) { 357 auto ModuleId = getUniqueModuleId(&M); 358 // Create the pseudo probe desc metadata beforehand. 359 // Note that modules with only data but no functions will require this to 360 // be set up so that they will be known as probed later. 361 M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName); 362 363 for (auto &F : M) { 364 if (F.isDeclaration()) 365 continue; 366 SampleProfileProber ProbeManager(F, ModuleId); 367 ProbeManager.instrumentOneFunc(F, TM); 368 } 369 370 return PreservedAnalyses::none(); 371 } 372 373 void PseudoProbeUpdatePass::runOnFunction(Function &F, 374 FunctionAnalysisManager &FAM) { 375 BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F); 376 auto BBProfileCount = [&BFI](BasicBlock *BB) { 377 return BFI.getBlockProfileCount(BB).value_or(0); 378 }; 379 380 // Collect the sum of execution weight for each probe. 381 ProbeFactorMap ProbeFactors; 382 for (auto &Block : F) { 383 for (auto &I : Block) { 384 if (std::optional<PseudoProbe> Probe = extractProbe(I)) { 385 uint64_t Hash = computeCallStackHash(I); 386 ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block); 387 } 388 } 389 } 390 391 // Fix up over-counted probes. 392 for (auto &Block : F) { 393 for (auto &I : Block) { 394 if (std::optional<PseudoProbe> Probe = extractProbe(I)) { 395 uint64_t Hash = computeCallStackHash(I); 396 float Sum = ProbeFactors[{Probe->Id, Hash}]; 397 if (Sum != 0) 398 setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum); 399 } 400 } 401 } 402 } 403 404 PreservedAnalyses PseudoProbeUpdatePass::run(Module &M, 405 ModuleAnalysisManager &AM) { 406 if (UpdatePseudoProbe) { 407 for (auto &F : M) { 408 if (F.isDeclaration()) 409 continue; 410 FunctionAnalysisManager &FAM = 411 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 412 runOnFunction(F, FAM); 413 } 414 } 415 return PreservedAnalyses::none(); 416 } 417