xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
1606c3fb27SDimitry 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"
215f757f3fSDimitry 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"
26*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
2781ad6265SDimitry Andric #include "llvm/IR/PseudoProbe.h"
28e8d8bef9SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
29e8d8bef9SDimitry Andric #include "llvm/Support/CRC.h"
30d409305fSDimitry Andric #include "llvm/Support/CommandLine.h"
3181ad6265SDimitry Andric #include "llvm/Target/TargetMachine.h"
32e8d8bef9SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
33e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
34d409305fSDimitry Andric #include <unordered_set>
35e8d8bef9SDimitry Andric #include <vector>
36e8d8bef9SDimitry Andric 
37e8d8bef9SDimitry Andric using namespace llvm;
3806c3fb27SDimitry Andric #define DEBUG_TYPE "pseudo-probe"
39e8d8bef9SDimitry Andric 
40e8d8bef9SDimitry Andric STATISTIC(ArtificialDbgLine,
41e8d8bef9SDimitry Andric           "Number of probes that have an artificial debug line");
42e8d8bef9SDimitry Andric 
43d409305fSDimitry Andric static cl::opt<bool>
44d409305fSDimitry Andric     VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden,
45d409305fSDimitry Andric                       cl::desc("Do pseudo probe verification"));
46d409305fSDimitry Andric 
47d409305fSDimitry Andric static cl::list<std::string> VerifyPseudoProbeFuncList(
48d409305fSDimitry Andric     "verify-pseudo-probe-funcs", cl::Hidden,
49d409305fSDimitry Andric     cl::desc("The option to specify the name of the functions to verify."));
50d409305fSDimitry Andric 
51d409305fSDimitry Andric static cl::opt<bool>
52d409305fSDimitry Andric     UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden,
53d409305fSDimitry Andric                       cl::desc("Update pseudo probe distribution factor"));
54d409305fSDimitry Andric 
55fe6060f1SDimitry Andric static uint64_t getCallStackHash(const DILocation *DIL) {
56fe6060f1SDimitry Andric   uint64_t Hash = 0;
57fe6060f1SDimitry Andric   const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;
58fe6060f1SDimitry Andric   while (InlinedAt) {
59fe6060f1SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getLine()));
60fe6060f1SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn()));
6106c3fb27SDimitry Andric     auto Name = InlinedAt->getSubprogramLinkageName();
62fe6060f1SDimitry Andric     Hash ^= MD5Hash(Name);
63fe6060f1SDimitry Andric     InlinedAt = InlinedAt->getInlinedAt();
64fe6060f1SDimitry Andric   }
65fe6060f1SDimitry Andric   return Hash;
66fe6060f1SDimitry Andric }
67fe6060f1SDimitry Andric 
68fe6060f1SDimitry Andric static uint64_t computeCallStackHash(const Instruction &Inst) {
69fe6060f1SDimitry Andric   return getCallStackHash(Inst.getDebugLoc());
70fe6060f1SDimitry Andric }
71fe6060f1SDimitry Andric 
72d409305fSDimitry Andric bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
73d409305fSDimitry Andric   // Skip function declaration.
74d409305fSDimitry Andric   if (F->isDeclaration())
75d409305fSDimitry Andric     return false;
76d409305fSDimitry Andric   // Skip function that will not be emitted into object file. The prevailing
77d409305fSDimitry Andric   // defintion will be verified instead.
78d409305fSDimitry Andric   if (F->hasAvailableExternallyLinkage())
79d409305fSDimitry Andric     return false;
80d409305fSDimitry Andric   // Do a name matching.
81d409305fSDimitry Andric   static std::unordered_set<std::string> VerifyFuncNames(
82d409305fSDimitry Andric       VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());
83d409305fSDimitry Andric   return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str());
84d409305fSDimitry Andric }
85d409305fSDimitry Andric 
86d409305fSDimitry Andric void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
87d409305fSDimitry Andric   if (VerifyPseudoProbe) {
88d409305fSDimitry Andric     PIC.registerAfterPassCallback(
89d409305fSDimitry Andric         [this](StringRef P, Any IR, const PreservedAnalyses &) {
90d409305fSDimitry Andric           this->runAfterPass(P, IR);
91d409305fSDimitry Andric         });
92d409305fSDimitry Andric   }
93d409305fSDimitry Andric }
94d409305fSDimitry Andric 
95d409305fSDimitry Andric // Callback to run after each transformation for the new pass manager.
96d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {
97d409305fSDimitry Andric   std::string Banner =
98d409305fSDimitry Andric       "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
99d409305fSDimitry Andric   dbgs() << Banner;
1005f757f3fSDimitry Andric   if (const auto **M = llvm::any_cast<const Module *>(&IR))
101bdd1243dSDimitry Andric     runAfterPass(*M);
1025f757f3fSDimitry Andric   else if (const auto **F = llvm::any_cast<const Function *>(&IR))
103bdd1243dSDimitry Andric     runAfterPass(*F);
1045f757f3fSDimitry Andric   else if (const auto **C = llvm::any_cast<const LazyCallGraph::SCC *>(&IR))
105bdd1243dSDimitry Andric     runAfterPass(*C);
1065f757f3fSDimitry Andric   else if (const auto **L = llvm::any_cast<const Loop *>(&IR))
107bdd1243dSDimitry Andric     runAfterPass(*L);
108d409305fSDimitry Andric   else
109d409305fSDimitry Andric     llvm_unreachable("Unknown IR unit");
110d409305fSDimitry Andric }
111d409305fSDimitry Andric 
112d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Module *M) {
113d409305fSDimitry Andric   for (const Function &F : *M)
114d409305fSDimitry Andric     runAfterPass(&F);
115d409305fSDimitry Andric }
116d409305fSDimitry Andric 
117d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {
118d409305fSDimitry Andric   for (const LazyCallGraph::Node &N : *C)
119d409305fSDimitry Andric     runAfterPass(&N.getFunction());
120d409305fSDimitry Andric }
121d409305fSDimitry Andric 
122d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Function *F) {
123d409305fSDimitry Andric   if (!shouldVerifyFunction(F))
124d409305fSDimitry Andric     return;
125d409305fSDimitry Andric   ProbeFactorMap ProbeFactors;
126d409305fSDimitry Andric   for (const auto &BB : *F)
127d409305fSDimitry Andric     collectProbeFactors(&BB, ProbeFactors);
128d409305fSDimitry Andric   verifyProbeFactors(F, ProbeFactors);
129d409305fSDimitry Andric }
130d409305fSDimitry Andric 
131d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Loop *L) {
132d409305fSDimitry Andric   const Function *F = L->getHeader()->getParent();
133d409305fSDimitry Andric   runAfterPass(F);
134d409305fSDimitry Andric }
135d409305fSDimitry Andric 
136d409305fSDimitry Andric void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,
137d409305fSDimitry Andric                                               ProbeFactorMap &ProbeFactors) {
138d409305fSDimitry Andric   for (const auto &I : *Block) {
139bdd1243dSDimitry Andric     if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
140fe6060f1SDimitry Andric       uint64_t Hash = computeCallStackHash(I);
141fe6060f1SDimitry Andric       ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;
142fe6060f1SDimitry Andric     }
143d409305fSDimitry Andric   }
144d409305fSDimitry Andric }
145d409305fSDimitry Andric 
146d409305fSDimitry Andric void PseudoProbeVerifier::verifyProbeFactors(
147d409305fSDimitry Andric     const Function *F, const ProbeFactorMap &ProbeFactors) {
148d409305fSDimitry Andric   bool BannerPrinted = false;
149d409305fSDimitry Andric   auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];
150d409305fSDimitry Andric   for (const auto &I : ProbeFactors) {
151d409305fSDimitry Andric     float CurProbeFactor = I.second;
152d409305fSDimitry Andric     if (PrevProbeFactors.count(I.first)) {
153d409305fSDimitry Andric       float PrevProbeFactor = PrevProbeFactors[I.first];
154d409305fSDimitry Andric       if (std::abs(CurProbeFactor - PrevProbeFactor) >
155d409305fSDimitry Andric           DistributionFactorVariance) {
156d409305fSDimitry Andric         if (!BannerPrinted) {
157d409305fSDimitry Andric           dbgs() << "Function " << F->getName() << ":\n";
158d409305fSDimitry Andric           BannerPrinted = true;
159d409305fSDimitry Andric         }
160fe6060f1SDimitry Andric         dbgs() << "Probe " << I.first.first << "\tprevious factor "
161d409305fSDimitry Andric                << format("%0.2f", PrevProbeFactor) << "\tcurrent factor "
162d409305fSDimitry Andric                << format("%0.2f", CurProbeFactor) << "\n";
163d409305fSDimitry Andric       }
164d409305fSDimitry Andric     }
165d409305fSDimitry Andric 
166d409305fSDimitry Andric     // Update
167d409305fSDimitry Andric     PrevProbeFactors[I.first] = I.second;
168d409305fSDimitry Andric   }
169d409305fSDimitry Andric }
170d409305fSDimitry Andric 
171e8d8bef9SDimitry Andric SampleProfileProber::SampleProfileProber(Function &Func,
172e8d8bef9SDimitry Andric                                          const std::string &CurModuleUniqueId)
173e8d8bef9SDimitry Andric     : F(&Func), CurModuleUniqueId(CurModuleUniqueId) {
174e8d8bef9SDimitry Andric   BlockProbeIds.clear();
175e8d8bef9SDimitry Andric   CallProbeIds.clear();
176e8d8bef9SDimitry Andric   LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
177*0fca6ea1SDimitry Andric 
178*0fca6ea1SDimitry Andric   DenseSet<BasicBlock *> BlocksToIgnore;
179*0fca6ea1SDimitry Andric   DenseSet<BasicBlock *> BlocksAndCallsToIgnore;
180*0fca6ea1SDimitry Andric   computeBlocksToIgnore(BlocksToIgnore, BlocksAndCallsToIgnore);
181*0fca6ea1SDimitry Andric 
182*0fca6ea1SDimitry Andric   computeProbeId(BlocksToIgnore, BlocksAndCallsToIgnore);
183*0fca6ea1SDimitry Andric   computeCFGHash(BlocksToIgnore);
184*0fca6ea1SDimitry Andric }
185*0fca6ea1SDimitry Andric 
186*0fca6ea1SDimitry Andric // Two purposes to compute the blocks to ignore:
187*0fca6ea1SDimitry Andric // 1. Reduce the IR size.
188*0fca6ea1SDimitry Andric // 2. Make the instrumentation(checksum) stable. e.g. the frondend may
189*0fca6ea1SDimitry Andric // generate unstable IR while optimizing nounwind attribute, some versions are
190*0fca6ea1SDimitry Andric // optimized with the call-to-invoke conversion, while other versions do not.
191*0fca6ea1SDimitry Andric // This discrepancy in probe ID could cause profile mismatching issues.
192*0fca6ea1SDimitry Andric // Note that those ignored blocks are either cold blocks or new split blocks
193*0fca6ea1SDimitry Andric // whose original blocks are instrumented, so it shouldn't degrade the profile
194*0fca6ea1SDimitry Andric // quality.
195*0fca6ea1SDimitry Andric void SampleProfileProber::computeBlocksToIgnore(
196*0fca6ea1SDimitry Andric     DenseSet<BasicBlock *> &BlocksToIgnore,
197*0fca6ea1SDimitry Andric     DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
198*0fca6ea1SDimitry Andric   // Ignore the cold EH and unreachable blocks and calls.
199*0fca6ea1SDimitry Andric   computeEHOnlyBlocks(*F, BlocksAndCallsToIgnore);
200*0fca6ea1SDimitry Andric   findUnreachableBlocks(BlocksAndCallsToIgnore);
201*0fca6ea1SDimitry Andric 
202*0fca6ea1SDimitry Andric   BlocksToIgnore.insert(BlocksAndCallsToIgnore.begin(),
203*0fca6ea1SDimitry Andric                         BlocksAndCallsToIgnore.end());
204*0fca6ea1SDimitry Andric 
205*0fca6ea1SDimitry Andric   // Handle the call-to-invoke conversion case: make sure that the probe id and
206*0fca6ea1SDimitry Andric   // callsite id are consistent before and after the block split. For block
207*0fca6ea1SDimitry Andric   // probe, we only keep the head block probe id and ignore the block ids of the
208*0fca6ea1SDimitry Andric   // normal dests. For callsite probe, it's different to block probe, there is
209*0fca6ea1SDimitry Andric   // no additional callsite in the normal dests, so we don't ignore the
210*0fca6ea1SDimitry Andric   // callsites.
211*0fca6ea1SDimitry Andric   findInvokeNormalDests(BlocksToIgnore);
212*0fca6ea1SDimitry Andric }
213*0fca6ea1SDimitry Andric 
214*0fca6ea1SDimitry Andric // Unreachable blocks and calls are always cold, ignore them.
215*0fca6ea1SDimitry Andric void SampleProfileProber::findUnreachableBlocks(
216*0fca6ea1SDimitry Andric     DenseSet<BasicBlock *> &BlocksToIgnore) {
217*0fca6ea1SDimitry Andric   for (auto &BB : *F) {
218*0fca6ea1SDimitry Andric     if (&BB != &F->getEntryBlock() && pred_size(&BB) == 0)
219*0fca6ea1SDimitry Andric       BlocksToIgnore.insert(&BB);
220*0fca6ea1SDimitry Andric   }
221*0fca6ea1SDimitry Andric }
222*0fca6ea1SDimitry Andric 
223*0fca6ea1SDimitry Andric // In call-to-invoke conversion, basic block can be split into multiple blocks,
224*0fca6ea1SDimitry Andric // only instrument probe in the head block, ignore the normal dests.
225*0fca6ea1SDimitry Andric void SampleProfileProber::findInvokeNormalDests(
226*0fca6ea1SDimitry Andric     DenseSet<BasicBlock *> &InvokeNormalDests) {
227*0fca6ea1SDimitry Andric   for (auto &BB : *F) {
228*0fca6ea1SDimitry Andric     auto *TI = BB.getTerminator();
229*0fca6ea1SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
230*0fca6ea1SDimitry Andric       auto *ND = II->getNormalDest();
231*0fca6ea1SDimitry Andric       InvokeNormalDests.insert(ND);
232*0fca6ea1SDimitry Andric 
233*0fca6ea1SDimitry Andric       // The normal dest and the try/catch block are connected by an
234*0fca6ea1SDimitry Andric       // unconditional branch.
235*0fca6ea1SDimitry Andric       while (pred_size(ND) == 1) {
236*0fca6ea1SDimitry Andric         auto *Pred = *pred_begin(ND);
237*0fca6ea1SDimitry Andric         if (succ_size(Pred) == 1) {
238*0fca6ea1SDimitry Andric           InvokeNormalDests.insert(Pred);
239*0fca6ea1SDimitry Andric           ND = Pred;
240*0fca6ea1SDimitry Andric         } else
241*0fca6ea1SDimitry Andric           break;
242*0fca6ea1SDimitry Andric       }
243*0fca6ea1SDimitry Andric     }
244*0fca6ea1SDimitry Andric   }
245*0fca6ea1SDimitry Andric }
246*0fca6ea1SDimitry Andric 
247*0fca6ea1SDimitry Andric // The call-to-invoke conversion splits the original block into a list of block,
248*0fca6ea1SDimitry Andric // we need to compute the hash using the original block's successors to keep the
249*0fca6ea1SDimitry Andric // CFG Hash consistent. For a given head block, we keep searching the
250*0fca6ea1SDimitry Andric // succesor(normal dest or unconditional branch dest) to find the tail block,
251*0fca6ea1SDimitry Andric // the tail block's successors are the original block's successors.
252*0fca6ea1SDimitry Andric const Instruction *SampleProfileProber::getOriginalTerminator(
253*0fca6ea1SDimitry Andric     const BasicBlock *Head, const DenseSet<BasicBlock *> &BlocksToIgnore) {
254*0fca6ea1SDimitry Andric   auto *TI = Head->getTerminator();
255*0fca6ea1SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI)) {
256*0fca6ea1SDimitry Andric     return getOriginalTerminator(II->getNormalDest(), BlocksToIgnore);
257*0fca6ea1SDimitry Andric   } else if (succ_size(Head) == 1 &&
258*0fca6ea1SDimitry Andric              BlocksToIgnore.contains(*succ_begin(Head))) {
259*0fca6ea1SDimitry Andric     // Go to the unconditional branch dest.
260*0fca6ea1SDimitry Andric     return getOriginalTerminator(*succ_begin(Head), BlocksToIgnore);
261*0fca6ea1SDimitry Andric   }
262*0fca6ea1SDimitry Andric   return TI;
263e8d8bef9SDimitry Andric }
264e8d8bef9SDimitry Andric 
265e8d8bef9SDimitry Andric // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
266e8d8bef9SDimitry Andric // value of each BB in the CFG. The higher 32 bits record the number of edges
267e8d8bef9SDimitry Andric // preceded by the number of indirect calls.
268e8d8bef9SDimitry Andric // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().
269*0fca6ea1SDimitry Andric void SampleProfileProber::computeCFGHash(
270*0fca6ea1SDimitry Andric     const DenseSet<BasicBlock *> &BlocksToIgnore) {
271e8d8bef9SDimitry Andric   std::vector<uint8_t> Indexes;
272e8d8bef9SDimitry Andric   JamCRC JC;
273e8d8bef9SDimitry Andric   for (auto &BB : *F) {
274*0fca6ea1SDimitry Andric     if (BlocksToIgnore.contains(&BB))
275*0fca6ea1SDimitry Andric       continue;
276*0fca6ea1SDimitry Andric 
277*0fca6ea1SDimitry Andric     auto *TI = getOriginalTerminator(&BB, BlocksToIgnore);
278*0fca6ea1SDimitry Andric     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
279*0fca6ea1SDimitry Andric       auto *Succ = TI->getSuccessor(I);
280e8d8bef9SDimitry Andric       auto Index = getBlockId(Succ);
281*0fca6ea1SDimitry Andric       // Ingore ignored-block(zero ID) to avoid unstable checksum.
282*0fca6ea1SDimitry Andric       if (Index == 0)
283*0fca6ea1SDimitry Andric         continue;
284e8d8bef9SDimitry Andric       for (int J = 0; J < 4; J++)
285e8d8bef9SDimitry Andric         Indexes.push_back((uint8_t)(Index >> (J * 8)));
286e8d8bef9SDimitry Andric     }
287e8d8bef9SDimitry Andric   }
288e8d8bef9SDimitry Andric 
289e8d8bef9SDimitry Andric   JC.update(Indexes);
290e8d8bef9SDimitry Andric 
291e8d8bef9SDimitry Andric   FunctionHash = (uint64_t)CallProbeIds.size() << 48 |
292e8d8bef9SDimitry Andric                  (uint64_t)Indexes.size() << 32 | JC.getCRC();
293e8d8bef9SDimitry Andric   // Reserve bit 60-63 for other information purpose.
294e8d8bef9SDimitry Andric   FunctionHash &= 0x0FFFFFFFFFFFFFFF;
295e8d8bef9SDimitry Andric   assert(FunctionHash && "Function checksum should not be zero");
296e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()
297e8d8bef9SDimitry Andric                     << ":\n"
298e8d8bef9SDimitry Andric                     << " CRC = " << JC.getCRC() << ", Edges = "
299e8d8bef9SDimitry Andric                     << Indexes.size() << ", ICSites = " << CallProbeIds.size()
300e8d8bef9SDimitry Andric                     << ", Hash = " << FunctionHash << "\n");
301e8d8bef9SDimitry Andric }
302e8d8bef9SDimitry Andric 
303*0fca6ea1SDimitry Andric void SampleProfileProber::computeProbeId(
304*0fca6ea1SDimitry Andric     const DenseSet<BasicBlock *> &BlocksToIgnore,
305*0fca6ea1SDimitry Andric     const DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
3065f757f3fSDimitry Andric   LLVMContext &Ctx = F->getContext();
3075f757f3fSDimitry Andric   Module *M = F->getParent();
3085f757f3fSDimitry Andric 
309e8d8bef9SDimitry Andric   for (auto &BB : *F) {
310*0fca6ea1SDimitry Andric     if (!BlocksToIgnore.contains(&BB))
311*0fca6ea1SDimitry Andric       BlockProbeIds[&BB] = ++LastProbeId;
312*0fca6ea1SDimitry Andric 
313*0fca6ea1SDimitry Andric     if (BlocksAndCallsToIgnore.contains(&BB))
314e8d8bef9SDimitry Andric       continue;
315*0fca6ea1SDimitry Andric     for (auto &I : BB) {
316*0fca6ea1SDimitry Andric       if (!isa<CallBase>(I) || isa<IntrinsicInst>(&I))
317e8d8bef9SDimitry Andric         continue;
3185f757f3fSDimitry Andric 
3195f757f3fSDimitry Andric       // The current implementation uses the lower 16 bits of the discriminator
3205f757f3fSDimitry Andric       // so anything larger than 0xFFFF will be ignored.
3215f757f3fSDimitry Andric       if (LastProbeId >= 0xFFFF) {
3225f757f3fSDimitry Andric         std::string Msg = "Pseudo instrumentation incomplete for " +
3235f757f3fSDimitry Andric                           std::string(F->getName()) + " because it's too large";
3245f757f3fSDimitry Andric         Ctx.diagnose(
3255f757f3fSDimitry Andric             DiagnosticInfoSampleProfile(M->getName().data(), Msg, DS_Warning));
3265f757f3fSDimitry Andric         return;
3275f757f3fSDimitry Andric       }
3285f757f3fSDimitry Andric 
329e8d8bef9SDimitry Andric       CallProbeIds[&I] = ++LastProbeId;
330e8d8bef9SDimitry Andric     }
331e8d8bef9SDimitry Andric   }
332e8d8bef9SDimitry Andric }
333e8d8bef9SDimitry Andric 
334e8d8bef9SDimitry Andric uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {
335e8d8bef9SDimitry Andric   auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB));
336e8d8bef9SDimitry Andric   return I == BlockProbeIds.end() ? 0 : I->second;
337e8d8bef9SDimitry Andric }
338e8d8bef9SDimitry Andric 
339e8d8bef9SDimitry Andric uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {
340e8d8bef9SDimitry Andric   auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call));
341e8d8bef9SDimitry Andric   return Iter == CallProbeIds.end() ? 0 : Iter->second;
342e8d8bef9SDimitry Andric }
343e8d8bef9SDimitry Andric 
344e8d8bef9SDimitry Andric void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {
345e8d8bef9SDimitry Andric   Module *M = F.getParent();
346e8d8bef9SDimitry Andric   MDBuilder MDB(F.getContext());
347*0fca6ea1SDimitry Andric   // Since the GUID from probe desc and inline stack are computed separately, we
34806c3fb27SDimitry Andric   // need to make sure their names are consistent, so here also use the name
34906c3fb27SDimitry Andric   // from debug info.
35006c3fb27SDimitry Andric   StringRef FName = F.getName();
35106c3fb27SDimitry Andric   if (auto *SP = F.getSubprogram()) {
35206c3fb27SDimitry Andric     FName = SP->getLinkageName();
35306c3fb27SDimitry Andric     if (FName.empty())
35406c3fb27SDimitry Andric       FName = SP->getName();
35506c3fb27SDimitry Andric   }
35606c3fb27SDimitry Andric   uint64_t Guid = Function::getGUID(FName);
357e8d8bef9SDimitry Andric 
358e8d8bef9SDimitry Andric   // Assign an artificial debug line to a probe that doesn't come with a real
359e8d8bef9SDimitry Andric   // line. A probe not having a debug line will get an incomplete inline
360e8d8bef9SDimitry Andric   // context. This will cause samples collected on the probe to be counted
361e8d8bef9SDimitry Andric   // into the base profile instead of a context profile. The line number
362e8d8bef9SDimitry Andric   // itself is not important though.
363e8d8bef9SDimitry Andric   auto AssignDebugLoc = [&](Instruction *I) {
364e8d8bef9SDimitry Andric     assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&
365e8d8bef9SDimitry Andric            "Expecting pseudo probe or call instructions");
366e8d8bef9SDimitry Andric     if (!I->getDebugLoc()) {
367e8d8bef9SDimitry Andric       if (auto *SP = F.getSubprogram()) {
368e8d8bef9SDimitry Andric         auto DIL = DILocation::get(SP->getContext(), 0, 0, SP);
369e8d8bef9SDimitry Andric         I->setDebugLoc(DIL);
370e8d8bef9SDimitry Andric         ArtificialDbgLine++;
371e8d8bef9SDimitry Andric         LLVM_DEBUG({
372e8d8bef9SDimitry Andric           dbgs() << "\nIn Function " << F.getName()
373e8d8bef9SDimitry Andric                  << " Probe gets an artificial debug line\n";
374e8d8bef9SDimitry Andric           I->dump();
375e8d8bef9SDimitry Andric         });
376e8d8bef9SDimitry Andric       }
377e8d8bef9SDimitry Andric     }
378e8d8bef9SDimitry Andric   };
379e8d8bef9SDimitry Andric 
380e8d8bef9SDimitry Andric   // Probe basic blocks.
381e8d8bef9SDimitry Andric   for (auto &I : BlockProbeIds) {
382e8d8bef9SDimitry Andric     BasicBlock *BB = I.first;
383e8d8bef9SDimitry Andric     uint32_t Index = I.second;
384e8d8bef9SDimitry Andric     // Insert a probe before an instruction with a valid debug line number which
385e8d8bef9SDimitry Andric     // will be assigned to the probe. The line number will be used later to
386e8d8bef9SDimitry Andric     // model the inline context when the probe is inlined into other functions.
387e8d8bef9SDimitry Andric     // Debug instructions, phi nodes and lifetime markers do not have an valid
388e8d8bef9SDimitry Andric     // line number. Real instructions generated by optimizations may not come
389e8d8bef9SDimitry Andric     // with a line number either.
390e8d8bef9SDimitry Andric     auto HasValidDbgLine = [](Instruction *J) {
391e8d8bef9SDimitry Andric       return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) &&
392e8d8bef9SDimitry Andric              !J->isLifetimeStartOrEnd() && J->getDebugLoc();
393e8d8bef9SDimitry Andric     };
394e8d8bef9SDimitry Andric 
395e8d8bef9SDimitry Andric     Instruction *J = &*BB->getFirstInsertionPt();
396e8d8bef9SDimitry Andric     while (J != BB->getTerminator() && !HasValidDbgLine(J)) {
397e8d8bef9SDimitry Andric       J = J->getNextNode();
398e8d8bef9SDimitry Andric     }
399e8d8bef9SDimitry Andric 
400e8d8bef9SDimitry Andric     IRBuilder<> Builder(J);
401e8d8bef9SDimitry Andric     assert(Builder.GetInsertPoint() != BB->end() &&
402e8d8bef9SDimitry Andric            "Cannot get the probing point");
403e8d8bef9SDimitry Andric     Function *ProbeFn =
404e8d8bef9SDimitry Andric         llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe);
405e8d8bef9SDimitry Andric     Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index),
406d409305fSDimitry Andric                      Builder.getInt32(0),
407d409305fSDimitry Andric                      Builder.getInt64(PseudoProbeFullDistributionFactor)};
408e8d8bef9SDimitry Andric     auto *Probe = Builder.CreateCall(ProbeFn, Args);
409e8d8bef9SDimitry Andric     AssignDebugLoc(Probe);
41006c3fb27SDimitry Andric     // Reset the dwarf discriminator if the debug location comes with any. The
41106c3fb27SDimitry Andric     // discriminator field may be used by FS-AFDO later in the pipeline.
41206c3fb27SDimitry Andric     if (auto DIL = Probe->getDebugLoc()) {
41306c3fb27SDimitry Andric       if (DIL->getDiscriminator()) {
41406c3fb27SDimitry Andric         DIL = DIL->cloneWithDiscriminator(0);
41506c3fb27SDimitry Andric         Probe->setDebugLoc(DIL);
41606c3fb27SDimitry Andric       }
41706c3fb27SDimitry Andric     }
418e8d8bef9SDimitry Andric   }
419e8d8bef9SDimitry Andric 
420e8d8bef9SDimitry Andric   // Probe both direct calls and indirect calls. Direct calls are probed so that
421e8d8bef9SDimitry Andric   // their probe ID can be used as an call site identifier to represent a
422e8d8bef9SDimitry Andric   // calling context.
423e8d8bef9SDimitry Andric   for (auto &I : CallProbeIds) {
424e8d8bef9SDimitry Andric     auto *Call = I.first;
425e8d8bef9SDimitry Andric     uint32_t Index = I.second;
426e8d8bef9SDimitry Andric     uint32_t Type = cast<CallBase>(Call)->getCalledFunction()
427e8d8bef9SDimitry Andric                         ? (uint32_t)PseudoProbeType::DirectCall
428e8d8bef9SDimitry Andric                         : (uint32_t)PseudoProbeType::IndirectCall;
429e8d8bef9SDimitry Andric     AssignDebugLoc(Call);
430e8d8bef9SDimitry Andric     if (auto DIL = Call->getDebugLoc()) {
43106c3fb27SDimitry Andric       // Levarge the 32-bit discriminator field of debug data to store the ID
43206c3fb27SDimitry Andric       // and type of a callsite probe. This gets rid of the dependency on
43306c3fb27SDimitry Andric       // plumbing a customized metadata through the codegen pipeline.
43406c3fb27SDimitry Andric       uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(
435*0fca6ea1SDimitry Andric           Index, Type, 0, PseudoProbeDwarfDiscriminator::FullDistributionFactor,
436*0fca6ea1SDimitry Andric           DIL->getBaseDiscriminator());
437e8d8bef9SDimitry Andric       DIL = DIL->cloneWithDiscriminator(V);
438e8d8bef9SDimitry Andric       Call->setDebugLoc(DIL);
439e8d8bef9SDimitry Andric     }
440e8d8bef9SDimitry Andric   }
441e8d8bef9SDimitry Andric 
442e8d8bef9SDimitry Andric   // Create module-level metadata that contains function info necessary to
443e8d8bef9SDimitry Andric   // synthesize probe-based sample counts,  which are
444e8d8bef9SDimitry Andric   // - FunctionGUID
445e8d8bef9SDimitry Andric   // - FunctionHash.
446e8d8bef9SDimitry Andric   // - FunctionName
447e8d8bef9SDimitry Andric   auto Hash = getFunctionHash();
44806c3fb27SDimitry Andric   auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, FName);
449e8d8bef9SDimitry Andric   auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName);
450e8d8bef9SDimitry Andric   assert(NMD && "llvm.pseudo_probe_desc should be pre-created");
451e8d8bef9SDimitry Andric   NMD->addOperand(MD);
452e8d8bef9SDimitry Andric }
453e8d8bef9SDimitry Andric 
454e8d8bef9SDimitry Andric PreservedAnalyses SampleProfileProbePass::run(Module &M,
455e8d8bef9SDimitry Andric                                               ModuleAnalysisManager &AM) {
456e8d8bef9SDimitry Andric   auto ModuleId = getUniqueModuleId(&M);
457e8d8bef9SDimitry Andric   // Create the pseudo probe desc metadata beforehand.
458e8d8bef9SDimitry Andric   // Note that modules with only data but no functions will require this to
459e8d8bef9SDimitry Andric   // be set up so that they will be known as probed later.
460e8d8bef9SDimitry Andric   M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName);
461e8d8bef9SDimitry Andric 
462e8d8bef9SDimitry Andric   for (auto &F : M) {
463e8d8bef9SDimitry Andric     if (F.isDeclaration())
464e8d8bef9SDimitry Andric       continue;
465e8d8bef9SDimitry Andric     SampleProfileProber ProbeManager(F, ModuleId);
466e8d8bef9SDimitry Andric     ProbeManager.instrumentOneFunc(F, TM);
467e8d8bef9SDimitry Andric   }
468e8d8bef9SDimitry Andric 
469e8d8bef9SDimitry Andric   return PreservedAnalyses::none();
470e8d8bef9SDimitry Andric }
471d409305fSDimitry Andric 
472d409305fSDimitry Andric void PseudoProbeUpdatePass::runOnFunction(Function &F,
473d409305fSDimitry Andric                                           FunctionAnalysisManager &FAM) {
474d409305fSDimitry Andric   BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
475d409305fSDimitry Andric   auto BBProfileCount = [&BFI](BasicBlock *BB) {
47681ad6265SDimitry Andric     return BFI.getBlockProfileCount(BB).value_or(0);
477d409305fSDimitry Andric   };
478d409305fSDimitry Andric 
479d409305fSDimitry Andric   // Collect the sum of execution weight for each probe.
480d409305fSDimitry Andric   ProbeFactorMap ProbeFactors;
481d409305fSDimitry Andric   for (auto &Block : F) {
482d409305fSDimitry Andric     for (auto &I : Block) {
483bdd1243dSDimitry Andric       if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
484fe6060f1SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
485fe6060f1SDimitry Andric         ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);
486fe6060f1SDimitry Andric       }
487d409305fSDimitry Andric     }
488d409305fSDimitry Andric   }
489d409305fSDimitry Andric 
490d409305fSDimitry Andric   // Fix up over-counted probes.
491d409305fSDimitry Andric   for (auto &Block : F) {
492d409305fSDimitry Andric     for (auto &I : Block) {
493bdd1243dSDimitry Andric       if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
494fe6060f1SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
495fe6060f1SDimitry Andric         float Sum = ProbeFactors[{Probe->Id, Hash}];
496d409305fSDimitry Andric         if (Sum != 0)
497d409305fSDimitry Andric           setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum);
498d409305fSDimitry Andric       }
499d409305fSDimitry Andric     }
500d409305fSDimitry Andric   }
501d409305fSDimitry Andric }
502d409305fSDimitry Andric 
503d409305fSDimitry Andric PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,
504d409305fSDimitry Andric                                              ModuleAnalysisManager &AM) {
505d409305fSDimitry Andric   if (UpdatePseudoProbe) {
506d409305fSDimitry Andric     for (auto &F : M) {
507d409305fSDimitry Andric       if (F.isDeclaration())
508d409305fSDimitry Andric         continue;
509d409305fSDimitry Andric       FunctionAnalysisManager &FAM =
510d409305fSDimitry Andric           AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
511d409305fSDimitry Andric       runOnFunction(F, FAM);
512d409305fSDimitry Andric     }
513d409305fSDimitry Andric   }
514d409305fSDimitry Andric   return PreservedAnalyses::none();
515d409305fSDimitry Andric }
516