xref: /src/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1b60736ecSDimitry Andric //===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===//
2b60736ecSDimitry Andric //
3b60736ecSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4b60736ecSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5b60736ecSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b60736ecSDimitry Andric //
7b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
8b60736ecSDimitry Andric //
9b60736ecSDimitry Andric // This file implements the SampleProfileProber transformation.
10b60736ecSDimitry Andric //
11b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
12b60736ecSDimitry Andric 
13b60736ecSDimitry Andric #include "llvm/Transforms/IPO/SampleProfileProbe.h"
14b60736ecSDimitry Andric #include "llvm/ADT/Statistic.h"
15344a3780SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
167fa27ce4SDimitry Andric #include "llvm/Analysis/EHUtils.h"
17145449b1SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
18b60736ecSDimitry Andric #include "llvm/IR/BasicBlock.h"
19b60736ecSDimitry Andric #include "llvm/IR/Constants.h"
20b60736ecSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
21b1c73532SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
22b60736ecSDimitry Andric #include "llvm/IR/IRBuilder.h"
23b60736ecSDimitry Andric #include "llvm/IR/Instruction.h"
24ecbca9f5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
25b60736ecSDimitry Andric #include "llvm/IR/MDBuilder.h"
26ac9a064cSDimitry Andric #include "llvm/IR/Module.h"
27145449b1SDimitry Andric #include "llvm/IR/PseudoProbe.h"
28b60736ecSDimitry Andric #include "llvm/ProfileData/SampleProf.h"
29b60736ecSDimitry Andric #include "llvm/Support/CRC.h"
30344a3780SDimitry Andric #include "llvm/Support/CommandLine.h"
31145449b1SDimitry Andric #include "llvm/Target/TargetMachine.h"
32b60736ecSDimitry Andric #include "llvm/Transforms/Instrumentation.h"
33b60736ecSDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
34344a3780SDimitry Andric #include <unordered_set>
35b60736ecSDimitry Andric #include <vector>
36b60736ecSDimitry Andric 
37b60736ecSDimitry Andric using namespace llvm;
387fa27ce4SDimitry Andric #define DEBUG_TYPE "pseudo-probe"
39b60736ecSDimitry Andric 
40b60736ecSDimitry Andric STATISTIC(ArtificialDbgLine,
41b60736ecSDimitry Andric           "Number of probes that have an artificial debug line");
42b60736ecSDimitry Andric 
43344a3780SDimitry Andric static cl::opt<bool>
44344a3780SDimitry Andric     VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden,
45344a3780SDimitry Andric                       cl::desc("Do pseudo probe verification"));
46344a3780SDimitry Andric 
47344a3780SDimitry Andric static cl::list<std::string> VerifyPseudoProbeFuncList(
48344a3780SDimitry Andric     "verify-pseudo-probe-funcs", cl::Hidden,
49344a3780SDimitry Andric     cl::desc("The option to specify the name of the functions to verify."));
50344a3780SDimitry Andric 
51344a3780SDimitry Andric static cl::opt<bool>
52344a3780SDimitry Andric     UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden,
53344a3780SDimitry Andric                       cl::desc("Update pseudo probe distribution factor"));
54344a3780SDimitry Andric 
getCallStackHash(const DILocation * DIL)55344a3780SDimitry Andric static uint64_t getCallStackHash(const DILocation *DIL) {
56344a3780SDimitry Andric   uint64_t Hash = 0;
57344a3780SDimitry Andric   const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;
58344a3780SDimitry Andric   while (InlinedAt) {
59344a3780SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getLine()));
60344a3780SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn()));
617fa27ce4SDimitry Andric     auto Name = InlinedAt->getSubprogramLinkageName();
62344a3780SDimitry Andric     Hash ^= MD5Hash(Name);
63344a3780SDimitry Andric     InlinedAt = InlinedAt->getInlinedAt();
64344a3780SDimitry Andric   }
65344a3780SDimitry Andric   return Hash;
66344a3780SDimitry Andric }
67344a3780SDimitry Andric 
computeCallStackHash(const Instruction & Inst)68344a3780SDimitry Andric static uint64_t computeCallStackHash(const Instruction &Inst) {
69344a3780SDimitry Andric   return getCallStackHash(Inst.getDebugLoc());
70344a3780SDimitry Andric }
71344a3780SDimitry Andric 
shouldVerifyFunction(const Function * F)72344a3780SDimitry Andric bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
73344a3780SDimitry Andric   // Skip function declaration.
74344a3780SDimitry Andric   if (F->isDeclaration())
75344a3780SDimitry Andric     return false;
76344a3780SDimitry Andric   // Skip function that will not be emitted into object file. The prevailing
77344a3780SDimitry Andric   // defintion will be verified instead.
78344a3780SDimitry Andric   if (F->hasAvailableExternallyLinkage())
79344a3780SDimitry Andric     return false;
80344a3780SDimitry Andric   // Do a name matching.
81344a3780SDimitry Andric   static std::unordered_set<std::string> VerifyFuncNames(
82344a3780SDimitry Andric       VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());
83344a3780SDimitry Andric   return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str());
84344a3780SDimitry Andric }
85344a3780SDimitry Andric 
registerCallbacks(PassInstrumentationCallbacks & PIC)86344a3780SDimitry Andric void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
87344a3780SDimitry Andric   if (VerifyPseudoProbe) {
88344a3780SDimitry Andric     PIC.registerAfterPassCallback(
89344a3780SDimitry Andric         [this](StringRef P, Any IR, const PreservedAnalyses &) {
90344a3780SDimitry Andric           this->runAfterPass(P, IR);
91344a3780SDimitry Andric         });
92344a3780SDimitry Andric   }
93344a3780SDimitry Andric }
94344a3780SDimitry Andric 
95344a3780SDimitry Andric // Callback to run after each transformation for the new pass manager.
runAfterPass(StringRef PassID,Any IR)96344a3780SDimitry Andric void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {
97344a3780SDimitry Andric   std::string Banner =
98344a3780SDimitry Andric       "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
99344a3780SDimitry Andric   dbgs() << Banner;
100b1c73532SDimitry Andric   if (const auto **M = llvm::any_cast<const Module *>(&IR))
101e3b55780SDimitry Andric     runAfterPass(*M);
102b1c73532SDimitry Andric   else if (const auto **F = llvm::any_cast<const Function *>(&IR))
103e3b55780SDimitry Andric     runAfterPass(*F);
104b1c73532SDimitry Andric   else if (const auto **C = llvm::any_cast<const LazyCallGraph::SCC *>(&IR))
105e3b55780SDimitry Andric     runAfterPass(*C);
106b1c73532SDimitry Andric   else if (const auto **L = llvm::any_cast<const Loop *>(&IR))
107e3b55780SDimitry Andric     runAfterPass(*L);
108344a3780SDimitry Andric   else
109344a3780SDimitry Andric     llvm_unreachable("Unknown IR unit");
110344a3780SDimitry Andric }
111344a3780SDimitry Andric 
runAfterPass(const Module * M)112344a3780SDimitry Andric void PseudoProbeVerifier::runAfterPass(const Module *M) {
113344a3780SDimitry Andric   for (const Function &F : *M)
114344a3780SDimitry Andric     runAfterPass(&F);
115344a3780SDimitry Andric }
116344a3780SDimitry Andric 
runAfterPass(const LazyCallGraph::SCC * C)117344a3780SDimitry Andric void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {
118344a3780SDimitry Andric   for (const LazyCallGraph::Node &N : *C)
119344a3780SDimitry Andric     runAfterPass(&N.getFunction());
120344a3780SDimitry Andric }
121344a3780SDimitry Andric 
runAfterPass(const Function * F)122344a3780SDimitry Andric void PseudoProbeVerifier::runAfterPass(const Function *F) {
123344a3780SDimitry Andric   if (!shouldVerifyFunction(F))
124344a3780SDimitry Andric     return;
125344a3780SDimitry Andric   ProbeFactorMap ProbeFactors;
126344a3780SDimitry Andric   for (const auto &BB : *F)
127344a3780SDimitry Andric     collectProbeFactors(&BB, ProbeFactors);
128344a3780SDimitry Andric   verifyProbeFactors(F, ProbeFactors);
129344a3780SDimitry Andric }
130344a3780SDimitry Andric 
runAfterPass(const Loop * L)131344a3780SDimitry Andric void PseudoProbeVerifier::runAfterPass(const Loop *L) {
132344a3780SDimitry Andric   const Function *F = L->getHeader()->getParent();
133344a3780SDimitry Andric   runAfterPass(F);
134344a3780SDimitry Andric }
135344a3780SDimitry Andric 
collectProbeFactors(const BasicBlock * Block,ProbeFactorMap & ProbeFactors)136344a3780SDimitry Andric void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,
137344a3780SDimitry Andric                                               ProbeFactorMap &ProbeFactors) {
138344a3780SDimitry Andric   for (const auto &I : *Block) {
139e3b55780SDimitry Andric     if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
140344a3780SDimitry Andric       uint64_t Hash = computeCallStackHash(I);
141344a3780SDimitry Andric       ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;
142344a3780SDimitry Andric     }
143344a3780SDimitry Andric   }
144344a3780SDimitry Andric }
145344a3780SDimitry Andric 
verifyProbeFactors(const Function * F,const ProbeFactorMap & ProbeFactors)146344a3780SDimitry Andric void PseudoProbeVerifier::verifyProbeFactors(
147344a3780SDimitry Andric     const Function *F, const ProbeFactorMap &ProbeFactors) {
148344a3780SDimitry Andric   bool BannerPrinted = false;
149344a3780SDimitry Andric   auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];
150344a3780SDimitry Andric   for (const auto &I : ProbeFactors) {
151344a3780SDimitry Andric     float CurProbeFactor = I.second;
152344a3780SDimitry Andric     if (PrevProbeFactors.count(I.first)) {
153344a3780SDimitry Andric       float PrevProbeFactor = PrevProbeFactors[I.first];
154344a3780SDimitry Andric       if (std::abs(CurProbeFactor - PrevProbeFactor) >
155344a3780SDimitry Andric           DistributionFactorVariance) {
156344a3780SDimitry Andric         if (!BannerPrinted) {
157344a3780SDimitry Andric           dbgs() << "Function " << F->getName() << ":\n";
158344a3780SDimitry Andric           BannerPrinted = true;
159344a3780SDimitry Andric         }
160344a3780SDimitry Andric         dbgs() << "Probe " << I.first.first << "\tprevious factor "
161344a3780SDimitry Andric                << format("%0.2f", PrevProbeFactor) << "\tcurrent factor "
162344a3780SDimitry Andric                << format("%0.2f", CurProbeFactor) << "\n";
163344a3780SDimitry Andric       }
164344a3780SDimitry Andric     }
165344a3780SDimitry Andric 
166344a3780SDimitry Andric     // Update
167344a3780SDimitry Andric     PrevProbeFactors[I.first] = I.second;
168344a3780SDimitry Andric   }
169344a3780SDimitry Andric }
170344a3780SDimitry Andric 
SampleProfileProber(Function & Func,const std::string & CurModuleUniqueId)171b60736ecSDimitry Andric SampleProfileProber::SampleProfileProber(Function &Func,
172b60736ecSDimitry Andric                                          const std::string &CurModuleUniqueId)
173b60736ecSDimitry Andric     : F(&Func), CurModuleUniqueId(CurModuleUniqueId) {
174b60736ecSDimitry Andric   BlockProbeIds.clear();
175b60736ecSDimitry Andric   CallProbeIds.clear();
176b60736ecSDimitry Andric   LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
177ac9a064cSDimitry Andric 
178ac9a064cSDimitry Andric   DenseSet<BasicBlock *> BlocksToIgnore;
179ac9a064cSDimitry Andric   DenseSet<BasicBlock *> BlocksAndCallsToIgnore;
180ac9a064cSDimitry Andric   computeBlocksToIgnore(BlocksToIgnore, BlocksAndCallsToIgnore);
181ac9a064cSDimitry Andric 
182ac9a064cSDimitry Andric   computeProbeId(BlocksToIgnore, BlocksAndCallsToIgnore);
183ac9a064cSDimitry Andric   computeCFGHash(BlocksToIgnore);
184ac9a064cSDimitry Andric }
185ac9a064cSDimitry Andric 
186ac9a064cSDimitry Andric // Two purposes to compute the blocks to ignore:
187ac9a064cSDimitry Andric // 1. Reduce the IR size.
188ac9a064cSDimitry Andric // 2. Make the instrumentation(checksum) stable. e.g. the frondend may
189ac9a064cSDimitry Andric // generate unstable IR while optimizing nounwind attribute, some versions are
190ac9a064cSDimitry Andric // optimized with the call-to-invoke conversion, while other versions do not.
191ac9a064cSDimitry Andric // This discrepancy in probe ID could cause profile mismatching issues.
192ac9a064cSDimitry Andric // Note that those ignored blocks are either cold blocks or new split blocks
193ac9a064cSDimitry Andric // whose original blocks are instrumented, so it shouldn't degrade the profile
194ac9a064cSDimitry Andric // quality.
computeBlocksToIgnore(DenseSet<BasicBlock * > & BlocksToIgnore,DenseSet<BasicBlock * > & BlocksAndCallsToIgnore)195ac9a064cSDimitry Andric void SampleProfileProber::computeBlocksToIgnore(
196ac9a064cSDimitry Andric     DenseSet<BasicBlock *> &BlocksToIgnore,
197ac9a064cSDimitry Andric     DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
198ac9a064cSDimitry Andric   // Ignore the cold EH and unreachable blocks and calls.
199ac9a064cSDimitry Andric   computeEHOnlyBlocks(*F, BlocksAndCallsToIgnore);
200ac9a064cSDimitry Andric   findUnreachableBlocks(BlocksAndCallsToIgnore);
201ac9a064cSDimitry Andric 
202ac9a064cSDimitry Andric   BlocksToIgnore.insert(BlocksAndCallsToIgnore.begin(),
203ac9a064cSDimitry Andric                         BlocksAndCallsToIgnore.end());
204ac9a064cSDimitry Andric 
205ac9a064cSDimitry Andric   // Handle the call-to-invoke conversion case: make sure that the probe id and
206ac9a064cSDimitry Andric   // callsite id are consistent before and after the block split. For block
207ac9a064cSDimitry Andric   // probe, we only keep the head block probe id and ignore the block ids of the
208ac9a064cSDimitry Andric   // normal dests. For callsite probe, it's different to block probe, there is
209ac9a064cSDimitry Andric   // no additional callsite in the normal dests, so we don't ignore the
210ac9a064cSDimitry Andric   // callsites.
211ac9a064cSDimitry Andric   findInvokeNormalDests(BlocksToIgnore);
212ac9a064cSDimitry Andric }
213ac9a064cSDimitry Andric 
214ac9a064cSDimitry Andric // Unreachable blocks and calls are always cold, ignore them.
findUnreachableBlocks(DenseSet<BasicBlock * > & BlocksToIgnore)215ac9a064cSDimitry Andric void SampleProfileProber::findUnreachableBlocks(
216ac9a064cSDimitry Andric     DenseSet<BasicBlock *> &BlocksToIgnore) {
217ac9a064cSDimitry Andric   for (auto &BB : *F) {
218ac9a064cSDimitry Andric     if (&BB != &F->getEntryBlock() && pred_size(&BB) == 0)
219ac9a064cSDimitry Andric       BlocksToIgnore.insert(&BB);
220ac9a064cSDimitry Andric   }
221ac9a064cSDimitry Andric }
222ac9a064cSDimitry Andric 
223ac9a064cSDimitry Andric // In call-to-invoke conversion, basic block can be split into multiple blocks,
224ac9a064cSDimitry Andric // only instrument probe in the head block, ignore the normal dests.
findInvokeNormalDests(DenseSet<BasicBlock * > & InvokeNormalDests)225ac9a064cSDimitry Andric void SampleProfileProber::findInvokeNormalDests(
226ac9a064cSDimitry Andric     DenseSet<BasicBlock *> &InvokeNormalDests) {
227ac9a064cSDimitry Andric   for (auto &BB : *F) {
228ac9a064cSDimitry Andric     auto *TI = BB.getTerminator();
229ac9a064cSDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
230ac9a064cSDimitry Andric       auto *ND = II->getNormalDest();
231ac9a064cSDimitry Andric       InvokeNormalDests.insert(ND);
232ac9a064cSDimitry Andric 
233ac9a064cSDimitry Andric       // The normal dest and the try/catch block are connected by an
234ac9a064cSDimitry Andric       // unconditional branch.
235ac9a064cSDimitry Andric       while (pred_size(ND) == 1) {
236ac9a064cSDimitry Andric         auto *Pred = *pred_begin(ND);
237ac9a064cSDimitry Andric         if (succ_size(Pred) == 1) {
238ac9a064cSDimitry Andric           InvokeNormalDests.insert(Pred);
239ac9a064cSDimitry Andric           ND = Pred;
240ac9a064cSDimitry Andric         } else
241ac9a064cSDimitry Andric           break;
242ac9a064cSDimitry Andric       }
243ac9a064cSDimitry Andric     }
244ac9a064cSDimitry Andric   }
245ac9a064cSDimitry Andric }
246ac9a064cSDimitry Andric 
247ac9a064cSDimitry Andric // The call-to-invoke conversion splits the original block into a list of block,
248ac9a064cSDimitry Andric // we need to compute the hash using the original block's successors to keep the
249ac9a064cSDimitry Andric // CFG Hash consistent. For a given head block, we keep searching the
250ac9a064cSDimitry Andric // succesor(normal dest or unconditional branch dest) to find the tail block,
251ac9a064cSDimitry Andric // the tail block's successors are the original block's successors.
getOriginalTerminator(const BasicBlock * Head,const DenseSet<BasicBlock * > & BlocksToIgnore)252ac9a064cSDimitry Andric const Instruction *SampleProfileProber::getOriginalTerminator(
253ac9a064cSDimitry Andric     const BasicBlock *Head, const DenseSet<BasicBlock *> &BlocksToIgnore) {
254ac9a064cSDimitry Andric   auto *TI = Head->getTerminator();
255ac9a064cSDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI)) {
256ac9a064cSDimitry Andric     return getOriginalTerminator(II->getNormalDest(), BlocksToIgnore);
257ac9a064cSDimitry Andric   } else if (succ_size(Head) == 1 &&
258ac9a064cSDimitry Andric              BlocksToIgnore.contains(*succ_begin(Head))) {
259ac9a064cSDimitry Andric     // Go to the unconditional branch dest.
260ac9a064cSDimitry Andric     return getOriginalTerminator(*succ_begin(Head), BlocksToIgnore);
261ac9a064cSDimitry Andric   }
262ac9a064cSDimitry Andric   return TI;
263b60736ecSDimitry Andric }
264b60736ecSDimitry Andric 
265b60736ecSDimitry Andric // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
266b60736ecSDimitry Andric // value of each BB in the CFG. The higher 32 bits record the number of edges
267b60736ecSDimitry Andric // preceded by the number of indirect calls.
268b60736ecSDimitry Andric // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().
computeCFGHash(const DenseSet<BasicBlock * > & BlocksToIgnore)269ac9a064cSDimitry Andric void SampleProfileProber::computeCFGHash(
270ac9a064cSDimitry Andric     const DenseSet<BasicBlock *> &BlocksToIgnore) {
271b60736ecSDimitry Andric   std::vector<uint8_t> Indexes;
272b60736ecSDimitry Andric   JamCRC JC;
273b60736ecSDimitry Andric   for (auto &BB : *F) {
274ac9a064cSDimitry Andric     if (BlocksToIgnore.contains(&BB))
275ac9a064cSDimitry Andric       continue;
276ac9a064cSDimitry Andric 
277ac9a064cSDimitry Andric     auto *TI = getOriginalTerminator(&BB, BlocksToIgnore);
278ac9a064cSDimitry Andric     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
279ac9a064cSDimitry Andric       auto *Succ = TI->getSuccessor(I);
280b60736ecSDimitry Andric       auto Index = getBlockId(Succ);
281ac9a064cSDimitry Andric       // Ingore ignored-block(zero ID) to avoid unstable checksum.
282ac9a064cSDimitry Andric       if (Index == 0)
283ac9a064cSDimitry Andric         continue;
284b60736ecSDimitry Andric       for (int J = 0; J < 4; J++)
285b60736ecSDimitry Andric         Indexes.push_back((uint8_t)(Index >> (J * 8)));
286b60736ecSDimitry Andric     }
287b60736ecSDimitry Andric   }
288b60736ecSDimitry Andric 
289b60736ecSDimitry Andric   JC.update(Indexes);
290b60736ecSDimitry Andric 
291b60736ecSDimitry Andric   FunctionHash = (uint64_t)CallProbeIds.size() << 48 |
292b60736ecSDimitry Andric                  (uint64_t)Indexes.size() << 32 | JC.getCRC();
293b60736ecSDimitry Andric   // Reserve bit 60-63 for other information purpose.
294b60736ecSDimitry Andric   FunctionHash &= 0x0FFFFFFFFFFFFFFF;
295b60736ecSDimitry Andric   assert(FunctionHash && "Function checksum should not be zero");
296b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()
297b60736ecSDimitry Andric                     << ":\n"
298b60736ecSDimitry Andric                     << " CRC = " << JC.getCRC() << ", Edges = "
299b60736ecSDimitry Andric                     << Indexes.size() << ", ICSites = " << CallProbeIds.size()
300b60736ecSDimitry Andric                     << ", Hash = " << FunctionHash << "\n");
301b60736ecSDimitry Andric }
302b60736ecSDimitry Andric 
computeProbeId(const DenseSet<BasicBlock * > & BlocksToIgnore,const DenseSet<BasicBlock * > & BlocksAndCallsToIgnore)303ac9a064cSDimitry Andric void SampleProfileProber::computeProbeId(
304ac9a064cSDimitry Andric     const DenseSet<BasicBlock *> &BlocksToIgnore,
305ac9a064cSDimitry Andric     const DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
306b1c73532SDimitry Andric   LLVMContext &Ctx = F->getContext();
307b1c73532SDimitry Andric   Module *M = F->getParent();
308b1c73532SDimitry Andric 
309b60736ecSDimitry Andric   for (auto &BB : *F) {
310ac9a064cSDimitry Andric     if (!BlocksToIgnore.contains(&BB))
311ac9a064cSDimitry Andric       BlockProbeIds[&BB] = ++LastProbeId;
312ac9a064cSDimitry Andric 
313ac9a064cSDimitry Andric     if (BlocksAndCallsToIgnore.contains(&BB))
314b60736ecSDimitry Andric       continue;
315ac9a064cSDimitry Andric     for (auto &I : BB) {
316ac9a064cSDimitry Andric       if (!isa<CallBase>(I) || isa<IntrinsicInst>(&I))
317b60736ecSDimitry Andric         continue;
318b1c73532SDimitry Andric 
319b1c73532SDimitry Andric       // The current implementation uses the lower 16 bits of the discriminator
320b1c73532SDimitry Andric       // so anything larger than 0xFFFF will be ignored.
321b1c73532SDimitry Andric       if (LastProbeId >= 0xFFFF) {
322b1c73532SDimitry Andric         std::string Msg = "Pseudo instrumentation incomplete for " +
323b1c73532SDimitry Andric                           std::string(F->getName()) + " because it's too large";
324b1c73532SDimitry Andric         Ctx.diagnose(
325b1c73532SDimitry Andric             DiagnosticInfoSampleProfile(M->getName().data(), Msg, DS_Warning));
326b1c73532SDimitry Andric         return;
327b1c73532SDimitry Andric       }
328b1c73532SDimitry Andric 
329b60736ecSDimitry Andric       CallProbeIds[&I] = ++LastProbeId;
330b60736ecSDimitry Andric     }
331b60736ecSDimitry Andric   }
332b60736ecSDimitry Andric }
333b60736ecSDimitry Andric 
getBlockId(const BasicBlock * BB) const334b60736ecSDimitry Andric uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {
335b60736ecSDimitry Andric   auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB));
336b60736ecSDimitry Andric   return I == BlockProbeIds.end() ? 0 : I->second;
337b60736ecSDimitry Andric }
338b60736ecSDimitry Andric 
getCallsiteId(const Instruction * Call) const339b60736ecSDimitry Andric uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {
340b60736ecSDimitry Andric   auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call));
341b60736ecSDimitry Andric   return Iter == CallProbeIds.end() ? 0 : Iter->second;
342b60736ecSDimitry Andric }
343b60736ecSDimitry Andric 
instrumentOneFunc(Function & F,TargetMachine * TM)344b60736ecSDimitry Andric void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {
345b60736ecSDimitry Andric   Module *M = F.getParent();
346b60736ecSDimitry Andric   MDBuilder MDB(F.getContext());
347ac9a064cSDimitry Andric   // Since the GUID from probe desc and inline stack are computed separately, we
3487fa27ce4SDimitry Andric   // need to make sure their names are consistent, so here also use the name
3497fa27ce4SDimitry Andric   // from debug info.
3507fa27ce4SDimitry Andric   StringRef FName = F.getName();
3517fa27ce4SDimitry Andric   if (auto *SP = F.getSubprogram()) {
3527fa27ce4SDimitry Andric     FName = SP->getLinkageName();
3537fa27ce4SDimitry Andric     if (FName.empty())
3547fa27ce4SDimitry Andric       FName = SP->getName();
3557fa27ce4SDimitry Andric   }
3567fa27ce4SDimitry Andric   uint64_t Guid = Function::getGUID(FName);
357b60736ecSDimitry Andric 
358b60736ecSDimitry Andric   // Assign an artificial debug line to a probe that doesn't come with a real
359b60736ecSDimitry Andric   // line. A probe not having a debug line will get an incomplete inline
360b60736ecSDimitry Andric   // context. This will cause samples collected on the probe to be counted
361b60736ecSDimitry Andric   // into the base profile instead of a context profile. The line number
362b60736ecSDimitry Andric   // itself is not important though.
363b60736ecSDimitry Andric   auto AssignDebugLoc = [&](Instruction *I) {
364b60736ecSDimitry Andric     assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&
365b60736ecSDimitry Andric            "Expecting pseudo probe or call instructions");
366b60736ecSDimitry Andric     if (!I->getDebugLoc()) {
367b60736ecSDimitry Andric       if (auto *SP = F.getSubprogram()) {
368b60736ecSDimitry Andric         auto DIL = DILocation::get(SP->getContext(), 0, 0, SP);
369b60736ecSDimitry Andric         I->setDebugLoc(DIL);
370b60736ecSDimitry Andric         ArtificialDbgLine++;
371b60736ecSDimitry Andric         LLVM_DEBUG({
372b60736ecSDimitry Andric           dbgs() << "\nIn Function " << F.getName()
373b60736ecSDimitry Andric                  << " Probe gets an artificial debug line\n";
374b60736ecSDimitry Andric           I->dump();
375b60736ecSDimitry Andric         });
376b60736ecSDimitry Andric       }
377b60736ecSDimitry Andric     }
378b60736ecSDimitry Andric   };
379b60736ecSDimitry Andric 
380b60736ecSDimitry Andric   // Probe basic blocks.
381b60736ecSDimitry Andric   for (auto &I : BlockProbeIds) {
382b60736ecSDimitry Andric     BasicBlock *BB = I.first;
383b60736ecSDimitry Andric     uint32_t Index = I.second;
384b60736ecSDimitry Andric     // Insert a probe before an instruction with a valid debug line number which
385b60736ecSDimitry Andric     // will be assigned to the probe. The line number will be used later to
386b60736ecSDimitry Andric     // model the inline context when the probe is inlined into other functions.
387b60736ecSDimitry Andric     // Debug instructions, phi nodes and lifetime markers do not have an valid
388b60736ecSDimitry Andric     // line number. Real instructions generated by optimizations may not come
389b60736ecSDimitry Andric     // with a line number either.
390b60736ecSDimitry Andric     auto HasValidDbgLine = [](Instruction *J) {
391b60736ecSDimitry Andric       return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) &&
392b60736ecSDimitry Andric              !J->isLifetimeStartOrEnd() && J->getDebugLoc();
393b60736ecSDimitry Andric     };
394b60736ecSDimitry Andric 
395b60736ecSDimitry Andric     Instruction *J = &*BB->getFirstInsertionPt();
396b60736ecSDimitry Andric     while (J != BB->getTerminator() && !HasValidDbgLine(J)) {
397b60736ecSDimitry Andric       J = J->getNextNode();
398b60736ecSDimitry Andric     }
399b60736ecSDimitry Andric 
400b60736ecSDimitry Andric     IRBuilder<> Builder(J);
401b60736ecSDimitry Andric     assert(Builder.GetInsertPoint() != BB->end() &&
402b60736ecSDimitry Andric            "Cannot get the probing point");
403b60736ecSDimitry Andric     Function *ProbeFn =
404b60736ecSDimitry Andric         llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe);
405b60736ecSDimitry Andric     Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index),
406344a3780SDimitry Andric                      Builder.getInt32(0),
407344a3780SDimitry Andric                      Builder.getInt64(PseudoProbeFullDistributionFactor)};
408b60736ecSDimitry Andric     auto *Probe = Builder.CreateCall(ProbeFn, Args);
409b60736ecSDimitry Andric     AssignDebugLoc(Probe);
4107fa27ce4SDimitry Andric     // Reset the dwarf discriminator if the debug location comes with any. The
4117fa27ce4SDimitry Andric     // discriminator field may be used by FS-AFDO later in the pipeline.
4127fa27ce4SDimitry Andric     if (auto DIL = Probe->getDebugLoc()) {
4137fa27ce4SDimitry Andric       if (DIL->getDiscriminator()) {
4147fa27ce4SDimitry Andric         DIL = DIL->cloneWithDiscriminator(0);
4157fa27ce4SDimitry Andric         Probe->setDebugLoc(DIL);
4167fa27ce4SDimitry Andric       }
4177fa27ce4SDimitry Andric     }
418b60736ecSDimitry Andric   }
419b60736ecSDimitry Andric 
420b60736ecSDimitry Andric   // Probe both direct calls and indirect calls. Direct calls are probed so that
421b60736ecSDimitry Andric   // their probe ID can be used as an call site identifier to represent a
422b60736ecSDimitry Andric   // calling context.
423b60736ecSDimitry Andric   for (auto &I : CallProbeIds) {
424b60736ecSDimitry Andric     auto *Call = I.first;
425b60736ecSDimitry Andric     uint32_t Index = I.second;
426b60736ecSDimitry Andric     uint32_t Type = cast<CallBase>(Call)->getCalledFunction()
427b60736ecSDimitry Andric                         ? (uint32_t)PseudoProbeType::DirectCall
428b60736ecSDimitry Andric                         : (uint32_t)PseudoProbeType::IndirectCall;
429b60736ecSDimitry Andric     AssignDebugLoc(Call);
430b60736ecSDimitry Andric     if (auto DIL = Call->getDebugLoc()) {
4317fa27ce4SDimitry Andric       // Levarge the 32-bit discriminator field of debug data to store the ID
4327fa27ce4SDimitry Andric       // and type of a callsite probe. This gets rid of the dependency on
4337fa27ce4SDimitry Andric       // plumbing a customized metadata through the codegen pipeline.
4347fa27ce4SDimitry Andric       uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(
435ac9a064cSDimitry Andric           Index, Type, 0, PseudoProbeDwarfDiscriminator::FullDistributionFactor,
436ac9a064cSDimitry Andric           DIL->getBaseDiscriminator());
437b60736ecSDimitry Andric       DIL = DIL->cloneWithDiscriminator(V);
438b60736ecSDimitry Andric       Call->setDebugLoc(DIL);
439b60736ecSDimitry Andric     }
440b60736ecSDimitry Andric   }
441b60736ecSDimitry Andric 
442b60736ecSDimitry Andric   // Create module-level metadata that contains function info necessary to
443b60736ecSDimitry Andric   // synthesize probe-based sample counts,  which are
444b60736ecSDimitry Andric   // - FunctionGUID
445b60736ecSDimitry Andric   // - FunctionHash.
446b60736ecSDimitry Andric   // - FunctionName
447b60736ecSDimitry Andric   auto Hash = getFunctionHash();
4487fa27ce4SDimitry Andric   auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, FName);
449b60736ecSDimitry Andric   auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName);
450b60736ecSDimitry Andric   assert(NMD && "llvm.pseudo_probe_desc should be pre-created");
451b60736ecSDimitry Andric   NMD->addOperand(MD);
452b60736ecSDimitry Andric }
453b60736ecSDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)454b60736ecSDimitry Andric PreservedAnalyses SampleProfileProbePass::run(Module &M,
455b60736ecSDimitry Andric                                               ModuleAnalysisManager &AM) {
456b60736ecSDimitry Andric   auto ModuleId = getUniqueModuleId(&M);
457b60736ecSDimitry Andric   // Create the pseudo probe desc metadata beforehand.
458b60736ecSDimitry Andric   // Note that modules with only data but no functions will require this to
459b60736ecSDimitry Andric   // be set up so that they will be known as probed later.
460b60736ecSDimitry Andric   M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName);
461b60736ecSDimitry Andric 
462b60736ecSDimitry Andric   for (auto &F : M) {
463b60736ecSDimitry Andric     if (F.isDeclaration())
464b60736ecSDimitry Andric       continue;
465b60736ecSDimitry Andric     SampleProfileProber ProbeManager(F, ModuleId);
466b60736ecSDimitry Andric     ProbeManager.instrumentOneFunc(F, TM);
467b60736ecSDimitry Andric   }
468b60736ecSDimitry Andric 
469b60736ecSDimitry Andric   return PreservedAnalyses::none();
470b60736ecSDimitry Andric }
471344a3780SDimitry Andric 
runOnFunction(Function & F,FunctionAnalysisManager & FAM)472344a3780SDimitry Andric void PseudoProbeUpdatePass::runOnFunction(Function &F,
473344a3780SDimitry Andric                                           FunctionAnalysisManager &FAM) {
474344a3780SDimitry Andric   BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
475344a3780SDimitry Andric   auto BBProfileCount = [&BFI](BasicBlock *BB) {
476145449b1SDimitry Andric     return BFI.getBlockProfileCount(BB).value_or(0);
477344a3780SDimitry Andric   };
478344a3780SDimitry Andric 
479344a3780SDimitry Andric   // Collect the sum of execution weight for each probe.
480344a3780SDimitry Andric   ProbeFactorMap ProbeFactors;
481344a3780SDimitry Andric   for (auto &Block : F) {
482344a3780SDimitry Andric     for (auto &I : Block) {
483e3b55780SDimitry Andric       if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
484344a3780SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
485344a3780SDimitry Andric         ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);
486344a3780SDimitry Andric       }
487344a3780SDimitry Andric     }
488344a3780SDimitry Andric   }
489344a3780SDimitry Andric 
490344a3780SDimitry Andric   // Fix up over-counted probes.
491344a3780SDimitry Andric   for (auto &Block : F) {
492344a3780SDimitry Andric     for (auto &I : Block) {
493e3b55780SDimitry Andric       if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
494344a3780SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
495344a3780SDimitry Andric         float Sum = ProbeFactors[{Probe->Id, Hash}];
496344a3780SDimitry Andric         if (Sum != 0)
497344a3780SDimitry Andric           setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum);
498344a3780SDimitry Andric       }
499344a3780SDimitry Andric     }
500344a3780SDimitry Andric   }
501344a3780SDimitry Andric }
502344a3780SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)503344a3780SDimitry Andric PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,
504344a3780SDimitry Andric                                              ModuleAnalysisManager &AM) {
505344a3780SDimitry Andric   if (UpdatePseudoProbe) {
506344a3780SDimitry Andric     for (auto &F : M) {
507344a3780SDimitry Andric       if (F.isDeclaration())
508344a3780SDimitry Andric         continue;
509344a3780SDimitry Andric       FunctionAnalysisManager &FAM =
510344a3780SDimitry Andric           AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
511344a3780SDimitry Andric       runOnFunction(F, FAM);
512344a3780SDimitry Andric     }
513344a3780SDimitry Andric   }
514344a3780SDimitry Andric   return PreservedAnalyses::none();
515344a3780SDimitry Andric }
516