1344a3780SDimitry Andric //===- Debugify.cpp - Check debug info preservation in optimizations ------===//
2044eb2f6SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6044eb2f6SDimitry Andric //
7044eb2f6SDimitry Andric //===----------------------------------------------------------------------===//
8044eb2f6SDimitry Andric ///
9344a3780SDimitry Andric /// \file In the `synthetic` mode, the `-debugify` attaches synthetic debug info
10344a3780SDimitry Andric /// to everything. It can be used to create targeted tests for debug info
11344a3780SDimitry Andric /// preservation. In addition, when using the `original` mode, it can check
12344a3780SDimitry Andric /// original debug info preservation. The `synthetic` mode is default one.
13044eb2f6SDimitry Andric ///
14044eb2f6SDimitry Andric //===----------------------------------------------------------------------===//
15044eb2f6SDimitry Andric
16706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/Debugify.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/BitVector.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/StringExtras.h"
19044eb2f6SDimitry Andric #include "llvm/IR/DIBuilder.h"
20044eb2f6SDimitry Andric #include "llvm/IR/DebugInfo.h"
21044eb2f6SDimitry Andric #include "llvm/IR/InstIterator.h"
22044eb2f6SDimitry Andric #include "llvm/IR/Instructions.h"
23044eb2f6SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
24044eb2f6SDimitry Andric #include "llvm/IR/Module.h"
25b60736ecSDimitry Andric #include "llvm/IR/PassInstrumentation.h"
26044eb2f6SDimitry Andric #include "llvm/Pass.h"
27706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
28344a3780SDimitry Andric #include "llvm/Support/FileSystem.h"
29344a3780SDimitry Andric #include "llvm/Support/JSON.h"
30e3b55780SDimitry Andric #include <optional>
31344a3780SDimitry Andric
32344a3780SDimitry Andric #define DEBUG_TYPE "debugify"
33044eb2f6SDimitry Andric
34044eb2f6SDimitry Andric using namespace llvm;
35044eb2f6SDimitry Andric
36044eb2f6SDimitry Andric namespace {
37044eb2f6SDimitry Andric
38eb11fae6SDimitry Andric cl::opt<bool> Quiet("debugify-quiet",
39eb11fae6SDimitry Andric cl::desc("Suppress verbose debugify output"));
40eb11fae6SDimitry Andric
41145449b1SDimitry Andric cl::opt<uint64_t> DebugifyFunctionsLimit(
42145449b1SDimitry Andric "debugify-func-limit",
43145449b1SDimitry Andric cl::desc("Set max number of processed functions per pass."),
44145449b1SDimitry Andric cl::init(UINT_MAX));
45145449b1SDimitry Andric
46cfca06d7SDimitry Andric enum class Level {
47cfca06d7SDimitry Andric Locations,
48cfca06d7SDimitry Andric LocationsAndVariables
49cfca06d7SDimitry Andric };
50344a3780SDimitry Andric
51cfca06d7SDimitry Andric cl::opt<Level> DebugifyLevel(
52cfca06d7SDimitry Andric "debugify-level", cl::desc("Kind of debug info to add"),
53cfca06d7SDimitry Andric cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
54cfca06d7SDimitry Andric clEnumValN(Level::LocationsAndVariables, "location+variables",
55cfca06d7SDimitry Andric "Locations and Variables")),
56cfca06d7SDimitry Andric cl::init(Level::LocationsAndVariables));
57cfca06d7SDimitry Andric
dbg()58eb11fae6SDimitry Andric raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
59eb11fae6SDimitry Andric
getAllocSizeInBits(Module & M,Type * Ty)60eb11fae6SDimitry Andric uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
61eb11fae6SDimitry Andric return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
62eb11fae6SDimitry Andric }
63eb11fae6SDimitry Andric
isFunctionSkipped(Function & F)64eb11fae6SDimitry Andric bool isFunctionSkipped(Function &F) {
65eb11fae6SDimitry Andric return F.isDeclaration() || !F.hasExactDefinition();
66eb11fae6SDimitry Andric }
67eb11fae6SDimitry Andric
68eb11fae6SDimitry Andric /// Find the basic block's terminating instruction.
69eb11fae6SDimitry Andric ///
70eb11fae6SDimitry Andric /// Special care is needed to handle musttail and deopt calls, as these behave
71eb11fae6SDimitry Andric /// like (but are in fact not) terminators.
findTerminatingInstruction(BasicBlock & BB)72eb11fae6SDimitry Andric Instruction *findTerminatingInstruction(BasicBlock &BB) {
73eb11fae6SDimitry Andric if (auto *I = BB.getTerminatingMustTailCall())
74eb11fae6SDimitry Andric return I;
75eb11fae6SDimitry Andric if (auto *I = BB.getTerminatingDeoptimizeCall())
76eb11fae6SDimitry Andric return I;
77eb11fae6SDimitry Andric return BB.getTerminator();
78eb11fae6SDimitry Andric }
79cfca06d7SDimitry Andric } // end anonymous namespace
80eb11fae6SDimitry Andric
applyDebugifyMetadata(Module & M,iterator_range<Module::iterator> Functions,StringRef Banner,std::function<bool (DIBuilder & DIB,Function & F)> ApplyToMF)81cfca06d7SDimitry Andric bool llvm::applyDebugifyMetadata(
82cfca06d7SDimitry Andric Module &M, iterator_range<Module::iterator> Functions, StringRef Banner,
83cfca06d7SDimitry Andric std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
84044eb2f6SDimitry Andric // Skip modules with debug info.
85044eb2f6SDimitry Andric if (M.getNamedMetadata("llvm.dbg.cu")) {
86eb11fae6SDimitry Andric dbg() << Banner << "Skipping module with debug info\n";
87044eb2f6SDimitry Andric return false;
88044eb2f6SDimitry Andric }
89044eb2f6SDimitry Andric
90044eb2f6SDimitry Andric DIBuilder DIB(M);
91044eb2f6SDimitry Andric LLVMContext &Ctx = M.getContext();
92cfca06d7SDimitry Andric auto *Int32Ty = Type::getInt32Ty(Ctx);
93044eb2f6SDimitry Andric
94044eb2f6SDimitry Andric // Get a DIType which corresponds to Ty.
95044eb2f6SDimitry Andric DenseMap<uint64_t, DIType *> TypeCache;
96044eb2f6SDimitry Andric auto getCachedDIType = [&](Type *Ty) -> DIType * {
97eb11fae6SDimitry Andric uint64_t Size = getAllocSizeInBits(M, Ty);
98044eb2f6SDimitry Andric DIType *&DTy = TypeCache[Size];
99044eb2f6SDimitry Andric if (!DTy) {
100044eb2f6SDimitry Andric std::string Name = "ty" + utostr(Size);
101044eb2f6SDimitry Andric DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
102044eb2f6SDimitry Andric }
103044eb2f6SDimitry Andric return DTy;
104044eb2f6SDimitry Andric };
105044eb2f6SDimitry Andric
106044eb2f6SDimitry Andric unsigned NextLine = 1;
107044eb2f6SDimitry Andric unsigned NextVar = 1;
108044eb2f6SDimitry Andric auto File = DIB.createFile(M.getName(), "/");
109eb11fae6SDimitry Andric auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
110eb11fae6SDimitry Andric /*isOptimized=*/true, "", 0);
111044eb2f6SDimitry Andric
112044eb2f6SDimitry Andric // Visit each instruction.
113eb11fae6SDimitry Andric for (Function &F : Functions) {
114eb11fae6SDimitry Andric if (isFunctionSkipped(F))
115044eb2f6SDimitry Andric continue;
116044eb2f6SDimitry Andric
117cfca06d7SDimitry Andric bool InsertedDbgVal = false;
118e3b55780SDimitry Andric auto SPType =
119e3b55780SDimitry Andric DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
120d8e91e46SDimitry Andric DISubprogram::DISPFlags SPFlags =
121d8e91e46SDimitry Andric DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
122d8e91e46SDimitry Andric if (F.hasPrivateLinkage() || F.hasInternalLinkage())
123d8e91e46SDimitry Andric SPFlags |= DISubprogram::SPFlagLocalToUnit;
124d8e91e46SDimitry Andric auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
125d8e91e46SDimitry Andric SPType, NextLine, DINode::FlagZero, SPFlags);
126044eb2f6SDimitry Andric F.setSubprogram(SP);
127cfca06d7SDimitry Andric
128cfca06d7SDimitry Andric // Helper that inserts a dbg.value before \p InsertBefore, copying the
129cfca06d7SDimitry Andric // location (and possibly the type, if it's non-void) from \p TemplateInst.
130cfca06d7SDimitry Andric auto insertDbgVal = [&](Instruction &TemplateInst,
131cfca06d7SDimitry Andric Instruction *InsertBefore) {
132cfca06d7SDimitry Andric std::string Name = utostr(NextVar++);
133cfca06d7SDimitry Andric Value *V = &TemplateInst;
134cfca06d7SDimitry Andric if (TemplateInst.getType()->isVoidTy())
135cfca06d7SDimitry Andric V = ConstantInt::get(Int32Ty, 0);
136cfca06d7SDimitry Andric const DILocation *Loc = TemplateInst.getDebugLoc().get();
137cfca06d7SDimitry Andric auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
138cfca06d7SDimitry Andric getCachedDIType(V->getType()),
139cfca06d7SDimitry Andric /*AlwaysPreserve=*/true);
140cfca06d7SDimitry Andric DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
141cfca06d7SDimitry Andric InsertBefore);
142cfca06d7SDimitry Andric };
143cfca06d7SDimitry Andric
144044eb2f6SDimitry Andric for (BasicBlock &BB : F) {
145044eb2f6SDimitry Andric // Attach debug locations.
146044eb2f6SDimitry Andric for (Instruction &I : BB)
147044eb2f6SDimitry Andric I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
148044eb2f6SDimitry Andric
149cfca06d7SDimitry Andric if (DebugifyLevel < Level::LocationsAndVariables)
150cfca06d7SDimitry Andric continue;
151cfca06d7SDimitry Andric
152eb11fae6SDimitry Andric // Inserting debug values into EH pads can break IR invariants.
153eb11fae6SDimitry Andric if (BB.isEHPad())
154044eb2f6SDimitry Andric continue;
155044eb2f6SDimitry Andric
156eb11fae6SDimitry Andric // Find the terminating instruction, after which no debug values are
157eb11fae6SDimitry Andric // attached.
158eb11fae6SDimitry Andric Instruction *LastInst = findTerminatingInstruction(BB);
159eb11fae6SDimitry Andric assert(LastInst && "Expected basic block with a terminator");
160eb11fae6SDimitry Andric
161eb11fae6SDimitry Andric // Maintain an insertion point which can't be invalidated when updates
162eb11fae6SDimitry Andric // are made.
163eb11fae6SDimitry Andric BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
164eb11fae6SDimitry Andric assert(InsertPt != BB.end() && "Expected to find an insertion point");
165eb11fae6SDimitry Andric Instruction *InsertBefore = &*InsertPt;
166eb11fae6SDimitry Andric
167eb11fae6SDimitry Andric // Attach debug values.
168eb11fae6SDimitry Andric for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
169eb11fae6SDimitry Andric // Skip void-valued instructions.
170eb11fae6SDimitry Andric if (I->getType()->isVoidTy())
171eb11fae6SDimitry Andric continue;
172eb11fae6SDimitry Andric
173eb11fae6SDimitry Andric // Phis and EH pads must be grouped at the beginning of the block.
174eb11fae6SDimitry Andric // Only advance the insertion point when we finish visiting these.
175eb11fae6SDimitry Andric if (!isa<PHINode>(I) && !I->isEHPad())
176eb11fae6SDimitry Andric InsertBefore = I->getNextNode();
177044eb2f6SDimitry Andric
178cfca06d7SDimitry Andric insertDbgVal(*I, InsertBefore);
179cfca06d7SDimitry Andric InsertedDbgVal = true;
180044eb2f6SDimitry Andric }
181044eb2f6SDimitry Andric }
182cfca06d7SDimitry Andric // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
183cfca06d7SDimitry Andric // not have anything to work with as it goes about inserting DBG_VALUEs.
184cfca06d7SDimitry Andric // (It's common for MIR tests to be written containing skeletal IR with
185cfca06d7SDimitry Andric // empty functions -- we're still interested in debugifying the MIR within
186cfca06d7SDimitry Andric // those tests, and this helps with that.)
187cfca06d7SDimitry Andric if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
188cfca06d7SDimitry Andric auto *Term = findTerminatingInstruction(F.getEntryBlock());
189cfca06d7SDimitry Andric insertDbgVal(*Term, Term);
190cfca06d7SDimitry Andric }
191cfca06d7SDimitry Andric if (ApplyToMF)
192cfca06d7SDimitry Andric ApplyToMF(DIB, F);
193044eb2f6SDimitry Andric DIB.finalizeSubprogram(SP);
194044eb2f6SDimitry Andric }
195044eb2f6SDimitry Andric DIB.finalize();
196044eb2f6SDimitry Andric
197044eb2f6SDimitry Andric // Track the number of distinct lines and variables.
198044eb2f6SDimitry Andric NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
199044eb2f6SDimitry Andric auto addDebugifyOperand = [&](unsigned N) {
200044eb2f6SDimitry Andric NMD->addOperand(MDNode::get(
201cfca06d7SDimitry Andric Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
202044eb2f6SDimitry Andric };
203044eb2f6SDimitry Andric addDebugifyOperand(NextLine - 1); // Original number of lines.
204044eb2f6SDimitry Andric addDebugifyOperand(NextVar - 1); // Original number of variables.
205eb11fae6SDimitry Andric assert(NMD->getNumOperands() == 2 &&
206eb11fae6SDimitry Andric "llvm.debugify should have exactly 2 operands!");
207eb11fae6SDimitry Andric
208eb11fae6SDimitry Andric // Claim that this synthetic debug info is valid.
209eb11fae6SDimitry Andric StringRef DIVersionKey = "Debug Info Version";
210eb11fae6SDimitry Andric if (!M.getModuleFlag(DIVersionKey))
211eb11fae6SDimitry Andric M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
212eb11fae6SDimitry Andric
213044eb2f6SDimitry Andric return true;
214044eb2f6SDimitry Andric }
215044eb2f6SDimitry Andric
216344a3780SDimitry Andric static bool
applyDebugify(Function & F,enum DebugifyMode Mode=DebugifyMode::SyntheticDebugInfo,DebugInfoPerPass * DebugInfoBeforePass=nullptr,StringRef NameOfWrappedPass="")217344a3780SDimitry Andric applyDebugify(Function &F,
218344a3780SDimitry Andric enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
219145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr,
220344a3780SDimitry Andric StringRef NameOfWrappedPass = "") {
221b60736ecSDimitry Andric Module &M = *F.getParent();
222b60736ecSDimitry Andric auto FuncIt = F.getIterator();
223344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
224b60736ecSDimitry Andric return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
225344a3780SDimitry Andric "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
226145449b1SDimitry Andric assert(DebugInfoBeforePass);
227145449b1SDimitry Andric return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
228344a3780SDimitry Andric "FunctionDebugify (original debuginfo)",
229344a3780SDimitry Andric NameOfWrappedPass);
230b60736ecSDimitry Andric }
231b60736ecSDimitry Andric
232344a3780SDimitry Andric static bool
applyDebugify(Module & M,enum DebugifyMode Mode=DebugifyMode::SyntheticDebugInfo,DebugInfoPerPass * DebugInfoBeforePass=nullptr,StringRef NameOfWrappedPass="")233344a3780SDimitry Andric applyDebugify(Module &M,
234344a3780SDimitry Andric enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
235145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr,
236344a3780SDimitry Andric StringRef NameOfWrappedPass = "") {
237344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
238b60736ecSDimitry Andric return applyDebugifyMetadata(M, M.functions(),
239344a3780SDimitry Andric "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
240145449b1SDimitry Andric return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
241344a3780SDimitry Andric "ModuleDebugify (original debuginfo)",
242344a3780SDimitry Andric NameOfWrappedPass);
243b60736ecSDimitry Andric }
244b60736ecSDimitry Andric
stripDebugifyMetadata(Module & M)245cfca06d7SDimitry Andric bool llvm::stripDebugifyMetadata(Module &M) {
246cfca06d7SDimitry Andric bool Changed = false;
247cfca06d7SDimitry Andric
248e3b55780SDimitry Andric // Remove the llvm.debugify and llvm.mir.debugify module-level named metadata.
249cfca06d7SDimitry Andric NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
250cfca06d7SDimitry Andric if (DebugifyMD) {
251cfca06d7SDimitry Andric M.eraseNamedMetadata(DebugifyMD);
252cfca06d7SDimitry Andric Changed = true;
253cfca06d7SDimitry Andric }
254cfca06d7SDimitry Andric
255e3b55780SDimitry Andric if (auto *MIRDebugifyMD = M.getNamedMetadata("llvm.mir.debugify")) {
256e3b55780SDimitry Andric M.eraseNamedMetadata(MIRDebugifyMD);
257e3b55780SDimitry Andric Changed = true;
258e3b55780SDimitry Andric }
259e3b55780SDimitry Andric
260cfca06d7SDimitry Andric // Strip out all debug intrinsics and supporting metadata (subprograms, types,
261cfca06d7SDimitry Andric // variables, etc).
262cfca06d7SDimitry Andric Changed |= StripDebugInfo(M);
263cfca06d7SDimitry Andric
264cfca06d7SDimitry Andric // Strip out the dead dbg.value prototype.
265cfca06d7SDimitry Andric Function *DbgValF = M.getFunction("llvm.dbg.value");
266cfca06d7SDimitry Andric if (DbgValF) {
267cfca06d7SDimitry Andric assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
268cfca06d7SDimitry Andric "Not all debug info stripped?");
269cfca06d7SDimitry Andric DbgValF->eraseFromParent();
270cfca06d7SDimitry Andric Changed = true;
271cfca06d7SDimitry Andric }
272cfca06d7SDimitry Andric
273cfca06d7SDimitry Andric // Strip out the module-level Debug Info Version metadata.
274cfca06d7SDimitry Andric // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
275cfca06d7SDimitry Andric NamedMDNode *NMD = M.getModuleFlagsMetadata();
276cfca06d7SDimitry Andric if (!NMD)
277cfca06d7SDimitry Andric return Changed;
278b60736ecSDimitry Andric SmallVector<MDNode *, 4> Flags(NMD->operands());
279cfca06d7SDimitry Andric NMD->clearOperands();
280cfca06d7SDimitry Andric for (MDNode *Flag : Flags) {
281145449b1SDimitry Andric auto *Key = cast<MDString>(Flag->getOperand(1));
282cfca06d7SDimitry Andric if (Key->getString() == "Debug Info Version") {
283cfca06d7SDimitry Andric Changed = true;
284cfca06d7SDimitry Andric continue;
285cfca06d7SDimitry Andric }
286cfca06d7SDimitry Andric NMD->addOperand(Flag);
287cfca06d7SDimitry Andric }
288cfca06d7SDimitry Andric // If we left it empty we might as well remove it.
289cfca06d7SDimitry Andric if (NMD->getNumOperands() == 0)
290cfca06d7SDimitry Andric NMD->eraseFromParent();
291cfca06d7SDimitry Andric
292cfca06d7SDimitry Andric return Changed;
293cfca06d7SDimitry Andric }
294cfca06d7SDimitry Andric
collectDebugInfoMetadata(Module & M,iterator_range<Module::iterator> Functions,DebugInfoPerPass & DebugInfoBeforePass,StringRef Banner,StringRef NameOfWrappedPass)295344a3780SDimitry Andric bool llvm::collectDebugInfoMetadata(Module &M,
296344a3780SDimitry Andric iterator_range<Module::iterator> Functions,
297145449b1SDimitry Andric DebugInfoPerPass &DebugInfoBeforePass,
298344a3780SDimitry Andric StringRef Banner,
299344a3780SDimitry Andric StringRef NameOfWrappedPass) {
300344a3780SDimitry Andric LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
301344a3780SDimitry Andric
302344a3780SDimitry Andric if (!M.getNamedMetadata("llvm.dbg.cu")) {
303344a3780SDimitry Andric dbg() << Banner << ": Skipping module without debug info\n";
304344a3780SDimitry Andric return false;
305344a3780SDimitry Andric }
306344a3780SDimitry Andric
307145449b1SDimitry Andric uint64_t FunctionsCnt = DebugInfoBeforePass.DIFunctions.size();
308344a3780SDimitry Andric // Visit each instruction.
309344a3780SDimitry Andric for (Function &F : Functions) {
310145449b1SDimitry Andric // Use DI collected after previous Pass (when -debugify-each is used).
311145449b1SDimitry Andric if (DebugInfoBeforePass.DIFunctions.count(&F))
312145449b1SDimitry Andric continue;
313145449b1SDimitry Andric
314344a3780SDimitry Andric if (isFunctionSkipped(F))
315344a3780SDimitry Andric continue;
316344a3780SDimitry Andric
317145449b1SDimitry Andric // Stop collecting DI if the Functions number reached the limit.
318145449b1SDimitry Andric if (++FunctionsCnt >= DebugifyFunctionsLimit)
319145449b1SDimitry Andric break;
320344a3780SDimitry Andric // Collect the DISubprogram.
321344a3780SDimitry Andric auto *SP = F.getSubprogram();
322145449b1SDimitry Andric DebugInfoBeforePass.DIFunctions.insert({&F, SP});
323344a3780SDimitry Andric if (SP) {
324344a3780SDimitry Andric LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
325344a3780SDimitry Andric for (const DINode *DN : SP->getRetainedNodes()) {
326344a3780SDimitry Andric if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
327145449b1SDimitry Andric DebugInfoBeforePass.DIVariables[DV] = 0;
328344a3780SDimitry Andric }
329344a3780SDimitry Andric }
330344a3780SDimitry Andric }
331344a3780SDimitry Andric
332344a3780SDimitry Andric for (BasicBlock &BB : F) {
333344a3780SDimitry Andric // Collect debug locations (!dbg) and debug variable intrinsics.
334344a3780SDimitry Andric for (Instruction &I : BB) {
335344a3780SDimitry Andric // Skip PHIs.
336344a3780SDimitry Andric if (isa<PHINode>(I))
337344a3780SDimitry Andric continue;
338344a3780SDimitry Andric
339145449b1SDimitry Andric // Cllect dbg.values and dbg.declare.
340145449b1SDimitry Andric if (DebugifyLevel > Level::Locations) {
341ac9a064cSDimitry Andric auto HandleDbgVariable = [&](auto *DbgVar) {
342344a3780SDimitry Andric if (!SP)
343ac9a064cSDimitry Andric return;
344344a3780SDimitry Andric // Skip inlined variables.
345ac9a064cSDimitry Andric if (DbgVar->getDebugLoc().getInlinedAt())
346ac9a064cSDimitry Andric return;
347344a3780SDimitry Andric // Skip undef values.
348ac9a064cSDimitry Andric if (DbgVar->isKillLocation())
349ac9a064cSDimitry Andric return;
350344a3780SDimitry Andric
351ac9a064cSDimitry Andric auto *Var = DbgVar->getVariable();
352145449b1SDimitry Andric DebugInfoBeforePass.DIVariables[Var]++;
353ac9a064cSDimitry Andric };
354ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
355ac9a064cSDimitry Andric HandleDbgVariable(&DVR);
356ac9a064cSDimitry Andric if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
357ac9a064cSDimitry Andric HandleDbgVariable(DVI);
358145449b1SDimitry Andric }
359344a3780SDimitry Andric
360344a3780SDimitry Andric // Skip debug instructions other than dbg.value and dbg.declare.
361344a3780SDimitry Andric if (isa<DbgInfoIntrinsic>(&I))
362344a3780SDimitry Andric continue;
363344a3780SDimitry Andric
364344a3780SDimitry Andric LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
365145449b1SDimitry Andric DebugInfoBeforePass.InstToDelete.insert({&I, &I});
366344a3780SDimitry Andric
367344a3780SDimitry Andric const DILocation *Loc = I.getDebugLoc().get();
368344a3780SDimitry Andric bool HasLoc = Loc != nullptr;
369145449b1SDimitry Andric DebugInfoBeforePass.DILocations.insert({&I, HasLoc});
370344a3780SDimitry Andric }
371344a3780SDimitry Andric }
372344a3780SDimitry Andric }
373344a3780SDimitry Andric
374344a3780SDimitry Andric return true;
375344a3780SDimitry Andric }
376344a3780SDimitry Andric
377344a3780SDimitry Andric // This checks the preservation of original debug info attached to functions.
checkFunctions(const DebugFnMap & DIFunctionsBefore,const DebugFnMap & DIFunctionsAfter,StringRef NameOfWrappedPass,StringRef FileNameFromCU,bool ShouldWriteIntoJSON,llvm::json::Array & Bugs)378344a3780SDimitry Andric static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
379344a3780SDimitry Andric const DebugFnMap &DIFunctionsAfter,
380344a3780SDimitry Andric StringRef NameOfWrappedPass,
381344a3780SDimitry Andric StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
382344a3780SDimitry Andric llvm::json::Array &Bugs) {
383344a3780SDimitry Andric bool Preserved = true;
384344a3780SDimitry Andric for (const auto &F : DIFunctionsAfter) {
385344a3780SDimitry Andric if (F.second)
386344a3780SDimitry Andric continue;
387344a3780SDimitry Andric auto SPIt = DIFunctionsBefore.find(F.first);
388344a3780SDimitry Andric if (SPIt == DIFunctionsBefore.end()) {
389344a3780SDimitry Andric if (ShouldWriteIntoJSON)
390344a3780SDimitry Andric Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
391145449b1SDimitry Andric {"name", F.first->getName()},
392344a3780SDimitry Andric {"action", "not-generate"}}));
393344a3780SDimitry Andric else
394344a3780SDimitry Andric dbg() << "ERROR: " << NameOfWrappedPass
395145449b1SDimitry Andric << " did not generate DISubprogram for " << F.first->getName()
396145449b1SDimitry Andric << " from " << FileNameFromCU << '\n';
397344a3780SDimitry Andric Preserved = false;
398344a3780SDimitry Andric } else {
399344a3780SDimitry Andric auto SP = SPIt->second;
400344a3780SDimitry Andric if (!SP)
401344a3780SDimitry Andric continue;
402344a3780SDimitry Andric // If the function had the SP attached before the pass, consider it as
403344a3780SDimitry Andric // a debug info bug.
404344a3780SDimitry Andric if (ShouldWriteIntoJSON)
405344a3780SDimitry Andric Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
406145449b1SDimitry Andric {"name", F.first->getName()},
407344a3780SDimitry Andric {"action", "drop"}}));
408344a3780SDimitry Andric else
409344a3780SDimitry Andric dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
410145449b1SDimitry Andric << F.first->getName() << " from " << FileNameFromCU << '\n';
411344a3780SDimitry Andric Preserved = false;
412344a3780SDimitry Andric }
413344a3780SDimitry Andric }
414344a3780SDimitry Andric
415344a3780SDimitry Andric return Preserved;
416344a3780SDimitry Andric }
417344a3780SDimitry Andric
418344a3780SDimitry Andric // This checks the preservation of the original debug info attached to
419344a3780SDimitry Andric // instructions.
checkInstructions(const DebugInstMap & DILocsBefore,const DebugInstMap & DILocsAfter,const WeakInstValueMap & InstToDelete,StringRef NameOfWrappedPass,StringRef FileNameFromCU,bool ShouldWriteIntoJSON,llvm::json::Array & Bugs)420344a3780SDimitry Andric static bool checkInstructions(const DebugInstMap &DILocsBefore,
421344a3780SDimitry Andric const DebugInstMap &DILocsAfter,
422344a3780SDimitry Andric const WeakInstValueMap &InstToDelete,
423344a3780SDimitry Andric StringRef NameOfWrappedPass,
424344a3780SDimitry Andric StringRef FileNameFromCU,
425344a3780SDimitry Andric bool ShouldWriteIntoJSON,
426344a3780SDimitry Andric llvm::json::Array &Bugs) {
427344a3780SDimitry Andric bool Preserved = true;
428344a3780SDimitry Andric for (const auto &L : DILocsAfter) {
429344a3780SDimitry Andric if (L.second)
430344a3780SDimitry Andric continue;
431344a3780SDimitry Andric auto Instr = L.first;
432344a3780SDimitry Andric
433344a3780SDimitry Andric // In order to avoid pointer reuse/recycling, skip the values that might
434344a3780SDimitry Andric // have been deleted during a pass.
435344a3780SDimitry Andric auto WeakInstrPtr = InstToDelete.find(Instr);
436344a3780SDimitry Andric if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second)
437344a3780SDimitry Andric continue;
438344a3780SDimitry Andric
439344a3780SDimitry Andric auto FnName = Instr->getFunction()->getName();
440344a3780SDimitry Andric auto BB = Instr->getParent();
441344a3780SDimitry Andric auto BBName = BB->hasName() ? BB->getName() : "no-name";
442344a3780SDimitry Andric auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
443344a3780SDimitry Andric
444344a3780SDimitry Andric auto InstrIt = DILocsBefore.find(Instr);
445344a3780SDimitry Andric if (InstrIt == DILocsBefore.end()) {
446344a3780SDimitry Andric if (ShouldWriteIntoJSON)
447344a3780SDimitry Andric Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
448344a3780SDimitry Andric {"fn-name", FnName.str()},
449344a3780SDimitry Andric {"bb-name", BBName.str()},
450344a3780SDimitry Andric {"instr", InstName},
451344a3780SDimitry Andric {"action", "not-generate"}}));
452344a3780SDimitry Andric else
453344a3780SDimitry Andric dbg() << "WARNING: " << NameOfWrappedPass
454344a3780SDimitry Andric << " did not generate DILocation for " << *Instr
455344a3780SDimitry Andric << " (BB: " << BBName << ", Fn: " << FnName
456344a3780SDimitry Andric << ", File: " << FileNameFromCU << ")\n";
457344a3780SDimitry Andric Preserved = false;
458344a3780SDimitry Andric } else {
459344a3780SDimitry Andric if (!InstrIt->second)
460344a3780SDimitry Andric continue;
461344a3780SDimitry Andric // If the instr had the !dbg attached before the pass, consider it as
462344a3780SDimitry Andric // a debug info issue.
463344a3780SDimitry Andric if (ShouldWriteIntoJSON)
464344a3780SDimitry Andric Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
465344a3780SDimitry Andric {"fn-name", FnName.str()},
466344a3780SDimitry Andric {"bb-name", BBName.str()},
467344a3780SDimitry Andric {"instr", InstName},
468344a3780SDimitry Andric {"action", "drop"}}));
469344a3780SDimitry Andric else
470344a3780SDimitry Andric dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of "
471344a3780SDimitry Andric << *Instr << " (BB: " << BBName << ", Fn: " << FnName
472344a3780SDimitry Andric << ", File: " << FileNameFromCU << ")\n";
473344a3780SDimitry Andric Preserved = false;
474344a3780SDimitry Andric }
475344a3780SDimitry Andric }
476344a3780SDimitry Andric
477344a3780SDimitry Andric return Preserved;
478344a3780SDimitry Andric }
479344a3780SDimitry Andric
480344a3780SDimitry Andric // This checks the preservation of original debug variable intrinsics.
checkVars(const DebugVarMap & DIVarsBefore,const DebugVarMap & DIVarsAfter,StringRef NameOfWrappedPass,StringRef FileNameFromCU,bool ShouldWriteIntoJSON,llvm::json::Array & Bugs)481c0981da4SDimitry Andric static bool checkVars(const DebugVarMap &DIVarsBefore,
482c0981da4SDimitry Andric const DebugVarMap &DIVarsAfter,
483344a3780SDimitry Andric StringRef NameOfWrappedPass, StringRef FileNameFromCU,
484344a3780SDimitry Andric bool ShouldWriteIntoJSON, llvm::json::Array &Bugs) {
485344a3780SDimitry Andric bool Preserved = true;
486c0981da4SDimitry Andric for (const auto &V : DIVarsBefore) {
487c0981da4SDimitry Andric auto VarIt = DIVarsAfter.find(V.first);
488c0981da4SDimitry Andric if (VarIt == DIVarsAfter.end())
489344a3780SDimitry Andric continue;
490344a3780SDimitry Andric
491344a3780SDimitry Andric unsigned NumOfDbgValsAfter = VarIt->second;
492344a3780SDimitry Andric
493344a3780SDimitry Andric if (V.second > NumOfDbgValsAfter) {
494344a3780SDimitry Andric if (ShouldWriteIntoJSON)
495344a3780SDimitry Andric Bugs.push_back(llvm::json::Object(
496344a3780SDimitry Andric {{"metadata", "dbg-var-intrinsic"},
497344a3780SDimitry Andric {"name", V.first->getName()},
498344a3780SDimitry Andric {"fn-name", V.first->getScope()->getSubprogram()->getName()},
499344a3780SDimitry Andric {"action", "drop"}}));
500344a3780SDimitry Andric else
501344a3780SDimitry Andric dbg() << "WARNING: " << NameOfWrappedPass
502344a3780SDimitry Andric << " drops dbg.value()/dbg.declare() for " << V.first->getName()
503344a3780SDimitry Andric << " from "
504344a3780SDimitry Andric << "function " << V.first->getScope()->getSubprogram()->getName()
505344a3780SDimitry Andric << " (file " << FileNameFromCU << ")\n";
506344a3780SDimitry Andric Preserved = false;
507344a3780SDimitry Andric }
508344a3780SDimitry Andric }
509344a3780SDimitry Andric
510344a3780SDimitry Andric return Preserved;
511344a3780SDimitry Andric }
512344a3780SDimitry Andric
513344a3780SDimitry Andric // Write the json data into the specifed file.
writeJSON(StringRef OrigDIVerifyBugsReportFilePath,StringRef FileNameFromCU,StringRef NameOfWrappedPass,llvm::json::Array & Bugs)514344a3780SDimitry Andric static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
515344a3780SDimitry Andric StringRef FileNameFromCU, StringRef NameOfWrappedPass,
516344a3780SDimitry Andric llvm::json::Array &Bugs) {
517344a3780SDimitry Andric std::error_code EC;
518344a3780SDimitry Andric raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
519344a3780SDimitry Andric sys::fs::OF_Append | sys::fs::OF_TextWithCRLF};
520344a3780SDimitry Andric if (EC) {
521344a3780SDimitry Andric errs() << "Could not open file: " << EC.message() << ", "
522344a3780SDimitry Andric << OrigDIVerifyBugsReportFilePath << '\n';
523344a3780SDimitry Andric return;
524344a3780SDimitry Andric }
525344a3780SDimitry Andric
526e3b55780SDimitry Andric if (auto L = OS_FILE.lock()) {
527344a3780SDimitry Andric OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
528344a3780SDimitry Andric
529e3b55780SDimitry Andric StringRef PassName =
530e3b55780SDimitry Andric NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
531344a3780SDimitry Andric OS_FILE << "\"pass\":\"" << PassName << "\", ";
532344a3780SDimitry Andric
533344a3780SDimitry Andric llvm::json::Value BugsToPrint{std::move(Bugs)};
534344a3780SDimitry Andric OS_FILE << "\"bugs\": " << BugsToPrint;
535344a3780SDimitry Andric
536344a3780SDimitry Andric OS_FILE << "}\n";
537344a3780SDimitry Andric }
538e3b55780SDimitry Andric OS_FILE.close();
539e3b55780SDimitry Andric }
540344a3780SDimitry Andric
checkDebugInfoMetadata(Module & M,iterator_range<Module::iterator> Functions,DebugInfoPerPass & DebugInfoBeforePass,StringRef Banner,StringRef NameOfWrappedPass,StringRef OrigDIVerifyBugsReportFilePath)541344a3780SDimitry Andric bool llvm::checkDebugInfoMetadata(Module &M,
542344a3780SDimitry Andric iterator_range<Module::iterator> Functions,
543145449b1SDimitry Andric DebugInfoPerPass &DebugInfoBeforePass,
544344a3780SDimitry Andric StringRef Banner, StringRef NameOfWrappedPass,
545344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath) {
546344a3780SDimitry Andric LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
547344a3780SDimitry Andric
548344a3780SDimitry Andric if (!M.getNamedMetadata("llvm.dbg.cu")) {
549344a3780SDimitry Andric dbg() << Banner << ": Skipping module without debug info\n";
550344a3780SDimitry Andric return false;
551344a3780SDimitry Andric }
552344a3780SDimitry Andric
553344a3780SDimitry Andric // Map the debug info holding DIs after a pass.
554145449b1SDimitry Andric DebugInfoPerPass DebugInfoAfterPass;
555344a3780SDimitry Andric
556344a3780SDimitry Andric // Visit each instruction.
557344a3780SDimitry Andric for (Function &F : Functions) {
558344a3780SDimitry Andric if (isFunctionSkipped(F))
559344a3780SDimitry Andric continue;
560344a3780SDimitry Andric
561145449b1SDimitry Andric // Don't process functions without DI collected before the Pass.
562145449b1SDimitry Andric if (!DebugInfoBeforePass.DIFunctions.count(&F))
563145449b1SDimitry Andric continue;
564344a3780SDimitry Andric // TODO: Collect metadata other than DISubprograms.
565344a3780SDimitry Andric // Collect the DISubprogram.
566344a3780SDimitry Andric auto *SP = F.getSubprogram();
567145449b1SDimitry Andric DebugInfoAfterPass.DIFunctions.insert({&F, SP});
568344a3780SDimitry Andric
569344a3780SDimitry Andric if (SP) {
570344a3780SDimitry Andric LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
571344a3780SDimitry Andric for (const DINode *DN : SP->getRetainedNodes()) {
572344a3780SDimitry Andric if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
573145449b1SDimitry Andric DebugInfoAfterPass.DIVariables[DV] = 0;
574344a3780SDimitry Andric }
575344a3780SDimitry Andric }
576344a3780SDimitry Andric }
577344a3780SDimitry Andric
578344a3780SDimitry Andric for (BasicBlock &BB : F) {
579344a3780SDimitry Andric // Collect debug locations (!dbg) and debug variable intrinsics.
580344a3780SDimitry Andric for (Instruction &I : BB) {
581344a3780SDimitry Andric // Skip PHIs.
582344a3780SDimitry Andric if (isa<PHINode>(I))
583344a3780SDimitry Andric continue;
584344a3780SDimitry Andric
585344a3780SDimitry Andric // Collect dbg.values and dbg.declares.
586145449b1SDimitry Andric if (DebugifyLevel > Level::Locations) {
587ac9a064cSDimitry Andric auto HandleDbgVariable = [&](auto *DbgVar) {
588344a3780SDimitry Andric if (!SP)
589ac9a064cSDimitry Andric return;
590344a3780SDimitry Andric // Skip inlined variables.
591ac9a064cSDimitry Andric if (DbgVar->getDebugLoc().getInlinedAt())
592ac9a064cSDimitry Andric return;
593344a3780SDimitry Andric // Skip undef values.
594ac9a064cSDimitry Andric if (DbgVar->isKillLocation())
595ac9a064cSDimitry Andric return;
596344a3780SDimitry Andric
597ac9a064cSDimitry Andric auto *Var = DbgVar->getVariable();
598145449b1SDimitry Andric DebugInfoAfterPass.DIVariables[Var]++;
599ac9a064cSDimitry Andric };
600ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
601ac9a064cSDimitry Andric HandleDbgVariable(&DVR);
602ac9a064cSDimitry Andric if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
603ac9a064cSDimitry Andric HandleDbgVariable(DVI);
604145449b1SDimitry Andric }
605344a3780SDimitry Andric
606344a3780SDimitry Andric // Skip debug instructions other than dbg.value and dbg.declare.
607344a3780SDimitry Andric if (isa<DbgInfoIntrinsic>(&I))
608344a3780SDimitry Andric continue;
609344a3780SDimitry Andric
610344a3780SDimitry Andric LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
611344a3780SDimitry Andric
612344a3780SDimitry Andric const DILocation *Loc = I.getDebugLoc().get();
613344a3780SDimitry Andric bool HasLoc = Loc != nullptr;
614344a3780SDimitry Andric
615145449b1SDimitry Andric DebugInfoAfterPass.DILocations.insert({&I, HasLoc});
616344a3780SDimitry Andric }
617344a3780SDimitry Andric }
618344a3780SDimitry Andric }
619344a3780SDimitry Andric
620344a3780SDimitry Andric // TODO: The name of the module could be read better?
621344a3780SDimitry Andric StringRef FileNameFromCU =
622344a3780SDimitry Andric (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
623344a3780SDimitry Andric ->getFilename();
624344a3780SDimitry Andric
625145449b1SDimitry Andric auto DIFunctionsBefore = DebugInfoBeforePass.DIFunctions;
626145449b1SDimitry Andric auto DIFunctionsAfter = DebugInfoAfterPass.DIFunctions;
627344a3780SDimitry Andric
628145449b1SDimitry Andric auto DILocsBefore = DebugInfoBeforePass.DILocations;
629145449b1SDimitry Andric auto DILocsAfter = DebugInfoAfterPass.DILocations;
630344a3780SDimitry Andric
631145449b1SDimitry Andric auto InstToDelete = DebugInfoBeforePass.InstToDelete;
632344a3780SDimitry Andric
633145449b1SDimitry Andric auto DIVarsBefore = DebugInfoBeforePass.DIVariables;
634145449b1SDimitry Andric auto DIVarsAfter = DebugInfoAfterPass.DIVariables;
635344a3780SDimitry Andric
636344a3780SDimitry Andric bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
637344a3780SDimitry Andric llvm::json::Array Bugs;
638344a3780SDimitry Andric
639344a3780SDimitry Andric bool ResultForFunc =
640344a3780SDimitry Andric checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
641344a3780SDimitry Andric FileNameFromCU, ShouldWriteIntoJSON, Bugs);
642344a3780SDimitry Andric bool ResultForInsts = checkInstructions(
643344a3780SDimitry Andric DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass,
644344a3780SDimitry Andric FileNameFromCU, ShouldWriteIntoJSON, Bugs);
645344a3780SDimitry Andric
646344a3780SDimitry Andric bool ResultForVars = checkVars(DIVarsBefore, DIVarsAfter, NameOfWrappedPass,
647344a3780SDimitry Andric FileNameFromCU, ShouldWriteIntoJSON, Bugs);
648344a3780SDimitry Andric
649344a3780SDimitry Andric bool Result = ResultForFunc && ResultForInsts && ResultForVars;
650344a3780SDimitry Andric
651344a3780SDimitry Andric StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
652344a3780SDimitry Andric if (ShouldWriteIntoJSON && !Bugs.empty())
653344a3780SDimitry Andric writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
654344a3780SDimitry Andric Bugs);
655344a3780SDimitry Andric
656344a3780SDimitry Andric if (Result)
657344a3780SDimitry Andric dbg() << ResultBanner << ": PASS\n";
658344a3780SDimitry Andric else
659344a3780SDimitry Andric dbg() << ResultBanner << ": FAIL\n";
660344a3780SDimitry Andric
661145449b1SDimitry Andric // In the case of the `debugify-each`, no need to go over all the instructions
662145449b1SDimitry Andric // again in the collectDebugInfoMetadata(), since as an input we can use
663145449b1SDimitry Andric // the debugging information from the previous pass.
664145449b1SDimitry Andric DebugInfoBeforePass = DebugInfoAfterPass;
665145449b1SDimitry Andric
666344a3780SDimitry Andric LLVM_DEBUG(dbgs() << "\n\n");
667344a3780SDimitry Andric return Result;
668344a3780SDimitry Andric }
669344a3780SDimitry Andric
670cfca06d7SDimitry Andric namespace {
671ac9a064cSDimitry Andric /// Return true if a mis-sized diagnostic is issued for \p DbgVal.
672ac9a064cSDimitry Andric template <typename DbgValTy>
diagnoseMisSizedDbgValue(Module & M,DbgValTy * DbgVal)673ac9a064cSDimitry Andric bool diagnoseMisSizedDbgValue(Module &M, DbgValTy *DbgVal) {
674eb11fae6SDimitry Andric // The size of a dbg.value's value operand should match the size of the
675eb11fae6SDimitry Andric // variable it corresponds to.
676eb11fae6SDimitry Andric //
677eb11fae6SDimitry Andric // TODO: This, along with a check for non-null value operands, should be
678eb11fae6SDimitry Andric // promoted to verifier failures.
679eb11fae6SDimitry Andric
680eb11fae6SDimitry Andric // For now, don't try to interpret anything more complicated than an empty
681eb11fae6SDimitry Andric // DIExpression. Eventually we should try to handle OP_deref and fragments.
682ac9a064cSDimitry Andric if (DbgVal->getExpression()->getNumElements())
683eb11fae6SDimitry Andric return false;
684eb11fae6SDimitry Andric
685ac9a064cSDimitry Andric Value *V = DbgVal->getVariableLocationOp(0);
686344a3780SDimitry Andric if (!V)
687344a3780SDimitry Andric return false;
688344a3780SDimitry Andric
689eb11fae6SDimitry Andric Type *Ty = V->getType();
690eb11fae6SDimitry Andric uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
691ac9a064cSDimitry Andric std::optional<uint64_t> DbgVarSize = DbgVal->getFragmentSizeInBits();
692eb11fae6SDimitry Andric if (!ValueOperandSize || !DbgVarSize)
693eb11fae6SDimitry Andric return false;
694eb11fae6SDimitry Andric
695eb11fae6SDimitry Andric bool HasBadSize = false;
696eb11fae6SDimitry Andric if (Ty->isIntegerTy()) {
697ac9a064cSDimitry Andric auto Signedness = DbgVal->getVariable()->getSignedness();
698eb11fae6SDimitry Andric if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
699eb11fae6SDimitry Andric HasBadSize = ValueOperandSize < *DbgVarSize;
700eb11fae6SDimitry Andric } else {
701eb11fae6SDimitry Andric HasBadSize = ValueOperandSize != *DbgVarSize;
702eb11fae6SDimitry Andric }
703eb11fae6SDimitry Andric
704eb11fae6SDimitry Andric if (HasBadSize) {
705eb11fae6SDimitry Andric dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
706eb11fae6SDimitry Andric << ", but its variable has size " << *DbgVarSize << ": ";
707ac9a064cSDimitry Andric DbgVal->print(dbg());
708eb11fae6SDimitry Andric dbg() << "\n";
709eb11fae6SDimitry Andric }
710eb11fae6SDimitry Andric return HasBadSize;
711eb11fae6SDimitry Andric }
712eb11fae6SDimitry Andric
checkDebugifyMetadata(Module & M,iterator_range<Module::iterator> Functions,StringRef NameOfWrappedPass,StringRef Banner,bool Strip,DebugifyStatsMap * StatsMap)713eb11fae6SDimitry Andric bool checkDebugifyMetadata(Module &M,
714eb11fae6SDimitry Andric iterator_range<Module::iterator> Functions,
715eb11fae6SDimitry Andric StringRef NameOfWrappedPass, StringRef Banner,
716eb11fae6SDimitry Andric bool Strip, DebugifyStatsMap *StatsMap) {
717044eb2f6SDimitry Andric // Skip modules without debugify metadata.
718044eb2f6SDimitry Andric NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
719eb11fae6SDimitry Andric if (!NMD) {
720cfca06d7SDimitry Andric dbg() << Banner << ": Skipping module without debugify metadata\n";
721eb11fae6SDimitry Andric return false;
722eb11fae6SDimitry Andric }
723044eb2f6SDimitry Andric
724044eb2f6SDimitry Andric auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
725044eb2f6SDimitry Andric return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
726044eb2f6SDimitry Andric ->getZExtValue();
727044eb2f6SDimitry Andric };
728eb11fae6SDimitry Andric assert(NMD->getNumOperands() == 2 &&
729eb11fae6SDimitry Andric "llvm.debugify should have exactly 2 operands!");
730044eb2f6SDimitry Andric unsigned OriginalNumLines = getDebugifyOperand(0);
731044eb2f6SDimitry Andric unsigned OriginalNumVars = getDebugifyOperand(1);
732044eb2f6SDimitry Andric bool HasErrors = false;
733044eb2f6SDimitry Andric
734eb11fae6SDimitry Andric // Track debug info loss statistics if able.
735eb11fae6SDimitry Andric DebugifyStatistics *Stats = nullptr;
736eb11fae6SDimitry Andric if (StatsMap && !NameOfWrappedPass.empty())
737eb11fae6SDimitry Andric Stats = &StatsMap->operator[](NameOfWrappedPass);
738eb11fae6SDimitry Andric
739044eb2f6SDimitry Andric BitVector MissingLines{OriginalNumLines, true};
740eb11fae6SDimitry Andric BitVector MissingVars{OriginalNumVars, true};
741eb11fae6SDimitry Andric for (Function &F : Functions) {
742eb11fae6SDimitry Andric if (isFunctionSkipped(F))
743eb11fae6SDimitry Andric continue;
744eb11fae6SDimitry Andric
745eb11fae6SDimitry Andric // Find missing lines.
746044eb2f6SDimitry Andric for (Instruction &I : instructions(F)) {
747344a3780SDimitry Andric if (isa<DbgValueInst>(&I))
748044eb2f6SDimitry Andric continue;
749044eb2f6SDimitry Andric
750044eb2f6SDimitry Andric auto DL = I.getDebugLoc();
751eb11fae6SDimitry Andric if (DL && DL.getLine() != 0) {
752044eb2f6SDimitry Andric MissingLines.reset(DL.getLine() - 1);
753044eb2f6SDimitry Andric continue;
754044eb2f6SDimitry Andric }
755044eb2f6SDimitry Andric
756344a3780SDimitry Andric if (!isa<PHINode>(&I) && !DL) {
757cfca06d7SDimitry Andric dbg() << "WARNING: Instruction with empty DebugLoc in function ";
758eb11fae6SDimitry Andric dbg() << F.getName() << " --";
759eb11fae6SDimitry Andric I.print(dbg());
760eb11fae6SDimitry Andric dbg() << "\n";
761044eb2f6SDimitry Andric }
762044eb2f6SDimitry Andric }
763044eb2f6SDimitry Andric
764eb11fae6SDimitry Andric // Find missing variables and mis-sized debug values.
765ac9a064cSDimitry Andric auto CheckForMisSized = [&](auto *DbgVal) {
766044eb2f6SDimitry Andric unsigned Var = ~0U;
767ac9a064cSDimitry Andric (void)to_integer(DbgVal->getVariable()->getName(), Var, 10);
768044eb2f6SDimitry Andric assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
769ac9a064cSDimitry Andric bool HasBadSize = diagnoseMisSizedDbgValue(M, DbgVal);
770eb11fae6SDimitry Andric if (!HasBadSize)
771044eb2f6SDimitry Andric MissingVars.reset(Var - 1);
772eb11fae6SDimitry Andric HasErrors |= HasBadSize;
773ac9a064cSDimitry Andric };
774ac9a064cSDimitry Andric for (Instruction &I : instructions(F)) {
775ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
776ac9a064cSDimitry Andric if (DVR.isDbgValue() || DVR.isDbgAssign())
777ac9a064cSDimitry Andric CheckForMisSized(&DVR);
778ac9a064cSDimitry Andric auto *DVI = dyn_cast<DbgValueInst>(&I);
779ac9a064cSDimitry Andric if (!DVI)
780ac9a064cSDimitry Andric continue;
781ac9a064cSDimitry Andric CheckForMisSized(DVI);
782044eb2f6SDimitry Andric }
783044eb2f6SDimitry Andric }
784eb11fae6SDimitry Andric
785eb11fae6SDimitry Andric // Print the results.
786eb11fae6SDimitry Andric for (unsigned Idx : MissingLines.set_bits())
787eb11fae6SDimitry Andric dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
788eb11fae6SDimitry Andric
789044eb2f6SDimitry Andric for (unsigned Idx : MissingVars.set_bits())
790eb11fae6SDimitry Andric dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
791044eb2f6SDimitry Andric
792eb11fae6SDimitry Andric // Update DI loss statistics.
793eb11fae6SDimitry Andric if (Stats) {
794eb11fae6SDimitry Andric Stats->NumDbgLocsExpected += OriginalNumLines;
795eb11fae6SDimitry Andric Stats->NumDbgLocsMissing += MissingLines.count();
796eb11fae6SDimitry Andric Stats->NumDbgValuesExpected += OriginalNumVars;
797eb11fae6SDimitry Andric Stats->NumDbgValuesMissing += MissingVars.count();
798044eb2f6SDimitry Andric }
799044eb2f6SDimitry Andric
800eb11fae6SDimitry Andric dbg() << Banner;
801eb11fae6SDimitry Andric if (!NameOfWrappedPass.empty())
802eb11fae6SDimitry Andric dbg() << " [" << NameOfWrappedPass << "]";
803eb11fae6SDimitry Andric dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
804044eb2f6SDimitry Andric
805cfca06d7SDimitry Andric // Strip debugify metadata if required.
806ac9a064cSDimitry Andric bool Ret = false;
807cfca06d7SDimitry Andric if (Strip)
808ac9a064cSDimitry Andric Ret = stripDebugifyMetadata(M);
809eb11fae6SDimitry Andric
810ac9a064cSDimitry Andric return Ret;
811eb11fae6SDimitry Andric }
812eb11fae6SDimitry Andric
813eb11fae6SDimitry Andric /// ModulePass for attaching synthetic debug info to everything, used with the
814eb11fae6SDimitry Andric /// legacy module pass manager.
815eb11fae6SDimitry Andric struct DebugifyModulePass : public ModulePass {
runOnModule__anon3123a4b20711::DebugifyModulePass816eb11fae6SDimitry Andric bool runOnModule(Module &M) override {
817ac9a064cSDimitry Andric bool Result =
818ac9a064cSDimitry Andric applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass);
819b1c73532SDimitry Andric return Result;
820eb11fae6SDimitry Andric }
821eb11fae6SDimitry Andric
DebugifyModulePass__anon3123a4b20711::DebugifyModulePass822344a3780SDimitry Andric DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
823344a3780SDimitry Andric StringRef NameOfWrappedPass = "",
824145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr)
825344a3780SDimitry Andric : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
826145449b1SDimitry Andric DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
827eb11fae6SDimitry Andric
getAnalysisUsage__anon3123a4b20711::DebugifyModulePass828eb11fae6SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
829eb11fae6SDimitry Andric AU.setPreservesAll();
830eb11fae6SDimitry Andric }
831eb11fae6SDimitry Andric
832eb11fae6SDimitry Andric static char ID; // Pass identification.
833eb11fae6SDimitry Andric
834eb11fae6SDimitry Andric private:
835eb11fae6SDimitry Andric StringRef NameOfWrappedPass;
836145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass;
837344a3780SDimitry Andric enum DebugifyMode Mode;
838344a3780SDimitry Andric };
839344a3780SDimitry Andric
840344a3780SDimitry Andric /// FunctionPass for attaching synthetic debug info to instructions within a
841344a3780SDimitry Andric /// single function, used with the legacy module pass manager.
842344a3780SDimitry Andric struct DebugifyFunctionPass : public FunctionPass {
runOnFunction__anon3123a4b20711::DebugifyFunctionPass843344a3780SDimitry Andric bool runOnFunction(Function &F) override {
844ac9a064cSDimitry Andric bool Result =
845ac9a064cSDimitry Andric applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass);
846b1c73532SDimitry Andric return Result;
847344a3780SDimitry Andric }
848344a3780SDimitry Andric
DebugifyFunctionPass__anon3123a4b20711::DebugifyFunctionPass849344a3780SDimitry Andric DebugifyFunctionPass(
850344a3780SDimitry Andric enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
851344a3780SDimitry Andric StringRef NameOfWrappedPass = "",
852145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr)
853344a3780SDimitry Andric : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
854145449b1SDimitry Andric DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
855344a3780SDimitry Andric
getAnalysisUsage__anon3123a4b20711::DebugifyFunctionPass856344a3780SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
857344a3780SDimitry Andric AU.setPreservesAll();
858344a3780SDimitry Andric }
859344a3780SDimitry Andric
860344a3780SDimitry Andric static char ID; // Pass identification.
861344a3780SDimitry Andric
862344a3780SDimitry Andric private:
863344a3780SDimitry Andric StringRef NameOfWrappedPass;
864145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass;
865344a3780SDimitry Andric enum DebugifyMode Mode;
866344a3780SDimitry Andric };
867344a3780SDimitry Andric
868344a3780SDimitry Andric /// ModulePass for checking debug info inserted by -debugify, used with the
869344a3780SDimitry Andric /// legacy module pass manager.
870344a3780SDimitry Andric struct CheckDebugifyModulePass : public ModulePass {
runOnModule__anon3123a4b20711::CheckDebugifyModulePass871344a3780SDimitry Andric bool runOnModule(Module &M) override {
872b1c73532SDimitry Andric bool Result;
873344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
874b1c73532SDimitry Andric Result = checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
875344a3780SDimitry Andric "CheckModuleDebugify", Strip, StatsMap);
876b1c73532SDimitry Andric else
877b1c73532SDimitry Andric Result = checkDebugInfoMetadata(
878145449b1SDimitry Andric M, M.functions(), *DebugInfoBeforePass,
879344a3780SDimitry Andric "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
880344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath);
881b1c73532SDimitry Andric
882b1c73532SDimitry Andric return Result;
883344a3780SDimitry Andric }
884344a3780SDimitry Andric
CheckDebugifyModulePass__anon3123a4b20711::CheckDebugifyModulePass885344a3780SDimitry Andric CheckDebugifyModulePass(
886344a3780SDimitry Andric bool Strip = false, StringRef NameOfWrappedPass = "",
887344a3780SDimitry Andric DebugifyStatsMap *StatsMap = nullptr,
888344a3780SDimitry Andric enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
889145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr,
890344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath = "")
891344a3780SDimitry Andric : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
892344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
893145449b1SDimitry Andric StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
894344a3780SDimitry Andric Strip(Strip) {}
895344a3780SDimitry Andric
getAnalysisUsage__anon3123a4b20711::CheckDebugifyModulePass896344a3780SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
897344a3780SDimitry Andric AU.setPreservesAll();
898344a3780SDimitry Andric }
899344a3780SDimitry Andric
900344a3780SDimitry Andric static char ID; // Pass identification.
901344a3780SDimitry Andric
902344a3780SDimitry Andric private:
903344a3780SDimitry Andric StringRef NameOfWrappedPass;
904344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath;
905eb11fae6SDimitry Andric DebugifyStatsMap *StatsMap;
906145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass;
907344a3780SDimitry Andric enum DebugifyMode Mode;
908344a3780SDimitry Andric bool Strip;
909eb11fae6SDimitry Andric };
910eb11fae6SDimitry Andric
911eb11fae6SDimitry Andric /// FunctionPass for checking debug info inserted by -debugify-function, used
912eb11fae6SDimitry Andric /// with the legacy module pass manager.
913eb11fae6SDimitry Andric struct CheckDebugifyFunctionPass : public FunctionPass {
runOnFunction__anon3123a4b20711::CheckDebugifyFunctionPass914eb11fae6SDimitry Andric bool runOnFunction(Function &F) override {
915eb11fae6SDimitry Andric Module &M = *F.getParent();
916eb11fae6SDimitry Andric auto FuncIt = F.getIterator();
917b1c73532SDimitry Andric bool Result;
918344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
919b1c73532SDimitry Andric Result = checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
920eb11fae6SDimitry Andric NameOfWrappedPass, "CheckFunctionDebugify",
921eb11fae6SDimitry Andric Strip, StatsMap);
922b1c73532SDimitry Andric else
923b1c73532SDimitry Andric Result = checkDebugInfoMetadata(
924145449b1SDimitry Andric M, make_range(FuncIt, std::next(FuncIt)), *DebugInfoBeforePass,
925344a3780SDimitry Andric "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
926344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath);
927b1c73532SDimitry Andric
928b1c73532SDimitry Andric return Result;
929eb11fae6SDimitry Andric }
930eb11fae6SDimitry Andric
CheckDebugifyFunctionPass__anon3123a4b20711::CheckDebugifyFunctionPass931344a3780SDimitry Andric CheckDebugifyFunctionPass(
932344a3780SDimitry Andric bool Strip = false, StringRef NameOfWrappedPass = "",
933344a3780SDimitry Andric DebugifyStatsMap *StatsMap = nullptr,
934344a3780SDimitry Andric enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
935145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass = nullptr,
936344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath = "")
937344a3780SDimitry Andric : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
938344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
939145449b1SDimitry Andric StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
940344a3780SDimitry Andric Strip(Strip) {}
941eb11fae6SDimitry Andric
getAnalysisUsage__anon3123a4b20711::CheckDebugifyFunctionPass942eb11fae6SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
943eb11fae6SDimitry Andric AU.setPreservesAll();
944eb11fae6SDimitry Andric }
945eb11fae6SDimitry Andric
946eb11fae6SDimitry Andric static char ID; // Pass identification.
947eb11fae6SDimitry Andric
948eb11fae6SDimitry Andric private:
949eb11fae6SDimitry Andric StringRef NameOfWrappedPass;
950344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath;
951eb11fae6SDimitry Andric DebugifyStatsMap *StatsMap;
952145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass;
953344a3780SDimitry Andric enum DebugifyMode Mode;
954344a3780SDimitry Andric bool Strip;
955eb11fae6SDimitry Andric };
956eb11fae6SDimitry Andric
957044eb2f6SDimitry Andric } // end anonymous namespace
958044eb2f6SDimitry Andric
exportDebugifyStats(StringRef Path,const DebugifyStatsMap & Map)959b60736ecSDimitry Andric void llvm::exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map) {
960b60736ecSDimitry Andric std::error_code EC;
961b60736ecSDimitry Andric raw_fd_ostream OS{Path, EC};
962b60736ecSDimitry Andric if (EC) {
963b60736ecSDimitry Andric errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
964b60736ecSDimitry Andric return;
965b60736ecSDimitry Andric }
966eb11fae6SDimitry Andric
967b60736ecSDimitry Andric OS << "Pass Name" << ',' << "# of missing debug values" << ','
968b60736ecSDimitry Andric << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
969b60736ecSDimitry Andric << "Missing/Expected location ratio" << '\n';
970b60736ecSDimitry Andric for (const auto &Entry : Map) {
971b60736ecSDimitry Andric StringRef Pass = Entry.first;
972b60736ecSDimitry Andric DebugifyStatistics Stats = Entry.second;
973b60736ecSDimitry Andric
974b60736ecSDimitry Andric OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
975b60736ecSDimitry Andric << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
976b60736ecSDimitry Andric << Stats.getEmptyLocationRatio() << '\n';
977b60736ecSDimitry Andric }
978b60736ecSDimitry Andric }
979b60736ecSDimitry Andric
createDebugifyModulePass(enum DebugifyMode Mode,llvm::StringRef NameOfWrappedPass,DebugInfoPerPass * DebugInfoBeforePass)980344a3780SDimitry Andric ModulePass *createDebugifyModulePass(enum DebugifyMode Mode,
981344a3780SDimitry Andric llvm::StringRef NameOfWrappedPass,
982145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass) {
983344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
984b60736ecSDimitry Andric return new DebugifyModulePass();
985344a3780SDimitry Andric assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
986145449b1SDimitry Andric return new DebugifyModulePass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
987b60736ecSDimitry Andric }
988b60736ecSDimitry Andric
989344a3780SDimitry Andric FunctionPass *
createDebugifyFunctionPass(enum DebugifyMode Mode,llvm::StringRef NameOfWrappedPass,DebugInfoPerPass * DebugInfoBeforePass)990344a3780SDimitry Andric createDebugifyFunctionPass(enum DebugifyMode Mode,
991344a3780SDimitry Andric llvm::StringRef NameOfWrappedPass,
992145449b1SDimitry Andric DebugInfoPerPass *DebugInfoBeforePass) {
993344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
994eb11fae6SDimitry Andric return new DebugifyFunctionPass();
995344a3780SDimitry Andric assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
996145449b1SDimitry Andric return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
997eb11fae6SDimitry Andric }
998eb11fae6SDimitry Andric
run(Module & M,ModuleAnalysisManager &)999eb11fae6SDimitry Andric PreservedAnalyses NewPMDebugifyPass::run(Module &M, ModuleAnalysisManager &) {
10001f917f69SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
1001cfca06d7SDimitry Andric applyDebugifyMetadata(M, M.functions(),
1002cfca06d7SDimitry Andric "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
10031f917f69SDimitry Andric else
10041f917f69SDimitry Andric collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
10051f917f69SDimitry Andric "ModuleDebugify (original debuginfo)",
10061f917f69SDimitry Andric NameOfWrappedPass);
1007b1c73532SDimitry Andric
10087fa27ce4SDimitry Andric PreservedAnalyses PA;
10097fa27ce4SDimitry Andric PA.preserveSet<CFGAnalyses>();
10107fa27ce4SDimitry Andric return PA;
1011eb11fae6SDimitry Andric }
1012eb11fae6SDimitry Andric
createCheckDebugifyModulePass(bool Strip,StringRef NameOfWrappedPass,DebugifyStatsMap * StatsMap,enum DebugifyMode Mode,DebugInfoPerPass * DebugInfoBeforePass,StringRef OrigDIVerifyBugsReportFilePath)1013344a3780SDimitry Andric ModulePass *createCheckDebugifyModulePass(
1014344a3780SDimitry Andric bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1015145449b1SDimitry Andric enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1016344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath) {
1017344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
1018eb11fae6SDimitry Andric return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
1019344a3780SDimitry Andric assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1020344a3780SDimitry Andric return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
1021145449b1SDimitry Andric DebugInfoBeforePass,
1022344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath);
1023eb11fae6SDimitry Andric }
1024eb11fae6SDimitry Andric
createCheckDebugifyFunctionPass(bool Strip,StringRef NameOfWrappedPass,DebugifyStatsMap * StatsMap,enum DebugifyMode Mode,DebugInfoPerPass * DebugInfoBeforePass,StringRef OrigDIVerifyBugsReportFilePath)1025344a3780SDimitry Andric FunctionPass *createCheckDebugifyFunctionPass(
1026344a3780SDimitry Andric bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1027145449b1SDimitry Andric enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1028344a3780SDimitry Andric StringRef OrigDIVerifyBugsReportFilePath) {
1029344a3780SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
1030eb11fae6SDimitry Andric return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
1031344a3780SDimitry Andric assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1032344a3780SDimitry Andric return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
1033145449b1SDimitry Andric DebugInfoBeforePass,
1034344a3780SDimitry Andric OrigDIVerifyBugsReportFilePath);
1035eb11fae6SDimitry Andric }
1036eb11fae6SDimitry Andric
run(Module & M,ModuleAnalysisManager &)1037eb11fae6SDimitry Andric PreservedAnalyses NewPMCheckDebugifyPass::run(Module &M,
1038eb11fae6SDimitry Andric ModuleAnalysisManager &) {
10391f917f69SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
10401f917f69SDimitry Andric checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
10411f917f69SDimitry Andric "CheckModuleDebugify", Strip, StatsMap);
10421f917f69SDimitry Andric else
10431f917f69SDimitry Andric checkDebugInfoMetadata(
10441f917f69SDimitry Andric M, M.functions(), *DebugInfoBeforePass,
10451f917f69SDimitry Andric "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
10461f917f69SDimitry Andric OrigDIVerifyBugsReportFilePath);
1047b1c73532SDimitry Andric
1048eb11fae6SDimitry Andric return PreservedAnalyses::all();
1049eb11fae6SDimitry Andric }
1050eb11fae6SDimitry Andric
isIgnoredPass(StringRef PassID)1051b60736ecSDimitry Andric static bool isIgnoredPass(StringRef PassID) {
1052b60736ecSDimitry Andric return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
1053b60736ecSDimitry Andric "AnalysisManagerProxy", "PrintFunctionPass",
1054b60736ecSDimitry Andric "PrintModulePass", "BitcodeWriterPass",
1055b60736ecSDimitry Andric "ThinLTOBitcodeWriterPass", "VerifierPass"});
1056b60736ecSDimitry Andric }
1057b60736ecSDimitry Andric
registerCallbacks(PassInstrumentationCallbacks & PIC,ModuleAnalysisManager & MAM)1058b60736ecSDimitry Andric void DebugifyEachInstrumentation::registerCallbacks(
10597fa27ce4SDimitry Andric PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM) {
10607fa27ce4SDimitry Andric PIC.registerBeforeNonSkippedPassCallback([this, &MAM](StringRef P, Any IR) {
1061b60736ecSDimitry Andric if (isIgnoredPass(P))
1062b60736ecSDimitry Andric return;
10637fa27ce4SDimitry Andric PreservedAnalyses PA;
10647fa27ce4SDimitry Andric PA.preserveSet<CFGAnalyses>();
1065b1c73532SDimitry Andric if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
10667fa27ce4SDimitry Andric Function &F = *const_cast<Function *>(*CF);
10677fa27ce4SDimitry Andric applyDebugify(F, Mode, DebugInfoBeforePass, P);
10687fa27ce4SDimitry Andric MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
10697fa27ce4SDimitry Andric .getManager()
10707fa27ce4SDimitry Andric .invalidate(F, PA);
1071b1c73532SDimitry Andric } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
10727fa27ce4SDimitry Andric Module &M = *const_cast<Module *>(*CM);
10737fa27ce4SDimitry Andric applyDebugify(M, Mode, DebugInfoBeforePass, P);
10747fa27ce4SDimitry Andric MAM.invalidate(M, PA);
10757fa27ce4SDimitry Andric }
1076b60736ecSDimitry Andric });
10777fa27ce4SDimitry Andric PIC.registerAfterPassCallback(
10787fa27ce4SDimitry Andric [this, &MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1079b60736ecSDimitry Andric if (isIgnoredPass(P))
1080b60736ecSDimitry Andric return;
10817fa27ce4SDimitry Andric PreservedAnalyses PA;
10827fa27ce4SDimitry Andric PA.preserveSet<CFGAnalyses>();
1083b1c73532SDimitry Andric if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1084e3b55780SDimitry Andric auto &F = *const_cast<Function *>(*CF);
1085b60736ecSDimitry Andric Module &M = *F.getParent();
1086b60736ecSDimitry Andric auto It = F.getIterator();
10871f917f69SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
1088b60736ecSDimitry Andric checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
10897fa27ce4SDimitry Andric "CheckFunctionDebugify", /*Strip=*/true,
10907fa27ce4SDimitry Andric DIStatsMap);
10911f917f69SDimitry Andric else
10927fa27ce4SDimitry Andric checkDebugInfoMetadata(M, make_range(It, std::next(It)),
10937fa27ce4SDimitry Andric *DebugInfoBeforePass,
10941f917f69SDimitry Andric "CheckModuleDebugify (original debuginfo)",
10951f917f69SDimitry Andric P, OrigDIVerifyBugsReportFilePath);
10967fa27ce4SDimitry Andric MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
10977fa27ce4SDimitry Andric .getManager()
10987fa27ce4SDimitry Andric .invalidate(F, PA);
1099b1c73532SDimitry Andric } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
11007fa27ce4SDimitry Andric Module &M = *const_cast<Module *>(*CM);
11011f917f69SDimitry Andric if (Mode == DebugifyMode::SyntheticDebugInfo)
1102b60736ecSDimitry Andric checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
11031f917f69SDimitry Andric /*Strip=*/true, DIStatsMap);
11041f917f69SDimitry Andric else
11057fa27ce4SDimitry Andric checkDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
11061f917f69SDimitry Andric "CheckModuleDebugify (original debuginfo)",
11071f917f69SDimitry Andric P, OrigDIVerifyBugsReportFilePath);
11087fa27ce4SDimitry Andric MAM.invalidate(M, PA);
1109b60736ecSDimitry Andric }
1110b60736ecSDimitry Andric });
1111b60736ecSDimitry Andric }
1112b60736ecSDimitry Andric
1113eb11fae6SDimitry Andric char DebugifyModulePass::ID = 0;
1114eb11fae6SDimitry Andric static RegisterPass<DebugifyModulePass> DM("debugify",
1115044eb2f6SDimitry Andric "Attach debug info to everything");
1116044eb2f6SDimitry Andric
1117eb11fae6SDimitry Andric char CheckDebugifyModulePass::ID = 0;
1118eb11fae6SDimitry Andric static RegisterPass<CheckDebugifyModulePass>
1119eb11fae6SDimitry Andric CDM("check-debugify", "Check debug info from -debugify");
1120eb11fae6SDimitry Andric
1121eb11fae6SDimitry Andric char DebugifyFunctionPass::ID = 0;
1122eb11fae6SDimitry Andric static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
1123eb11fae6SDimitry Andric "Attach debug info to a function");
1124eb11fae6SDimitry Andric
1125eb11fae6SDimitry Andric char CheckDebugifyFunctionPass::ID = 0;
1126eb11fae6SDimitry Andric static RegisterPass<CheckDebugifyFunctionPass>
1127eb11fae6SDimitry Andric CDF("check-debugify-function", "Check debug info from -debugify-function");
1128