LLVM 19.0.0git
Debugify.cpp
Go to the documentation of this file.
1//===- Debugify.cpp - Check debug info preservation in optimizations ------===//
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/// \file In the `synthetic` mode, the `-debugify` attaches synthetic debug info
10/// to everything. It can be used to create targeted tests for debug info
11/// preservation. In addition, when using the `original` mode, it can check
12/// original debug info preservation. The `synthetic` mode is default one.
13///
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/BitVector.h"
19#include "llvm/IR/DIBuilder.h"
20#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/Module.h"
26#include "llvm/Pass.h"
29#include "llvm/Support/JSON.h"
30#include <optional>
31
32#define DEBUG_TYPE "debugify"
33
34using namespace llvm;
35
36namespace {
37
38cl::opt<bool> Quiet("debugify-quiet",
39 cl::desc("Suppress verbose debugify output"));
40
41cl::opt<uint64_t> DebugifyFunctionsLimit(
42 "debugify-func-limit",
43 cl::desc("Set max number of processed functions per pass."),
44 cl::init(UINT_MAX));
45
46enum class Level {
47 Locations,
48 LocationsAndVariables
49};
50
51cl::opt<Level> DebugifyLevel(
52 "debugify-level", cl::desc("Kind of debug info to add"),
53 cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
54 clEnumValN(Level::LocationsAndVariables, "location+variables",
55 "Locations and Variables")),
56 cl::init(Level::LocationsAndVariables));
57
58raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
59
60uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
61 return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
62}
63
64bool isFunctionSkipped(Function &F) {
65 return F.isDeclaration() || !F.hasExactDefinition();
66}
67
68/// Find the basic block's terminating instruction.
69///
70/// Special care is needed to handle musttail and deopt calls, as these behave
71/// like (but are in fact not) terminators.
72Instruction *findTerminatingInstruction(BasicBlock &BB) {
73 if (auto *I = BB.getTerminatingMustTailCall())
74 return I;
75 if (auto *I = BB.getTerminatingDeoptimizeCall())
76 return I;
77 return BB.getTerminator();
78}
79} // end anonymous namespace
80
83 std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
84 // Skip modules with debug info.
85 if (M.getNamedMetadata("llvm.dbg.cu")) {
86 dbg() << Banner << "Skipping module with debug info\n";
87 return false;
88 }
89
90 bool NewDebugMode = M.IsNewDbgInfoFormat;
91 if (NewDebugMode)
92 M.convertFromNewDbgValues();
93
94 DIBuilder DIB(M);
95 LLVMContext &Ctx = M.getContext();
96 auto *Int32Ty = Type::getInt32Ty(Ctx);
97
98 // Get a DIType which corresponds to Ty.
100 auto getCachedDIType = [&](Type *Ty) -> DIType * {
101 uint64_t Size = getAllocSizeInBits(M, Ty);
102 DIType *&DTy = TypeCache[Size];
103 if (!DTy) {
104 std::string Name = "ty" + utostr(Size);
105 DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
106 }
107 return DTy;
108 };
109
110 unsigned NextLine = 1;
111 unsigned NextVar = 1;
112 auto File = DIB.createFile(M.getName(), "/");
113 auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
114 /*isOptimized=*/true, "", 0);
115
116 // Visit each instruction.
117 for (Function &F : Functions) {
118 if (isFunctionSkipped(F))
119 continue;
120
121 bool InsertedDbgVal = false;
122 auto SPType =
123 DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
125 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
126 if (F.hasPrivateLinkage() || F.hasInternalLinkage())
127 SPFlags |= DISubprogram::SPFlagLocalToUnit;
128 auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
129 SPType, NextLine, DINode::FlagZero, SPFlags);
130 F.setSubprogram(SP);
131
132 // Helper that inserts a dbg.value before \p InsertBefore, copying the
133 // location (and possibly the type, if it's non-void) from \p TemplateInst.
134 auto insertDbgVal = [&](Instruction &TemplateInst,
135 Instruction *InsertBefore) {
136 std::string Name = utostr(NextVar++);
137 Value *V = &TemplateInst;
138 if (TemplateInst.getType()->isVoidTy())
139 V = ConstantInt::get(Int32Ty, 0);
140 const DILocation *Loc = TemplateInst.getDebugLoc().get();
141 auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
142 getCachedDIType(V->getType()),
143 /*AlwaysPreserve=*/true);
144 DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
145 InsertBefore);
146 };
147
148 for (BasicBlock &BB : F) {
149 // Attach debug locations.
150 for (Instruction &I : BB)
151 I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
152
153 if (DebugifyLevel < Level::LocationsAndVariables)
154 continue;
155
156 // Inserting debug values into EH pads can break IR invariants.
157 if (BB.isEHPad())
158 continue;
159
160 // Find the terminating instruction, after which no debug values are
161 // attached.
162 Instruction *LastInst = findTerminatingInstruction(BB);
163 assert(LastInst && "Expected basic block with a terminator");
164
165 // Maintain an insertion point which can't be invalidated when updates
166 // are made.
167 BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
168 assert(InsertPt != BB.end() && "Expected to find an insertion point");
169 Instruction *InsertBefore = &*InsertPt;
170
171 // Attach debug values.
172 for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
173 // Skip void-valued instructions.
174 if (I->getType()->isVoidTy())
175 continue;
176
177 // Phis and EH pads must be grouped at the beginning of the block.
178 // Only advance the insertion point when we finish visiting these.
179 if (!isa<PHINode>(I) && !I->isEHPad())
180 InsertBefore = I->getNextNode();
181
182 insertDbgVal(*I, InsertBefore);
183 InsertedDbgVal = true;
184 }
185 }
186 // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
187 // not have anything to work with as it goes about inserting DBG_VALUEs.
188 // (It's common for MIR tests to be written containing skeletal IR with
189 // empty functions -- we're still interested in debugifying the MIR within
190 // those tests, and this helps with that.)
191 if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
192 auto *Term = findTerminatingInstruction(F.getEntryBlock());
193 insertDbgVal(*Term, Term);
194 }
195 if (ApplyToMF)
196 ApplyToMF(DIB, F);
197 DIB.finalizeSubprogram(SP);
198 }
199 DIB.finalize();
200
201 // Track the number of distinct lines and variables.
202 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
203 auto addDebugifyOperand = [&](unsigned N) {
205 Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
206 };
207 addDebugifyOperand(NextLine - 1); // Original number of lines.
208 addDebugifyOperand(NextVar - 1); // Original number of variables.
209 assert(NMD->getNumOperands() == 2 &&
210 "llvm.debugify should have exactly 2 operands!");
211
212 // Claim that this synthetic debug info is valid.
213 StringRef DIVersionKey = "Debug Info Version";
214 if (!M.getModuleFlag(DIVersionKey))
215 M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
216
217 if (NewDebugMode)
218 M.convertToNewDbgValues();
219
220 return true;
221}
222
223static bool
226 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
227 StringRef NameOfWrappedPass = "") {
228 Module &M = *F.getParent();
229 auto FuncIt = F.getIterator();
231 return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
232 "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
233 assert(DebugInfoBeforePass);
234 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
235 "FunctionDebugify (original debuginfo)",
236 NameOfWrappedPass);
237}
238
239static bool
242 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
243 StringRef NameOfWrappedPass = "") {
245 return applyDebugifyMetadata(M, M.functions(),
246 "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
247 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
248 "ModuleDebugify (original debuginfo)",
249 NameOfWrappedPass);
250}
251
253 bool Changed = false;
254
255 // Remove the llvm.debugify and llvm.mir.debugify module-level named metadata.
256 NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
257 if (DebugifyMD) {
258 M.eraseNamedMetadata(DebugifyMD);
259 Changed = true;
260 }
261
262 if (auto *MIRDebugifyMD = M.getNamedMetadata("llvm.mir.debugify")) {
263 M.eraseNamedMetadata(MIRDebugifyMD);
264 Changed = true;
265 }
266
267 // Strip out all debug intrinsics and supporting metadata (subprograms, types,
268 // variables, etc).
269 Changed |= StripDebugInfo(M);
270
271 // Strip out the dead dbg.value prototype.
272 Function *DbgValF = M.getFunction("llvm.dbg.value");
273 if (DbgValF) {
274 assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
275 "Not all debug info stripped?");
276 DbgValF->eraseFromParent();
277 Changed = true;
278 }
279
280 // Strip out the module-level Debug Info Version metadata.
281 // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
282 NamedMDNode *NMD = M.getModuleFlagsMetadata();
283 if (!NMD)
284 return Changed;
286 NMD->clearOperands();
287 for (MDNode *Flag : Flags) {
288 auto *Key = cast<MDString>(Flag->getOperand(1));
289 if (Key->getString() == "Debug Info Version") {
290 Changed = true;
291 continue;
292 }
293 NMD->addOperand(Flag);
294 }
295 // If we left it empty we might as well remove it.
296 if (NMD->getNumOperands() == 0)
297 NMD->eraseFromParent();
298
299 return Changed;
300}
301
304 DebugInfoPerPass &DebugInfoBeforePass,
305 StringRef Banner,
306 StringRef NameOfWrappedPass) {
307 LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
308
309 if (!M.getNamedMetadata("llvm.dbg.cu")) {
310 dbg() << Banner << ": Skipping module without debug info\n";
311 return false;
312 }
313
314 bool NewDebugMode = M.IsNewDbgInfoFormat;
315 if (NewDebugMode)
316 M.convertFromNewDbgValues();
317
318 uint64_t FunctionsCnt = DebugInfoBeforePass.DIFunctions.size();
319 // Visit each instruction.
320 for (Function &F : Functions) {
321 // Use DI collected after previous Pass (when -debugify-each is used).
322 if (DebugInfoBeforePass.DIFunctions.count(&F))
323 continue;
324
325 if (isFunctionSkipped(F))
326 continue;
327
328 // Stop collecting DI if the Functions number reached the limit.
329 if (++FunctionsCnt >= DebugifyFunctionsLimit)
330 break;
331 // Collect the DISubprogram.
332 auto *SP = F.getSubprogram();
333 DebugInfoBeforePass.DIFunctions.insert({&F, SP});
334 if (SP) {
335 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
336 for (const DINode *DN : SP->getRetainedNodes()) {
337 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
338 DebugInfoBeforePass.DIVariables[DV] = 0;
339 }
340 }
341 }
342
343 for (BasicBlock &BB : F) {
344 // Collect debug locations (!dbg) and debug variable intrinsics.
345 for (Instruction &I : BB) {
346 // Skip PHIs.
347 if (isa<PHINode>(I))
348 continue;
349
350 // Cllect dbg.values and dbg.declare.
351 if (DebugifyLevel > Level::Locations) {
352 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) {
353 if (!SP)
354 continue;
355 // Skip inlined variables.
356 if (I.getDebugLoc().getInlinedAt())
357 continue;
358 // Skip undef values.
359 if (DVI->isKillLocation())
360 continue;
361
362 auto *Var = DVI->getVariable();
363 DebugInfoBeforePass.DIVariables[Var]++;
364 continue;
365 }
366 }
367
368 // Skip debug instructions other than dbg.value and dbg.declare.
369 if (isa<DbgInfoIntrinsic>(&I))
370 continue;
371
372 LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
373 DebugInfoBeforePass.InstToDelete.insert({&I, &I});
374
375 const DILocation *Loc = I.getDebugLoc().get();
376 bool HasLoc = Loc != nullptr;
377 DebugInfoBeforePass.DILocations.insert({&I, HasLoc});
378 }
379 }
380 }
381
382 if (NewDebugMode)
383 M.convertToNewDbgValues();
384
385 return true;
386}
387
388// This checks the preservation of original debug info attached to functions.
389static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
390 const DebugFnMap &DIFunctionsAfter,
391 StringRef NameOfWrappedPass,
392 StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
393 llvm::json::Array &Bugs) {
394 bool Preserved = true;
395 for (const auto &F : DIFunctionsAfter) {
396 if (F.second)
397 continue;
398 auto SPIt = DIFunctionsBefore.find(F.first);
399 if (SPIt == DIFunctionsBefore.end()) {
400 if (ShouldWriteIntoJSON)
401 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
402 {"name", F.first->getName()},
403 {"action", "not-generate"}}));
404 else
405 dbg() << "ERROR: " << NameOfWrappedPass
406 << " did not generate DISubprogram for " << F.first->getName()
407 << " from " << FileNameFromCU << '\n';
408 Preserved = false;
409 } else {
410 auto SP = SPIt->second;
411 if (!SP)
412 continue;
413 // If the function had the SP attached before the pass, consider it as
414 // a debug info bug.
415 if (ShouldWriteIntoJSON)
416 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
417 {"name", F.first->getName()},
418 {"action", "drop"}}));
419 else
420 dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
421 << F.first->getName() << " from " << FileNameFromCU << '\n';
422 Preserved = false;
423 }
424 }
425
426 return Preserved;
427}
428
429// This checks the preservation of the original debug info attached to
430// instructions.
431static bool checkInstructions(const DebugInstMap &DILocsBefore,
432 const DebugInstMap &DILocsAfter,
433 const WeakInstValueMap &InstToDelete,
434 StringRef NameOfWrappedPass,
435 StringRef FileNameFromCU,
436 bool ShouldWriteIntoJSON,
437 llvm::json::Array &Bugs) {
438 bool Preserved = true;
439 for (const auto &L : DILocsAfter) {
440 if (L.second)
441 continue;
442 auto Instr = L.first;
443
444 // In order to avoid pointer reuse/recycling, skip the values that might
445 // have been deleted during a pass.
446 auto WeakInstrPtr = InstToDelete.find(Instr);
447 if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second)
448 continue;
449
450 auto FnName = Instr->getFunction()->getName();
451 auto BB = Instr->getParent();
452 auto BBName = BB->hasName() ? BB->getName() : "no-name";
453 auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
454
455 auto InstrIt = DILocsBefore.find(Instr);
456 if (InstrIt == DILocsBefore.end()) {
457 if (ShouldWriteIntoJSON)
458 Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
459 {"fn-name", FnName.str()},
460 {"bb-name", BBName.str()},
461 {"instr", InstName},
462 {"action", "not-generate"}}));
463 else
464 dbg() << "WARNING: " << NameOfWrappedPass
465 << " did not generate DILocation for " << *Instr
466 << " (BB: " << BBName << ", Fn: " << FnName
467 << ", File: " << FileNameFromCU << ")\n";
468 Preserved = false;
469 } else {
470 if (!InstrIt->second)
471 continue;
472 // If the instr had the !dbg attached before the pass, consider it as
473 // a debug info issue.
474 if (ShouldWriteIntoJSON)
475 Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
476 {"fn-name", FnName.str()},
477 {"bb-name", BBName.str()},
478 {"instr", InstName},
479 {"action", "drop"}}));
480 else
481 dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of "
482 << *Instr << " (BB: " << BBName << ", Fn: " << FnName
483 << ", File: " << FileNameFromCU << ")\n";
484 Preserved = false;
485 }
486 }
487
488 return Preserved;
489}
490
491// This checks the preservation of original debug variable intrinsics.
492static bool checkVars(const DebugVarMap &DIVarsBefore,
493 const DebugVarMap &DIVarsAfter,
494 StringRef NameOfWrappedPass, StringRef FileNameFromCU,
495 bool ShouldWriteIntoJSON, llvm::json::Array &Bugs) {
496 bool Preserved = true;
497 for (const auto &V : DIVarsBefore) {
498 auto VarIt = DIVarsAfter.find(V.first);
499 if (VarIt == DIVarsAfter.end())
500 continue;
501
502 unsigned NumOfDbgValsAfter = VarIt->second;
503
504 if (V.second > NumOfDbgValsAfter) {
505 if (ShouldWriteIntoJSON)
507 {{"metadata", "dbg-var-intrinsic"},
508 {"name", V.first->getName()},
509 {"fn-name", V.first->getScope()->getSubprogram()->getName()},
510 {"action", "drop"}}));
511 else
512 dbg() << "WARNING: " << NameOfWrappedPass
513 << " drops dbg.value()/dbg.declare() for " << V.first->getName()
514 << " from "
515 << "function " << V.first->getScope()->getSubprogram()->getName()
516 << " (file " << FileNameFromCU << ")\n";
517 Preserved = false;
518 }
519 }
520
521 return Preserved;
522}
523
524// Write the json data into the specifed file.
525static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
526 StringRef FileNameFromCU, StringRef NameOfWrappedPass,
527 llvm::json::Array &Bugs) {
528 std::error_code EC;
529 raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
531 if (EC) {
532 errs() << "Could not open file: " << EC.message() << ", "
533 << OrigDIVerifyBugsReportFilePath << '\n';
534 return;
535 }
536
537 if (auto L = OS_FILE.lock()) {
538 OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
539
541 NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
542 OS_FILE << "\"pass\":\"" << PassName << "\", ";
543
544 llvm::json::Value BugsToPrint{std::move(Bugs)};
545 OS_FILE << "\"bugs\": " << BugsToPrint;
546
547 OS_FILE << "}\n";
548 }
549 OS_FILE.close();
550}
551
554 DebugInfoPerPass &DebugInfoBeforePass,
555 StringRef Banner, StringRef NameOfWrappedPass,
556 StringRef OrigDIVerifyBugsReportFilePath) {
557 LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
558
559 if (!M.getNamedMetadata("llvm.dbg.cu")) {
560 dbg() << Banner << ": Skipping module without debug info\n";
561 return false;
562 }
563
564 bool NewDebugMode = M.IsNewDbgInfoFormat;
565 if (NewDebugMode)
566 M.convertFromNewDbgValues();
567
568 // Map the debug info holding DIs after a pass.
569 DebugInfoPerPass DebugInfoAfterPass;
570
571 // Visit each instruction.
572 for (Function &F : Functions) {
573 if (isFunctionSkipped(F))
574 continue;
575
576 // Don't process functions without DI collected before the Pass.
577 if (!DebugInfoBeforePass.DIFunctions.count(&F))
578 continue;
579 // TODO: Collect metadata other than DISubprograms.
580 // Collect the DISubprogram.
581 auto *SP = F.getSubprogram();
582 DebugInfoAfterPass.DIFunctions.insert({&F, SP});
583
584 if (SP) {
585 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
586 for (const DINode *DN : SP->getRetainedNodes()) {
587 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
588 DebugInfoAfterPass.DIVariables[DV] = 0;
589 }
590 }
591 }
592
593 for (BasicBlock &BB : F) {
594 // Collect debug locations (!dbg) and debug variable intrinsics.
595 for (Instruction &I : BB) {
596 // Skip PHIs.
597 if (isa<PHINode>(I))
598 continue;
599
600 // Collect dbg.values and dbg.declares.
601 if (DebugifyLevel > Level::Locations) {
602 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) {
603 if (!SP)
604 continue;
605 // Skip inlined variables.
606 if (I.getDebugLoc().getInlinedAt())
607 continue;
608 // Skip undef values.
609 if (DVI->isKillLocation())
610 continue;
611
612 auto *Var = DVI->getVariable();
613 DebugInfoAfterPass.DIVariables[Var]++;
614 continue;
615 }
616 }
617
618 // Skip debug instructions other than dbg.value and dbg.declare.
619 if (isa<DbgInfoIntrinsic>(&I))
620 continue;
621
622 LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
623
624 const DILocation *Loc = I.getDebugLoc().get();
625 bool HasLoc = Loc != nullptr;
626
627 DebugInfoAfterPass.DILocations.insert({&I, HasLoc});
628 }
629 }
630 }
631
632 // TODO: The name of the module could be read better?
633 StringRef FileNameFromCU =
634 (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
635 ->getFilename();
636
637 auto DIFunctionsBefore = DebugInfoBeforePass.DIFunctions;
638 auto DIFunctionsAfter = DebugInfoAfterPass.DIFunctions;
639
640 auto DILocsBefore = DebugInfoBeforePass.DILocations;
641 auto DILocsAfter = DebugInfoAfterPass.DILocations;
642
643 auto InstToDelete = DebugInfoBeforePass.InstToDelete;
644
645 auto DIVarsBefore = DebugInfoBeforePass.DIVariables;
646 auto DIVarsAfter = DebugInfoAfterPass.DIVariables;
647
648 bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
650
651 bool ResultForFunc =
652 checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
653 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
654 bool ResultForInsts = checkInstructions(
655 DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass,
656 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
657
658 bool ResultForVars = checkVars(DIVarsBefore, DIVarsAfter, NameOfWrappedPass,
659 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
660
661 bool Result = ResultForFunc && ResultForInsts && ResultForVars;
662
663 StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
664 if (ShouldWriteIntoJSON && !Bugs.empty())
665 writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
666 Bugs);
667
668 if (Result)
669 dbg() << ResultBanner << ": PASS\n";
670 else
671 dbg() << ResultBanner << ": FAIL\n";
672
673 // In the case of the `debugify-each`, no need to go over all the instructions
674 // again in the collectDebugInfoMetadata(), since as an input we can use
675 // the debugging information from the previous pass.
676 DebugInfoBeforePass = DebugInfoAfterPass;
677
678 if (NewDebugMode)
679 M.convertToNewDbgValues();
680
681 LLVM_DEBUG(dbgs() << "\n\n");
682 return Result;
683}
684
685namespace {
686/// Return true if a mis-sized diagnostic is issued for \p DVI.
687bool diagnoseMisSizedDbgValue(Module &M, DbgValueInst *DVI) {
688 // The size of a dbg.value's value operand should match the size of the
689 // variable it corresponds to.
690 //
691 // TODO: This, along with a check for non-null value operands, should be
692 // promoted to verifier failures.
693
694 // For now, don't try to interpret anything more complicated than an empty
695 // DIExpression. Eventually we should try to handle OP_deref and fragments.
696 if (DVI->getExpression()->getNumElements())
697 return false;
698
699 Value *V = DVI->getVariableLocationOp(0);
700 if (!V)
701 return false;
702
703 Type *Ty = V->getType();
704 uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
705 std::optional<uint64_t> DbgVarSize = DVI->getFragmentSizeInBits();
706 if (!ValueOperandSize || !DbgVarSize)
707 return false;
708
709 bool HasBadSize = false;
710 if (Ty->isIntegerTy()) {
711 auto Signedness = DVI->getVariable()->getSignedness();
712 if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
713 HasBadSize = ValueOperandSize < *DbgVarSize;
714 } else {
715 HasBadSize = ValueOperandSize != *DbgVarSize;
716 }
717
718 if (HasBadSize) {
719 dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
720 << ", but its variable has size " << *DbgVarSize << ": ";
721 DVI->print(dbg());
722 dbg() << "\n";
723 }
724 return HasBadSize;
725}
726
727bool checkDebugifyMetadata(Module &M,
729 StringRef NameOfWrappedPass, StringRef Banner,
730 bool Strip, DebugifyStatsMap *StatsMap) {
731 // Skip modules without debugify metadata.
732 NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
733 if (!NMD) {
734 dbg() << Banner << ": Skipping module without debugify metadata\n";
735 return false;
736 }
737
738 bool NewDebugMode = M.IsNewDbgInfoFormat;
739 if (NewDebugMode)
740 M.convertFromNewDbgValues();
741
742 auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
743 return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
744 ->getZExtValue();
745 };
746 assert(NMD->getNumOperands() == 2 &&
747 "llvm.debugify should have exactly 2 operands!");
748 unsigned OriginalNumLines = getDebugifyOperand(0);
749 unsigned OriginalNumVars = getDebugifyOperand(1);
750 bool HasErrors = false;
751
752 // Track debug info loss statistics if able.
753 DebugifyStatistics *Stats = nullptr;
754 if (StatsMap && !NameOfWrappedPass.empty())
755 Stats = &StatsMap->operator[](NameOfWrappedPass);
756
757 BitVector MissingLines{OriginalNumLines, true};
758 BitVector MissingVars{OriginalNumVars, true};
759 for (Function &F : Functions) {
760 if (isFunctionSkipped(F))
761 continue;
762
763 // Find missing lines.
764 for (Instruction &I : instructions(F)) {
765 if (isa<DbgValueInst>(&I))
766 continue;
767
768 auto DL = I.getDebugLoc();
769 if (DL && DL.getLine() != 0) {
770 MissingLines.reset(DL.getLine() - 1);
771 continue;
772 }
773
774 if (!isa<PHINode>(&I) && !DL) {
775 dbg() << "WARNING: Instruction with empty DebugLoc in function ";
776 dbg() << F.getName() << " --";
777 I.print(dbg());
778 dbg() << "\n";
779 }
780 }
781
782 // Find missing variables and mis-sized debug values.
783 for (Instruction &I : instructions(F)) {
784 auto *DVI = dyn_cast<DbgValueInst>(&I);
785 if (!DVI)
786 continue;
787
788 unsigned Var = ~0U;
789 (void)to_integer(DVI->getVariable()->getName(), Var, 10);
790 assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
791 bool HasBadSize = diagnoseMisSizedDbgValue(M, DVI);
792 if (!HasBadSize)
793 MissingVars.reset(Var - 1);
794 HasErrors |= HasBadSize;
795 }
796 }
797
798 // Print the results.
799 for (unsigned Idx : MissingLines.set_bits())
800 dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
801
802 for (unsigned Idx : MissingVars.set_bits())
803 dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
804
805 // Update DI loss statistics.
806 if (Stats) {
807 Stats->NumDbgLocsExpected += OriginalNumLines;
808 Stats->NumDbgLocsMissing += MissingLines.count();
809 Stats->NumDbgValuesExpected += OriginalNumVars;
810 Stats->NumDbgValuesMissing += MissingVars.count();
811 }
812
813 dbg() << Banner;
814 if (!NameOfWrappedPass.empty())
815 dbg() << " [" << NameOfWrappedPass << "]";
816 dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
817
818 // Strip debugify metadata if required.
819 bool Ret = false;
820 if (Strip)
822
823 if (NewDebugMode)
824 M.convertToNewDbgValues();
825
826 return Ret;
827}
828
829/// ModulePass for attaching synthetic debug info to everything, used with the
830/// legacy module pass manager.
831struct DebugifyModulePass : public ModulePass {
832 bool runOnModule(Module &M) override {
833 bool Result =
834 applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass);
835 return Result;
836 }
837
838 DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
839 StringRef NameOfWrappedPass = "",
840 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
841 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
842 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
843
844 void getAnalysisUsage(AnalysisUsage &AU) const override {
845 AU.setPreservesAll();
846 }
847
848 static char ID; // Pass identification.
849
850private:
851 StringRef NameOfWrappedPass;
852 DebugInfoPerPass *DebugInfoBeforePass;
853 enum DebugifyMode Mode;
854};
855
856/// FunctionPass for attaching synthetic debug info to instructions within a
857/// single function, used with the legacy module pass manager.
858struct DebugifyFunctionPass : public FunctionPass {
859 bool runOnFunction(Function &F) override {
860 bool Result =
861 applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass);
862 return Result;
863 }
864
865 DebugifyFunctionPass(
866 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
867 StringRef NameOfWrappedPass = "",
868 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
869 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
870 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
871
872 void getAnalysisUsage(AnalysisUsage &AU) const override {
873 AU.setPreservesAll();
874 }
875
876 static char ID; // Pass identification.
877
878private:
879 StringRef NameOfWrappedPass;
880 DebugInfoPerPass *DebugInfoBeforePass;
881 enum DebugifyMode Mode;
882};
883
884/// ModulePass for checking debug info inserted by -debugify, used with the
885/// legacy module pass manager.
886struct CheckDebugifyModulePass : public ModulePass {
887 bool runOnModule(Module &M) override {
888 bool Result;
889 if (Mode == DebugifyMode::SyntheticDebugInfo)
890 Result = checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
891 "CheckModuleDebugify", Strip, StatsMap);
892 else
894 M, M.functions(), *DebugInfoBeforePass,
895 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
896 OrigDIVerifyBugsReportFilePath);
897
898 return Result;
899 }
900
901 CheckDebugifyModulePass(
902 bool Strip = false, StringRef NameOfWrappedPass = "",
903 DebugifyStatsMap *StatsMap = nullptr,
904 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
905 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
906 StringRef OrigDIVerifyBugsReportFilePath = "")
907 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
908 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
909 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
910 Strip(Strip) {}
911
912 void getAnalysisUsage(AnalysisUsage &AU) const override {
913 AU.setPreservesAll();
914 }
915
916 static char ID; // Pass identification.
917
918private:
919 StringRef NameOfWrappedPass;
920 StringRef OrigDIVerifyBugsReportFilePath;
921 DebugifyStatsMap *StatsMap;
922 DebugInfoPerPass *DebugInfoBeforePass;
923 enum DebugifyMode Mode;
924 bool Strip;
925};
926
927/// FunctionPass for checking debug info inserted by -debugify-function, used
928/// with the legacy module pass manager.
929struct CheckDebugifyFunctionPass : public FunctionPass {
930 bool runOnFunction(Function &F) override {
931 Module &M = *F.getParent();
932 auto FuncIt = F.getIterator();
933 bool Result;
934 if (Mode == DebugifyMode::SyntheticDebugInfo)
935 Result = checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
936 NameOfWrappedPass, "CheckFunctionDebugify",
937 Strip, StatsMap);
938 else
940 M, make_range(FuncIt, std::next(FuncIt)), *DebugInfoBeforePass,
941 "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
942 OrigDIVerifyBugsReportFilePath);
943
944 return Result;
945 }
946
947 CheckDebugifyFunctionPass(
948 bool Strip = false, StringRef NameOfWrappedPass = "",
949 DebugifyStatsMap *StatsMap = nullptr,
950 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
951 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
952 StringRef OrigDIVerifyBugsReportFilePath = "")
953 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
954 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
955 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
956 Strip(Strip) {}
957
958 void getAnalysisUsage(AnalysisUsage &AU) const override {
959 AU.setPreservesAll();
960 }
961
962 static char ID; // Pass identification.
963
964private:
965 StringRef NameOfWrappedPass;
966 StringRef OrigDIVerifyBugsReportFilePath;
967 DebugifyStatsMap *StatsMap;
968 DebugInfoPerPass *DebugInfoBeforePass;
969 enum DebugifyMode Mode;
970 bool Strip;
971};
972
973} // end anonymous namespace
974
976 std::error_code EC;
977 raw_fd_ostream OS{Path, EC};
978 if (EC) {
979 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
980 return;
981 }
982
983 OS << "Pass Name" << ',' << "# of missing debug values" << ','
984 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
985 << "Missing/Expected location ratio" << '\n';
986 for (const auto &Entry : Map) {
987 StringRef Pass = Entry.first;
988 DebugifyStatistics Stats = Entry.second;
989
990 OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
991 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
992 << Stats.getEmptyLocationRatio() << '\n';
993 }
994}
995
997 llvm::StringRef NameOfWrappedPass,
998 DebugInfoPerPass *DebugInfoBeforePass) {
1000 return new DebugifyModulePass();
1001 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1002 return new DebugifyModulePass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
1003}
1004
1007 llvm::StringRef NameOfWrappedPass,
1008 DebugInfoPerPass *DebugInfoBeforePass) {
1010 return new DebugifyFunctionPass();
1011 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1012 return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
1013}
1014
1016 if (Mode == DebugifyMode::SyntheticDebugInfo)
1017 applyDebugifyMetadata(M, M.functions(),
1018 "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
1019 else
1020 collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1021 "ModuleDebugify (original debuginfo)",
1022 NameOfWrappedPass);
1023
1026 return PA;
1027}
1028
1030 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1031 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1032 StringRef OrigDIVerifyBugsReportFilePath) {
1034 return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
1035 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1036 return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
1037 DebugInfoBeforePass,
1038 OrigDIVerifyBugsReportFilePath);
1039}
1040
1042 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1043 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1044 StringRef OrigDIVerifyBugsReportFilePath) {
1046 return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
1047 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1048 return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
1049 DebugInfoBeforePass,
1050 OrigDIVerifyBugsReportFilePath);
1051}
1052
1055 bool NewDebugMode = M.IsNewDbgInfoFormat;
1056 if (NewDebugMode)
1057 M.convertFromNewDbgValues();
1058
1059 if (Mode == DebugifyMode::SyntheticDebugInfo)
1060 checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
1061 "CheckModuleDebugify", Strip, StatsMap);
1062 else
1064 M, M.functions(), *DebugInfoBeforePass,
1065 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
1066 OrigDIVerifyBugsReportFilePath);
1067
1068 if (NewDebugMode)
1069 M.convertToNewDbgValues();
1070
1071 return PreservedAnalyses::all();
1072}
1073
1074static bool isIgnoredPass(StringRef PassID) {
1075 return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
1076 "AnalysisManagerProxy", "PrintFunctionPass",
1077 "PrintModulePass", "BitcodeWriterPass",
1078 "ThinLTOBitcodeWriterPass", "VerifierPass"});
1079}
1080
1084 if (isIgnoredPass(P))
1085 return;
1088 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1089 Function &F = *const_cast<Function *>(*CF);
1090 applyDebugify(F, Mode, DebugInfoBeforePass, P);
1092 .getManager()
1093 .invalidate(F, PA);
1094 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1095 Module &M = *const_cast<Module *>(*CM);
1096 applyDebugify(M, Mode, DebugInfoBeforePass, P);
1097 MAM.invalidate(M, PA);
1098 }
1099 });
1101 [this, &MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1102 if (isIgnoredPass(P))
1103 return;
1106 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1107 auto &F = *const_cast<Function *>(*CF);
1108 Module &M = *F.getParent();
1109 auto It = F.getIterator();
1110 if (Mode == DebugifyMode::SyntheticDebugInfo)
1111 checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
1112 "CheckFunctionDebugify", /*Strip=*/true,
1113 DIStatsMap);
1114 else
1115 checkDebugInfoMetadata(M, make_range(It, std::next(It)),
1116 *DebugInfoBeforePass,
1117 "CheckModuleDebugify (original debuginfo)",
1118 P, OrigDIVerifyBugsReportFilePath);
1120 .getManager()
1121 .invalidate(F, PA);
1122 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1123 Module &M = *const_cast<Module *>(*CM);
1124 if (Mode == DebugifyMode::SyntheticDebugInfo)
1125 checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
1126 /*Strip=*/true, DIStatsMap);
1127 else
1128 checkDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1129 "CheckModuleDebugify (original debuginfo)",
1130 P, OrigDIVerifyBugsReportFilePath);
1131 MAM.invalidate(M, PA);
1132 }
1133 });
1134}
1135
1136char DebugifyModulePass::ID = 0;
1138 "Attach debug info to everything");
1139
1140char CheckDebugifyModulePass::ID = 0;
1142 CDM("check-debugify", "Check debug info from -debugify");
1143
1144char DebugifyFunctionPass::ID = 0;
1145static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
1146 "Attach debug info to a function");
1147
1148char CheckDebugifyFunctionPass::ID = 0;
1150 CDF("check-debugify-function", "Check debug info from -debugify-function");
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file implements the BitVector class.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:693
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
Definition: DIBuilder.cpp:838
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static RegisterPass< CheckDebugifyModulePass > CDM("check-debugify", "Check debug info from -debugify")
ModulePass * createDebugifyModulePass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
Definition: Debugify.cpp:996
FunctionPass * createDebugifyFunctionPass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
Definition: Debugify.cpp:1006
static bool isIgnoredPass(StringRef PassID)
Definition: Debugify.cpp:1074
static bool applyDebugify(Function &F, enum DebugifyMode Mode=DebugifyMode::SyntheticDebugInfo, DebugInfoPerPass *DebugInfoBeforePass=nullptr, StringRef NameOfWrappedPass="")
Definition: Debugify.cpp:224
ModulePass * createCheckDebugifyModulePass(bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef OrigDIVerifyBugsReportFilePath)
Definition: Debugify.cpp:1029
static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath, StringRef FileNameFromCU, StringRef NameOfWrappedPass, llvm::json::Array &Bugs)
Definition: Debugify.cpp:525
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
static bool checkFunctions(const DebugFnMap &DIFunctionsBefore, const DebugFnMap &DIFunctionsAfter, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:389
static RegisterPass< CheckDebugifyFunctionPass > CDF("check-debugify-function", "Check debug info from -debugify-function")
FunctionPass * createCheckDebugifyFunctionPass(bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef OrigDIVerifyBugsReportFilePath)
Definition: Debugify.cpp:1041
static bool checkVars(const DebugVarMap &DIVarsBefore, const DebugVarMap &DIVarsAfter, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:492
static bool checkInstructions(const DebugInstMap &DILocsBefore, const DebugInstMap &DILocsAfter, const WeakInstValueMap &InstToDelete, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:431
DebugifyMode
Used to check whether we track synthetic or original debug info.
Definition: Debugify.h:93
std::string Name
uint64_t Size
static SmallString< 128 > getFilename(const DISubprogram *SP)
Extract a filename for a DISubprogram.
This file supports working with JSON data.
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:81
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
block placement Basic Block Placement Stats
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
#define P(N)
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
static const char PassName[]
llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
Definition: Debugify.cpp:1053
llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
Definition: Debugify.cpp:1015
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Definition: Any.h:28
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:324
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:221
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:293
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
void finalize()
Construct any deferred debug info descriptors.
Definition: DIBuilder.cpp:64
DISubroutineType * createSubroutineType(DITypeRefArray ParameterTypes, DINode::DIFlags Flags=DINode::FlagZero, unsigned CC=0)
Create subroutine type.
Definition: DIBuilder.cpp:548
void finalizeSubprogram(DISubprogram *SP)
Finalize a specific subprogram - no new variables may be added to this subprogram afterwards.
Definition: DIBuilder.cpp:56
DICompileUnit * createCompileUnit(unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RV, StringRef SplitName=StringRef(), DICompileUnit::DebugEmissionKind Kind=DICompileUnit::DebugEmissionKind::FullDebug, uint64_t DWOId=0, bool SplitDebugInlining=true, bool DebugInfoForProfiling=false, DICompileUnit::DebugNameTableKind NameTableKind=DICompileUnit::DebugNameTableKind::Default, bool RangesBaseAddress=false, StringRef SysRoot={}, StringRef SDK={})
A CompileUnit provides an anchor for all debugging information generated during this instance of comp...
Definition: DIBuilder.cpp:135
DISubprogram * createFunction(DIScope *Scope, StringRef Name, StringRef LinkageName, DIFile *File, unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine, DINode::DIFlags Flags=DINode::FlagZero, DISubprogram::DISPFlags SPFlags=DISubprogram::SPFlagZero, DITemplateParameterArray TParams=nullptr, DISubprogram *Decl=nullptr, DITypeArray ThrownTypes=nullptr, DINodeArray Annotations=nullptr, StringRef TargetFuncName="")
Create a new descriptor for the specified subprogram.
Definition: DIBuilder.cpp:844
DIExpression * createExpression(ArrayRef< uint64_t > Addr=std::nullopt)
Create a new descriptor for the specified variable which has a complex address expression for its add...
Definition: DIBuilder.cpp:833
DIBasicType * createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding, DINode::DIFlags Flags=DINode::FlagZero)
Create debugging information entry for a basic type.
Definition: DIBuilder.cpp:267
DITypeRefArray getOrCreateTypeArray(ArrayRef< Metadata * > Elements)
Get a DITypeRefArray, create one if required.
Definition: DIBuilder.cpp:691
DILocalVariable * createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve=false, DINode::DIFlags Flags=DINode::FlagZero, uint32_t AlignInBits=0)
Create a new descriptor for an auto variable.
Definition: DIBuilder.cpp:795
DIFile * createFile(StringRef Filename, StringRef Directory, std::optional< DIFile::ChecksumInfo< StringRef > > Checksum=std::nullopt, std::optional< StringRef > Source=std::nullopt)
Create a file descriptor to hold debugging information for a file.
Definition: DIBuilder.cpp:215
unsigned getNumElements() const
Debug location.
Tagged DWARF-like metadata node.
DISPFlags
Debug info subprogram flags.
Base class for types.
std::optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or std::nullopt if this type is neither signed nor uns...
StringRef getName() const
This represents the llvm.dbg.value instruction.
Value * getVariableLocationOp(unsigned OpIdx) const
DILocalVariable * getVariable() const
std::optional< uint64_t > getFragmentSizeInBits() const
Get the size (in bits) of the variable, or fragment of the variable that is described.
DIExpression * getExpression() const
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:20
void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM)
Definition: Debugify.cpp:1081
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Function.cpp:403
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:281
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:631
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:454
const char * getOpcodeName() const
Definition: Instruction.h:254
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
size_type count(const KeyT &Key) const
Definition: MapVector.h:165
iterator end()
Definition: MapVector.h:71
iterator find(const KeyT &Key)
Definition: MapVector.h:167
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:141
size_type size() const
Definition: MapVector.h:60
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
@ Warning
Emits a warning if two values disagree.
Definition: Module.h:122
A tuple of MDNodes.
Definition: Metadata.h:1729
void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1395
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1382
unsigned getNumOperands() const
Definition: Metadata.cpp:1378
void clearOperands()
Drop all references to this node's operands.
Definition: Metadata.cpp:1397
iterator_range< op_iterator > operands()
Definition: Metadata.h:1825
void addOperand(MDNode *M)
Definition: Metadata.cpp:1388
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
void registerBeforeNonSkippedPassCallback(CallableT C)
void registerAfterPassCallback(CallableT C, bool ToFront=false)
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:472
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4996
bool use_empty() const
Definition: Value.h:344
A range adaptor for a pair of iterators.
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:164
bool empty() const
Definition: JSON.h:547
void push_back(const Value &E)
Definition: JSON.h:552
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:98
A Value is an JSON value of unknown type.
Definition: JSON.h:288
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:718
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:768
@ OF_Append
The file should be opened in append mode.
Definition: FileSystem.h:771
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool stripDebugifyMetadata(Module &M)
Strip out all of the metadata and debug info inserted by debugify.
Definition: Debugify.cpp:252
void exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map)
Definition: Debugify.cpp:975
bool collectDebugInfoMetadata(Module &M, iterator_range< Module::iterator > Functions, DebugInfoPerPass &DebugInfoBeforePass, StringRef Banner, StringRef NameOfWrappedPass)
Collect original debug information before a pass.
Definition: Debugify.cpp:302
bool checkDebugInfoMetadata(Module &M, iterator_range< Module::iterator > Functions, DebugInfoPerPass &DebugInfoBeforePass, StringRef Banner, StringRef NameOfWrappedPass, StringRef OrigDIVerifyBugsReportFilePath)
Check original debug information after a pass.
Definition: Debugify.cpp:552
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:594
@ DEBUG_METADATA_VERSION
Definition: Metadata.h:52
#define N
Used to track the Debug Info Metadata information.
Definition: Debugify.h:34
DebugInstMap DILocations
Definition: Debugify.h:38
DebugFnMap DIFunctions
Definition: Debugify.h:36
DebugVarMap DIVariables
Definition: Debugify.h:43
WeakInstValueMap InstToDelete
Definition: Debugify.h:41
Track how much debugify information (in the synthetic mode only) has been lost.
Definition: Debugify.h:121
RegisterPass<t> template - This template class is used to notify the system that a Pass is available ...
Definition: PassSupport.h:109