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