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