Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
35266 views
//===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the SampleProfileProber transformation.9//10//===----------------------------------------------------------------------===//1112#include "llvm/Transforms/IPO/SampleProfileProbe.h"13#include "llvm/ADT/Statistic.h"14#include "llvm/Analysis/BlockFrequencyInfo.h"15#include "llvm/Analysis/EHUtils.h"16#include "llvm/Analysis/LoopInfo.h"17#include "llvm/IR/BasicBlock.h"18#include "llvm/IR/Constants.h"19#include "llvm/IR/DebugInfoMetadata.h"20#include "llvm/IR/DiagnosticInfo.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/Module.h"26#include "llvm/IR/PseudoProbe.h"27#include "llvm/ProfileData/SampleProf.h"28#include "llvm/Support/CRC.h"29#include "llvm/Support/CommandLine.h"30#include "llvm/Target/TargetMachine.h"31#include "llvm/Transforms/Instrumentation.h"32#include "llvm/Transforms/Utils/ModuleUtils.h"33#include <unordered_set>34#include <vector>3536using namespace llvm;37#define DEBUG_TYPE "pseudo-probe"3839STATISTIC(ArtificialDbgLine,40"Number of probes that have an artificial debug line");4142static cl::opt<bool>43VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden,44cl::desc("Do pseudo probe verification"));4546static cl::list<std::string> VerifyPseudoProbeFuncList(47"verify-pseudo-probe-funcs", cl::Hidden,48cl::desc("The option to specify the name of the functions to verify."));4950static cl::opt<bool>51UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden,52cl::desc("Update pseudo probe distribution factor"));5354static uint64_t getCallStackHash(const DILocation *DIL) {55uint64_t Hash = 0;56const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;57while (InlinedAt) {58Hash ^= MD5Hash(std::to_string(InlinedAt->getLine()));59Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn()));60auto Name = InlinedAt->getSubprogramLinkageName();61Hash ^= MD5Hash(Name);62InlinedAt = InlinedAt->getInlinedAt();63}64return Hash;65}6667static uint64_t computeCallStackHash(const Instruction &Inst) {68return getCallStackHash(Inst.getDebugLoc());69}7071bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {72// Skip function declaration.73if (F->isDeclaration())74return false;75// Skip function that will not be emitted into object file. The prevailing76// defintion will be verified instead.77if (F->hasAvailableExternallyLinkage())78return false;79// Do a name matching.80static std::unordered_set<std::string> VerifyFuncNames(81VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());82return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str());83}8485void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {86if (VerifyPseudoProbe) {87PIC.registerAfterPassCallback(88[this](StringRef P, Any IR, const PreservedAnalyses &) {89this->runAfterPass(P, IR);90});91}92}9394// Callback to run after each transformation for the new pass manager.95void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {96std::string Banner =97"\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";98dbgs() << Banner;99if (const auto **M = llvm::any_cast<const Module *>(&IR))100runAfterPass(*M);101else if (const auto **F = llvm::any_cast<const Function *>(&IR))102runAfterPass(*F);103else if (const auto **C = llvm::any_cast<const LazyCallGraph::SCC *>(&IR))104runAfterPass(*C);105else if (const auto **L = llvm::any_cast<const Loop *>(&IR))106runAfterPass(*L);107else108llvm_unreachable("Unknown IR unit");109}110111void PseudoProbeVerifier::runAfterPass(const Module *M) {112for (const Function &F : *M)113runAfterPass(&F);114}115116void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {117for (const LazyCallGraph::Node &N : *C)118runAfterPass(&N.getFunction());119}120121void PseudoProbeVerifier::runAfterPass(const Function *F) {122if (!shouldVerifyFunction(F))123return;124ProbeFactorMap ProbeFactors;125for (const auto &BB : *F)126collectProbeFactors(&BB, ProbeFactors);127verifyProbeFactors(F, ProbeFactors);128}129130void PseudoProbeVerifier::runAfterPass(const Loop *L) {131const Function *F = L->getHeader()->getParent();132runAfterPass(F);133}134135void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,136ProbeFactorMap &ProbeFactors) {137for (const auto &I : *Block) {138if (std::optional<PseudoProbe> Probe = extractProbe(I)) {139uint64_t Hash = computeCallStackHash(I);140ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;141}142}143}144145void PseudoProbeVerifier::verifyProbeFactors(146const Function *F, const ProbeFactorMap &ProbeFactors) {147bool BannerPrinted = false;148auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];149for (const auto &I : ProbeFactors) {150float CurProbeFactor = I.second;151if (PrevProbeFactors.count(I.first)) {152float PrevProbeFactor = PrevProbeFactors[I.first];153if (std::abs(CurProbeFactor - PrevProbeFactor) >154DistributionFactorVariance) {155if (!BannerPrinted) {156dbgs() << "Function " << F->getName() << ":\n";157BannerPrinted = true;158}159dbgs() << "Probe " << I.first.first << "\tprevious factor "160<< format("%0.2f", PrevProbeFactor) << "\tcurrent factor "161<< format("%0.2f", CurProbeFactor) << "\n";162}163}164165// Update166PrevProbeFactors[I.first] = I.second;167}168}169170SampleProfileProber::SampleProfileProber(Function &Func,171const std::string &CurModuleUniqueId)172: F(&Func), CurModuleUniqueId(CurModuleUniqueId) {173BlockProbeIds.clear();174CallProbeIds.clear();175LastProbeId = (uint32_t)PseudoProbeReservedId::Last;176177DenseSet<BasicBlock *> BlocksToIgnore;178DenseSet<BasicBlock *> BlocksAndCallsToIgnore;179computeBlocksToIgnore(BlocksToIgnore, BlocksAndCallsToIgnore);180181computeProbeId(BlocksToIgnore, BlocksAndCallsToIgnore);182computeCFGHash(BlocksToIgnore);183}184185// Two purposes to compute the blocks to ignore:186// 1. Reduce the IR size.187// 2. Make the instrumentation(checksum) stable. e.g. the frondend may188// generate unstable IR while optimizing nounwind attribute, some versions are189// optimized with the call-to-invoke conversion, while other versions do not.190// This discrepancy in probe ID could cause profile mismatching issues.191// Note that those ignored blocks are either cold blocks or new split blocks192// whose original blocks are instrumented, so it shouldn't degrade the profile193// quality.194void SampleProfileProber::computeBlocksToIgnore(195DenseSet<BasicBlock *> &BlocksToIgnore,196DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {197// Ignore the cold EH and unreachable blocks and calls.198computeEHOnlyBlocks(*F, BlocksAndCallsToIgnore);199findUnreachableBlocks(BlocksAndCallsToIgnore);200201BlocksToIgnore.insert(BlocksAndCallsToIgnore.begin(),202BlocksAndCallsToIgnore.end());203204// Handle the call-to-invoke conversion case: make sure that the probe id and205// callsite id are consistent before and after the block split. For block206// probe, we only keep the head block probe id and ignore the block ids of the207// normal dests. For callsite probe, it's different to block probe, there is208// no additional callsite in the normal dests, so we don't ignore the209// callsites.210findInvokeNormalDests(BlocksToIgnore);211}212213// Unreachable blocks and calls are always cold, ignore them.214void SampleProfileProber::findUnreachableBlocks(215DenseSet<BasicBlock *> &BlocksToIgnore) {216for (auto &BB : *F) {217if (&BB != &F->getEntryBlock() && pred_size(&BB) == 0)218BlocksToIgnore.insert(&BB);219}220}221222// In call-to-invoke conversion, basic block can be split into multiple blocks,223// only instrument probe in the head block, ignore the normal dests.224void SampleProfileProber::findInvokeNormalDests(225DenseSet<BasicBlock *> &InvokeNormalDests) {226for (auto &BB : *F) {227auto *TI = BB.getTerminator();228if (auto *II = dyn_cast<InvokeInst>(TI)) {229auto *ND = II->getNormalDest();230InvokeNormalDests.insert(ND);231232// The normal dest and the try/catch block are connected by an233// unconditional branch.234while (pred_size(ND) == 1) {235auto *Pred = *pred_begin(ND);236if (succ_size(Pred) == 1) {237InvokeNormalDests.insert(Pred);238ND = Pred;239} else240break;241}242}243}244}245246// The call-to-invoke conversion splits the original block into a list of block,247// we need to compute the hash using the original block's successors to keep the248// CFG Hash consistent. For a given head block, we keep searching the249// succesor(normal dest or unconditional branch dest) to find the tail block,250// the tail block's successors are the original block's successors.251const Instruction *SampleProfileProber::getOriginalTerminator(252const BasicBlock *Head, const DenseSet<BasicBlock *> &BlocksToIgnore) {253auto *TI = Head->getTerminator();254if (auto *II = dyn_cast<InvokeInst>(TI)) {255return getOriginalTerminator(II->getNormalDest(), BlocksToIgnore);256} else if (succ_size(Head) == 1 &&257BlocksToIgnore.contains(*succ_begin(Head))) {258// Go to the unconditional branch dest.259return getOriginalTerminator(*succ_begin(Head), BlocksToIgnore);260}261return TI;262}263264// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index265// value of each BB in the CFG. The higher 32 bits record the number of edges266// preceded by the number of indirect calls.267// This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().268void SampleProfileProber::computeCFGHash(269const DenseSet<BasicBlock *> &BlocksToIgnore) {270std::vector<uint8_t> Indexes;271JamCRC JC;272for (auto &BB : *F) {273if (BlocksToIgnore.contains(&BB))274continue;275276auto *TI = getOriginalTerminator(&BB, BlocksToIgnore);277for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {278auto *Succ = TI->getSuccessor(I);279auto Index = getBlockId(Succ);280// Ingore ignored-block(zero ID) to avoid unstable checksum.281if (Index == 0)282continue;283for (int J = 0; J < 4; J++)284Indexes.push_back((uint8_t)(Index >> (J * 8)));285}286}287288JC.update(Indexes);289290FunctionHash = (uint64_t)CallProbeIds.size() << 48 |291(uint64_t)Indexes.size() << 32 | JC.getCRC();292// Reserve bit 60-63 for other information purpose.293FunctionHash &= 0x0FFFFFFFFFFFFFFF;294assert(FunctionHash && "Function checksum should not be zero");295LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()296<< ":\n"297<< " CRC = " << JC.getCRC() << ", Edges = "298<< Indexes.size() << ", ICSites = " << CallProbeIds.size()299<< ", Hash = " << FunctionHash << "\n");300}301302void SampleProfileProber::computeProbeId(303const DenseSet<BasicBlock *> &BlocksToIgnore,304const DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {305LLVMContext &Ctx = F->getContext();306Module *M = F->getParent();307308for (auto &BB : *F) {309if (!BlocksToIgnore.contains(&BB))310BlockProbeIds[&BB] = ++LastProbeId;311312if (BlocksAndCallsToIgnore.contains(&BB))313continue;314for (auto &I : BB) {315if (!isa<CallBase>(I) || isa<IntrinsicInst>(&I))316continue;317318// The current implementation uses the lower 16 bits of the discriminator319// so anything larger than 0xFFFF will be ignored.320if (LastProbeId >= 0xFFFF) {321std::string Msg = "Pseudo instrumentation incomplete for " +322std::string(F->getName()) + " because it's too large";323Ctx.diagnose(324DiagnosticInfoSampleProfile(M->getName().data(), Msg, DS_Warning));325return;326}327328CallProbeIds[&I] = ++LastProbeId;329}330}331}332333uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {334auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB));335return I == BlockProbeIds.end() ? 0 : I->second;336}337338uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {339auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call));340return Iter == CallProbeIds.end() ? 0 : Iter->second;341}342343void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {344Module *M = F.getParent();345MDBuilder MDB(F.getContext());346// Since the GUID from probe desc and inline stack are computed separately, we347// need to make sure their names are consistent, so here also use the name348// from debug info.349StringRef FName = F.getName();350if (auto *SP = F.getSubprogram()) {351FName = SP->getLinkageName();352if (FName.empty())353FName = SP->getName();354}355uint64_t Guid = Function::getGUID(FName);356357// Assign an artificial debug line to a probe that doesn't come with a real358// line. A probe not having a debug line will get an incomplete inline359// context. This will cause samples collected on the probe to be counted360// into the base profile instead of a context profile. The line number361// itself is not important though.362auto AssignDebugLoc = [&](Instruction *I) {363assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&364"Expecting pseudo probe or call instructions");365if (!I->getDebugLoc()) {366if (auto *SP = F.getSubprogram()) {367auto DIL = DILocation::get(SP->getContext(), 0, 0, SP);368I->setDebugLoc(DIL);369ArtificialDbgLine++;370LLVM_DEBUG({371dbgs() << "\nIn Function " << F.getName()372<< " Probe gets an artificial debug line\n";373I->dump();374});375}376}377};378379// Probe basic blocks.380for (auto &I : BlockProbeIds) {381BasicBlock *BB = I.first;382uint32_t Index = I.second;383// Insert a probe before an instruction with a valid debug line number which384// will be assigned to the probe. The line number will be used later to385// model the inline context when the probe is inlined into other functions.386// Debug instructions, phi nodes and lifetime markers do not have an valid387// line number. Real instructions generated by optimizations may not come388// with a line number either.389auto HasValidDbgLine = [](Instruction *J) {390return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) &&391!J->isLifetimeStartOrEnd() && J->getDebugLoc();392};393394Instruction *J = &*BB->getFirstInsertionPt();395while (J != BB->getTerminator() && !HasValidDbgLine(J)) {396J = J->getNextNode();397}398399IRBuilder<> Builder(J);400assert(Builder.GetInsertPoint() != BB->end() &&401"Cannot get the probing point");402Function *ProbeFn =403llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe);404Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index),405Builder.getInt32(0),406Builder.getInt64(PseudoProbeFullDistributionFactor)};407auto *Probe = Builder.CreateCall(ProbeFn, Args);408AssignDebugLoc(Probe);409// Reset the dwarf discriminator if the debug location comes with any. The410// discriminator field may be used by FS-AFDO later in the pipeline.411if (auto DIL = Probe->getDebugLoc()) {412if (DIL->getDiscriminator()) {413DIL = DIL->cloneWithDiscriminator(0);414Probe->setDebugLoc(DIL);415}416}417}418419// Probe both direct calls and indirect calls. Direct calls are probed so that420// their probe ID can be used as an call site identifier to represent a421// calling context.422for (auto &I : CallProbeIds) {423auto *Call = I.first;424uint32_t Index = I.second;425uint32_t Type = cast<CallBase>(Call)->getCalledFunction()426? (uint32_t)PseudoProbeType::DirectCall427: (uint32_t)PseudoProbeType::IndirectCall;428AssignDebugLoc(Call);429if (auto DIL = Call->getDebugLoc()) {430// Levarge the 32-bit discriminator field of debug data to store the ID431// and type of a callsite probe. This gets rid of the dependency on432// plumbing a customized metadata through the codegen pipeline.433uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(434Index, Type, 0, PseudoProbeDwarfDiscriminator::FullDistributionFactor,435DIL->getBaseDiscriminator());436DIL = DIL->cloneWithDiscriminator(V);437Call->setDebugLoc(DIL);438}439}440441// Create module-level metadata that contains function info necessary to442// synthesize probe-based sample counts, which are443// - FunctionGUID444// - FunctionHash.445// - FunctionName446auto Hash = getFunctionHash();447auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, FName);448auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName);449assert(NMD && "llvm.pseudo_probe_desc should be pre-created");450NMD->addOperand(MD);451}452453PreservedAnalyses SampleProfileProbePass::run(Module &M,454ModuleAnalysisManager &AM) {455auto ModuleId = getUniqueModuleId(&M);456// Create the pseudo probe desc metadata beforehand.457// Note that modules with only data but no functions will require this to458// be set up so that they will be known as probed later.459M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName);460461for (auto &F : M) {462if (F.isDeclaration())463continue;464SampleProfileProber ProbeManager(F, ModuleId);465ProbeManager.instrumentOneFunc(F, TM);466}467468return PreservedAnalyses::none();469}470471void PseudoProbeUpdatePass::runOnFunction(Function &F,472FunctionAnalysisManager &FAM) {473BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);474auto BBProfileCount = [&BFI](BasicBlock *BB) {475return BFI.getBlockProfileCount(BB).value_or(0);476};477478// Collect the sum of execution weight for each probe.479ProbeFactorMap ProbeFactors;480for (auto &Block : F) {481for (auto &I : Block) {482if (std::optional<PseudoProbe> Probe = extractProbe(I)) {483uint64_t Hash = computeCallStackHash(I);484ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);485}486}487}488489// Fix up over-counted probes.490for (auto &Block : F) {491for (auto &I : Block) {492if (std::optional<PseudoProbe> Probe = extractProbe(I)) {493uint64_t Hash = computeCallStackHash(I);494float Sum = ProbeFactors[{Probe->Id, Hash}];495if (Sum != 0)496setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum);497}498}499}500}501502PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,503ModuleAnalysisManager &AM) {504if (UpdatePseudoProbe) {505for (auto &F : M) {506if (F.isDeclaration())507continue;508FunctionAnalysisManager &FAM =509AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();510runOnFunction(F, FAM);511}512}513return PreservedAnalyses::none();514}515516517