LLVM 23.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/Config/llvm-config.h"
20#include "llvm/IR/DIBuilder.h"
21#include "llvm/IR/DebugInfo.h"
23#include "llvm/IR/DebugLoc.h"
26#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
31#include "llvm/Support/JSON.h"
32#include <optional>
33#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
34// We need the Signals header to operate on stacktraces if we're using DebugLoc
35// origin-tracking.
37#else
39#endif
40
41#define DEBUG_TYPE "debugify"
42
43using namespace llvm;
44
45namespace {
46
47cl::opt<bool> ApplyAtomGroups("debugify-atoms", cl::init(false));
48
49cl::opt<bool> Quiet("debugify-quiet",
50 cl::desc("Suppress verbose debugify output"));
51
52cl::opt<uint64_t> DebugifyFunctionsLimit(
53 "debugify-func-limit",
54 cl::desc("Set max number of processed functions per pass."),
55 cl::init(UINT_MAX));
56
57enum class Level {
58 Locations,
59 LocationsAndVariables
60};
61
62cl::opt<Level> DebugifyLevel(
63 "debugify-level", cl::desc("Kind of debug info to add"),
64 cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
65 clEnumValN(Level::LocationsAndVariables, "location+variables",
66 "Locations and Variables")),
67 cl::init(Level::LocationsAndVariables));
68
69raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
70
71#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
72cl::list<std::string> EnableOriginStacktraces(
73 "enable-origin-stacktraces",
74 cl::desc("Collect DebugLoc origin stacktraces; a comma-separated list of "
75 "passes may be given, in which case stacktraces will be collected "
76 "in those passes only"),
77 cl::value_desc("Pass1,Pass2,Pass3,..."), cl::CommaSeparated,
79
80// For a given pass, sets whether the collection of DebugLoc origin stacktraces
81// is enabled or not.
82static void setDebugLocOriginCollectionForPass(StringRef PassName) {
83 if (!EnableOriginStacktraces.getNumOccurrences()) {
84 llvm::DebugLocOriginCollectionEnabled = false;
85 return;
86 }
87 if (EnableOriginStacktraces.size() == 1 &&
88 EnableOriginStacktraces[0].empty()) {
89 llvm::DebugLocOriginCollectionEnabled = true;
90 return;
91 }
92 llvm::DebugLocOriginCollectionEnabled =
93 llvm::is_contained(EnableOriginStacktraces, PassName);
94}
95static void unsetDebugLocOriginCollection() {
96 llvm::DebugLocOriginCollectionEnabled = false;
97}
98
99// These maps refer to addresses in the current LLVM process, so we can reuse
100// them everywhere - therefore, we store them at file scope.
101static SymbolizedAddressMap SymbolizedAddrs;
102static AddressSet UnsymbolizedAddrs;
103
104std::string symbolizeStackTrace(const Instruction *I) {
105 // We flush the set of unsymbolized addresses at the latest possible moment,
106 // i.e. now.
107 if (!UnsymbolizedAddrs.empty()) {
108 sys::symbolizeAddresses(UnsymbolizedAddrs, SymbolizedAddrs);
109 UnsymbolizedAddrs.clear();
110 }
111 const DbgLocOrigin::StackTracesTy &OriginStackTraces =
112 I->getDebugLoc().getOriginStackTraces();
113 std::string Result;
114 raw_string_ostream OS(Result);
115 for (size_t TraceIdx = 0; TraceIdx < OriginStackTraces.size(); ++TraceIdx) {
116 if (TraceIdx != 0)
117 OS << "========================================\n";
118 auto &[Depth, StackTrace] = OriginStackTraces[TraceIdx];
119 unsigned VirtualFrameNo = 0;
120 for (int Frame = 0; Frame < Depth; ++Frame) {
121 assert(SymbolizedAddrs.contains(StackTrace[Frame]) &&
122 "Expected each address to have been symbolized.");
123 for (std::string &SymbolizedFrame : SymbolizedAddrs[StackTrace[Frame]]) {
124 OS << right_justify(formatv("#{0}", VirtualFrameNo++).str(),
125 std::log10(Depth) + 2)
126 << ' ' << SymbolizedFrame << '\n';
127 }
128 }
129 }
130 return Result;
131}
132void collectStackAddresses(Instruction &I) {
133 auto &OriginStackTraces = I.getDebugLoc().getOriginStackTraces();
134 for (auto &[Depth, StackTrace] : OriginStackTraces) {
135 for (int Frame = 0; Frame < Depth; ++Frame) {
136 void *Addr = StackTrace[Frame];
137 if (!SymbolizedAddrs.contains(Addr))
138 UnsymbolizedAddrs.insert(Addr);
139 }
140 }
141}
142#else
143// These functions are only used in origin-tracking builds; they are no-ops in
144// normal builds.
145static void setDebugLocOriginCollectionForPass(StringRef PassName) {}
146static void unsetDebugLocOriginCollection() {}
147
148cl::list<std::string> EnableOriginStacktraces(
149 "enable-origin-stacktraces",
150 cl::desc("Collect DebugLoc origin stacktraces; requires "
151 "LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING=COVERAGE_AND_ORIGIN"),
153 cl::cb<void, std::string>([](std::string Pass) {
154 WithColor::warning() << "--enable-origin-stacktraces has no effect "
155 "without LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING="
156 "COVERAGE_AND_ORIGIN\n";
157 }));
158
159void collectStackAddresses(Instruction &I) {}
160#endif // LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
161
162uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
163 return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
164}
165
166bool isFunctionSkipped(Function &F) {
167 return F.isDeclaration() || !F.hasExactDefinition();
168}
169
170/// Find the basic block's terminating instruction.
171///
172/// Special care is needed to handle musttail and deopt calls, as these behave
173/// like (but are in fact not) terminators.
174Instruction *findTerminatingInstruction(BasicBlock &BB) {
175 if (auto *I = BB.getTerminatingMustTailCall())
176 return I;
177 if (auto *I = BB.getTerminatingDeoptimizeCall())
178 return I;
179 return BB.getTerminator();
180}
181} // end anonymous namespace
182
185 std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
186 // Skip modules with debug info.
187 if (M.getNamedMetadata("llvm.dbg.cu")) {
188 dbg() << Banner << "Skipping module with debug info\n";
189 return false;
190 }
191
192 DIBuilder DIB(M);
193 LLVMContext &Ctx = M.getContext();
194 auto *Int32Ty = Type::getInt32Ty(Ctx);
195
196 // Get a DIType which corresponds to Ty.
198 auto getCachedDIType = [&](Type *Ty) -> DIType * {
199 uint64_t Size = getAllocSizeInBits(M, Ty);
200 DIType *&DTy = TypeCache[Size];
201 if (!DTy) {
202 std::string Name = "ty" + utostr(Size);
203 DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
204 }
205 return DTy;
206 };
207
208 unsigned NextLine = 1;
209 unsigned NextVar = 1;
210 auto File = DIB.createFile(M.getName(), "/");
211 auto CU = DIB.createCompileUnit(DISourceLanguageName(dwarf::DW_LANG_C), File,
212 "debugify", /*isOptimized=*/true, "", 0);
213
214 // Visit each instruction.
215 for (Function &F : Functions) {
216 if (isFunctionSkipped(F))
217 continue;
218
219 bool InsertedDbgVal = false;
220 auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray({}));
222 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
223 if (F.hasPrivateLinkage() || F.hasInternalLinkage())
224 SPFlags |= DISubprogram::SPFlagLocalToUnit;
225 auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
226 SPType, NextLine, DINode::FlagZero, SPFlags,
227 nullptr, nullptr, nullptr, nullptr, "",
228 /*UseKeyInstructions*/ ApplyAtomGroups);
229 F.setSubprogram(SP);
230
231 // Helper that inserts a dbg.value before \p InsertBefore, copying the
232 // location (and possibly the type, if it's non-void) from \p TemplateInst.
233 auto insertDbgVal = [&](Instruction &TemplateInst,
234 BasicBlock::iterator InsertPt) {
235 std::string Name = utostr(NextVar++);
236 Value *V = &TemplateInst;
237 if (TemplateInst.getType()->isVoidTy())
238 V = ConstantInt::get(Int32Ty, 0);
239 const DILocation *Loc = TemplateInst.getDebugLoc().get();
240 auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
241 getCachedDIType(V->getType()),
242 /*AlwaysPreserve=*/true);
243 DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
244 InsertPt);
245 };
246
247 for (BasicBlock &BB : F) {
248 // Attach debug locations.
249 for (Instruction &I : BB) {
250 uint64_t AtomGroup = ApplyAtomGroups ? NextLine : 0;
251 uint8_t AtomRank = ApplyAtomGroups ? 1 : 0;
252 uint64_t Line = NextLine++;
253 I.setDebugLoc(DILocation::get(Ctx, Line, 1, SP, nullptr, false,
254 AtomGroup, AtomRank));
255 }
256
257 if (DebugifyLevel < Level::LocationsAndVariables)
258 continue;
259
260 // Inserting debug values into EH pads can break IR invariants.
261 if (BB.isEHPad())
262 continue;
263
264 // Find the terminating instruction, after which no debug values are
265 // attached.
266 Instruction *LastInst = findTerminatingInstruction(BB);
267 assert(LastInst && "Expected basic block with a terminator");
268
269 // Maintain an insertion point which can't be invalidated when updates
270 // are made.
271 BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
272 assert(InsertPt != BB.end() && "Expected to find an insertion point");
273
274 // Insert after existing debug values to preserve order.
275 InsertPt.setHeadBit(false);
276
277 // Attach debug values.
278 for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
279 // Skip void-valued instructions.
280 if (I->getType()->isVoidTy())
281 continue;
282
283 // Phis and EH pads must be grouped at the beginning of the block.
284 // Only advance the insertion point when we finish visiting these.
285 if (!isa<PHINode>(I) && !I->isEHPad())
286 InsertPt = std::next(I->getIterator());
287
288 insertDbgVal(*I, InsertPt);
289 InsertedDbgVal = true;
290 }
291 }
292 // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
293 // not have anything to work with as it goes about inserting DBG_VALUEs.
294 // (It's common for MIR tests to be written containing skeletal IR with
295 // empty functions -- we're still interested in debugifying the MIR within
296 // those tests, and this helps with that.)
297 if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
298 auto *Term = findTerminatingInstruction(F.getEntryBlock());
299 insertDbgVal(*Term, Term->getIterator());
300 }
301 if (ApplyToMF)
302 ApplyToMF(DIB, F);
303 }
304 DIB.finalize();
305
306 // Track the number of distinct lines and variables.
307 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
308 auto addDebugifyOperand = [&](unsigned N) {
310 Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
311 };
312 addDebugifyOperand(NextLine - 1); // Original number of lines.
313 addDebugifyOperand(NextVar - 1); // Original number of variables.
314 assert(NMD->getNumOperands() == 2 &&
315 "llvm.debugify should have exactly 2 operands!");
316
317 // Claim that this synthetic debug info is valid.
318 StringRef DIVersionKey = "Debug Info Version";
319 if (!M.getModuleFlag(DIVersionKey))
320 M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
321
322 return true;
323}
324
326 DebugInfoPerPass *DebugInfoBeforePass,
327 StringRef NameOfWrappedPass = "") {
328 setDebugLocOriginCollectionForPass(NameOfWrappedPass);
329 Module &M = *F.getParent();
330 auto FuncIt = F.getIterator();
332 return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
333 "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
334 assert(DebugInfoBeforePass && "Missing debug info metadata");
335 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
336 "FunctionDebugify (original debuginfo)",
337 NameOfWrappedPass);
338}
339
341 DebugInfoPerPass *DebugInfoBeforePass,
342 StringRef NameOfWrappedPass = "") {
343 setDebugLocOriginCollectionForPass(NameOfWrappedPass);
345 return applyDebugifyMetadata(M, M.functions(),
346 "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
347 assert(DebugInfoBeforePass && "Missing debug info metadata");
348 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
349 "ModuleDebugify (original debuginfo)",
350 NameOfWrappedPass);
351}
352
354 bool Changed = false;
355
356 // Remove the llvm.debugify and llvm.mir.debugify module-level named metadata.
357 NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
358 if (DebugifyMD) {
359 M.eraseNamedMetadata(DebugifyMD);
360 Changed = true;
361 }
362
363 if (auto *MIRDebugifyMD = M.getNamedMetadata("llvm.mir.debugify")) {
364 M.eraseNamedMetadata(MIRDebugifyMD);
365 Changed = true;
366 }
367
368 // Strip out all debug intrinsics and supporting metadata (subprograms, types,
369 // variables, etc).
371
372 // Strip out the dead dbg.value prototype.
373 Function *DbgValF = M.getFunction("llvm.dbg.value");
374 if (DbgValF) {
375 assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
376 "Not all debug info stripped?");
377 DbgValF->eraseFromParent();
378 Changed = true;
379 }
380
381 // Strip out the module-level Debug Info Version metadata.
382 // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
383 NamedMDNode *NMD = M.getModuleFlagsMetadata();
384 if (!NMD)
385 return Changed;
387 NMD->clearOperands();
388 for (MDNode *Flag : Flags) {
389 auto *Key = cast<MDString>(Flag->getOperand(1));
390 if (Key->getString() == "Debug Info Version") {
391 Changed = true;
392 continue;
393 }
394 NMD->addOperand(Flag);
395 }
396 // If we left it empty we might as well remove it.
397 if (NMD->getNumOperands() == 0)
398 NMD->eraseFromParent();
399
400 return Changed;
401}
402
403bool hasLoc(const Instruction &I) {
404 const DILocation *Loc = I.getDebugLoc().get();
405#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
406 DebugLocKind Kind = I.getDebugLoc().getKind();
407 return Loc || Kind != DebugLocKind::Normal;
408#else
409 return Loc;
410#endif
411}
412
415 DebugInfoPerPass &DebugInfoBeforePass,
416 StringRef Banner,
417 StringRef NameOfWrappedPass) {
418 LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
419
420 if (!M.getNamedMetadata("llvm.dbg.cu")) {
421 dbg() << Banner << ": Skipping module without debug info\n";
422 return false;
423 }
424
425 uint64_t FunctionsCnt = DebugInfoBeforePass.DIFunctions.size();
426 // Visit each instruction.
427 for (Function &F : Functions) {
428 // Use DI collected after previous Pass (when -debugify-each is used).
429 if (DebugInfoBeforePass.DIFunctions.count(&F))
430 continue;
431
432 if (isFunctionSkipped(F))
433 continue;
434
435 // Stop collecting DI if the Functions number reached the limit.
436 if (++FunctionsCnt >= DebugifyFunctionsLimit)
437 break;
438 // Collect the DISubprogram.
439 auto *SP = F.getSubprogram();
440 DebugInfoBeforePass.DIFunctions.insert({&F, SP});
441 if (SP) {
442 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
443 for (const MDNode *DN : SP->getRetainedNodes()) {
444 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
445 DebugInfoBeforePass.DIVariables[DV] = 0;
446 }
447 }
448 }
449 if (DebugifyLevel > Level::Locations) {
450 for (BasicBlock &BB : F) {
451 // Collect debug variable records.
452 for (Instruction &I : BB) {
453 // PHIs have no variable records.
454 if (isa<PHINode>(I))
455 continue;
456 auto HandleDbgVariable = [&](DbgVariableRecord *DbgVar) {
457 if (!SP)
458 return;
459 // Skip inlined variables.
460 if (DbgVar->getDebugLoc().getInlinedAt())
461 return;
462 // Skip undef values.
463 if (DbgVar->isKillLocation())
464 return;
465
466 auto *Var = DbgVar->getVariable();
467 DebugInfoBeforePass.DIVariables[Var]++;
468 };
469 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
470 HandleDbgVariable(&DVR);
471 }
472 }
473 }
474 }
475
476 return true;
477}
478
479// This checks the preservation of original debug info attached to functions.
480static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
481 const DebugFnMap &DIFunctionsAfter,
482 StringRef NameOfWrappedPass,
483 StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
484 llvm::json::Array &Bugs) {
485 bool Preserved = true;
486 for (const auto &F : DIFunctionsAfter) {
487 if (F.second)
488 continue;
489 auto SPIt = DIFunctionsBefore.find(F.first);
490 if (SPIt == DIFunctionsBefore.end()) {
491 if (ShouldWriteIntoJSON)
492 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
493 {"name", F.first->getName()},
494 {"action", "not-generate"}}));
495 else
496 dbg() << "ERROR: " << NameOfWrappedPass
497 << " did not generate DISubprogram for " << F.first->getName()
498 << " from " << FileNameFromCU << '\n';
499 Preserved = false;
500 } else {
501 auto SP = SPIt->second;
502 if (!SP)
503 continue;
504 // If the function had the SP attached before the pass, consider it as
505 // a debug info bug.
506 if (ShouldWriteIntoJSON)
507 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
508 {"name", F.first->getName()},
509 {"action", "drop"}}));
510 else
511 dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
512 << F.first->getName() << " from " << FileNameFromCU << '\n';
513 Preserved = false;
514 }
515 }
516
517 return Preserved;
518}
519
521 StringRef NameOfWrappedPass,
522 StringRef FileNameFromCU,
523 bool ShouldWriteIntoJSON,
524 llvm::json::Array &Bugs) {
525 if (hasLoc(I))
526 return true;
527
528 Instruction *Instr = &I;
529 collectStackAddresses(I);
530 auto FnName = Instr->getFunction()->getName();
531 auto BB = Instr->getParent();
532 auto BBName = BB->hasName() ? BB->getName() : "no-name";
533 auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
534
535 auto CreateJSONBugEntry = [&](const char *Action) {
536 auto BugEntry = llvm::json::Object({
537 {"metadata", "DILocation"},
538 {"fn-name", FnName.str()},
539 {"bb-name", BBName.str()},
540 {"instr", InstName},
541 {"action", Action},
542 });
543#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
544 if (!Instr->getDebugLoc().getOriginStackTraces().empty())
545 BugEntry.insert({"origin", symbolizeStackTrace(Instr)});
546#endif
547 Bugs.push_back(std::move(BugEntry));
548 };
549
550 if (ShouldWriteIntoJSON)
551 CreateJSONBugEntry("not-generate");
552 else
553 dbg() << "WARNING: " << NameOfWrappedPass
554 << " did not generate DILocation for " << *Instr << " (BB: " << BBName
555 << ", Fn: " << FnName << ", File: " << FileNameFromCU << ")\n";
556 return false;
557}
558
559// This checks the preservation of original debug variable intrinsics.
560static bool checkVars(const DebugVarMap &DIVarsBefore,
561 const DebugVarMap &DIVarsAfter,
562 StringRef NameOfWrappedPass, StringRef FileNameFromCU,
563 bool ShouldWriteIntoJSON, llvm::json::Array &Bugs) {
564 bool Preserved = true;
565 for (const auto &V : DIVarsBefore) {
566 auto VarIt = DIVarsAfter.find(V.first);
567 if (VarIt == DIVarsAfter.end())
568 continue;
569
570 unsigned NumOfDbgValsAfter = VarIt->second;
571
572 if (V.second > NumOfDbgValsAfter) {
573 if (ShouldWriteIntoJSON)
575 {{"metadata", "dbg-var-intrinsic"},
576 {"name", V.first->getName()},
577 {"fn-name", V.first->getScope()->getSubprogram()->getName()},
578 {"action", "drop"}}));
579 else
580 dbg() << "WARNING: " << NameOfWrappedPass
581 << " drops dbg.value()/dbg.declare() for " << V.first->getName()
582 << " from "
583 << "function " << V.first->getScope()->getSubprogram()->getName()
584 << " (file " << FileNameFromCU << ")\n";
585 Preserved = false;
586 }
587 }
588
589 return Preserved;
590}
591
592// Write the json data into the specifed file.
593static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
594 StringRef FileNameFromCU, StringRef NameOfWrappedPass,
595 llvm::json::Array &Bugs) {
596 std::error_code EC;
597 raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
599 if (EC) {
600 errs() << "Could not open file: " << EC.message() << ", "
601 << OrigDIVerifyBugsReportFilePath << '\n';
602 return;
603 }
604
605 if (auto L = OS_FILE.lock()) {
606 OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
607
609 NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
610 OS_FILE << "\"pass\":\"" << PassName << "\", ";
611
612 llvm::json::Value BugsToPrint{std::move(Bugs)};
613 OS_FILE << "\"bugs\": " << BugsToPrint;
614
615 OS_FILE << "}\n";
616 }
617 OS_FILE.close();
618}
619
622 DebugInfoPerPass &DebugInfoBeforePass,
623 StringRef Banner, StringRef NameOfWrappedPass,
624 StringRef OrigDIVerifyBugsReportFilePath) {
625 LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
626 unsetDebugLocOriginCollection();
627
628 if (!M.getNamedMetadata("llvm.dbg.cu")) {
629 dbg() << Banner << ": Skipping module without debug info\n";
630 return false;
631 }
632
633 // Map the debug info holding DIs after a pass.
634 DebugInfoPerPass DebugInfoAfterPass;
635
636 bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
637
638 // TODO: The name of the module could be read better?
639 StringRef FileNameFromCU =
640 (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
641 ->getFilename();
643
644 bool ResultForInsts = true;
645
646 // Visit each instruction.
647 for (Function &F : Functions) {
648 if (isFunctionSkipped(F))
649 continue;
650
651 // Don't process functions without DI collected before the Pass.
652 if (!DebugInfoBeforePass.DIFunctions.count(&F))
653 continue;
654 // TODO: Collect metadata other than DISubprograms.
655 // Collect the DISubprogram.
656 auto *SP = F.getSubprogram();
657 DebugInfoAfterPass.DIFunctions.insert({&F, SP});
658
659 if (SP) {
660 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
661 for (const MDNode *DN : SP->getRetainedNodes()) {
662 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
663 DebugInfoAfterPass.DIVariables[DV] = 0;
664 }
665 }
666 }
667
668 for (BasicBlock &BB : F) {
669 // Collect debug locations (!dbg) and debug variable intrinsics.
670 for (Instruction &I : BB) {
671 // Skip PHIs.
672 if (isa<PHINode>(I))
673 continue;
674
675 // Collect dbg.values and dbg.declares.
676 if (DebugifyLevel > Level::Locations) {
677 auto HandleDbgVariable = [&](DbgVariableRecord *DbgVar) {
678 if (!SP)
679 return;
680 // Skip inlined variables.
681 if (DbgVar->getDebugLoc().getInlinedAt())
682 return;
683 // Skip undef values.
684 if (DbgVar->isKillLocation())
685 return;
686
687 auto *Var = DbgVar->getVariable();
688 DebugInfoAfterPass.DIVariables[Var]++;
689 };
690 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
691 HandleDbgVariable(&DVR);
692 }
693
694 LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
695
696 // Track the addresses to symbolize, if the feature is enabled.
697 bool InstResult = checkInstructionCoverage(
698 I, NameOfWrappedPass, FileNameFromCU, ShouldWriteIntoJSON, Bugs);
699 if (!InstResult)
700 I.setDebugLoc(DebugLoc::getUnknown());
701 ResultForInsts &= InstResult;
702 }
703 }
704 }
705
706 auto DIFunctionsBefore = DebugInfoBeforePass.DIFunctions;
707 auto DIFunctionsAfter = DebugInfoAfterPass.DIFunctions;
708
709 auto InstToDelete = DebugInfoBeforePass.InstToDelete;
710
711 auto DIVarsBefore = DebugInfoBeforePass.DIVariables;
712 auto DIVarsAfter = DebugInfoAfterPass.DIVariables;
713
714 bool ResultForFunc =
715 checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
716 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
717
718 bool ResultForVars = checkVars(DIVarsBefore, DIVarsAfter, NameOfWrappedPass,
719 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
720
721 bool Result = ResultForFunc && ResultForInsts && ResultForVars;
722
723 StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
724 if (ShouldWriteIntoJSON && !Bugs.empty())
725 writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
726 Bugs);
727
728 if (Result)
729 dbg() << ResultBanner << ": PASS\n";
730 else
731 dbg() << ResultBanner << ": FAIL\n";
732
733 // In the case of the `debugify-each`, no need to go over all the instructions
734 // again in the collectDebugInfoMetadata(), since as an input we can use
735 // the debugging information from the previous pass.
736 DebugInfoBeforePass = DebugInfoAfterPass;
737
738 LLVM_DEBUG(dbgs() << "\n\n");
739 return Result;
740}
741
742namespace {
743/// Return true if a mis-sized diagnostic is issued for \p DbgVal.
744template <typename DbgValTy>
745bool diagnoseMisSizedDbgValue(Module &M, DbgValTy *DbgVal) {
746 // The size of a dbg.value's value operand should match the size of the
747 // variable it corresponds to.
748 //
749 // TODO: This, along with a check for non-null value operands, should be
750 // promoted to verifier failures.
751
752 // For now, don't try to interpret anything more complicated than an empty
753 // DIExpression. Eventually we should try to handle OP_deref and fragments.
754 if (DbgVal->getExpression()->getNumElements())
755 return false;
756
757 Value *V = DbgVal->getVariableLocationOp(0);
758 if (!V)
759 return false;
760
761 Type *Ty = V->getType();
762 uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
763 std::optional<uint64_t> DbgVarSize = DbgVal->getFragmentSizeInBits();
764 if (!ValueOperandSize || !DbgVarSize)
765 return false;
766
767 bool HasBadSize = false;
768 if (Ty->isIntegerTy()) {
769 auto Signedness = DbgVal->getVariable()->getSignedness();
770 if (Signedness == DIBasicType::Signedness::Signed)
771 HasBadSize = ValueOperandSize < *DbgVarSize;
772 } else {
773 HasBadSize = ValueOperandSize != *DbgVarSize;
774 }
775
776 if (HasBadSize) {
777 dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
778 << ", but its variable has size " << *DbgVarSize << ": ";
779 DbgVal->print(dbg());
780 dbg() << "\n";
781 }
782 return HasBadSize;
783}
784
785bool checkDebugifyMetadata(Module &M,
787 StringRef NameOfWrappedPass, StringRef Banner,
788 bool Strip, DebugifyStatsMap *StatsMap) {
789 // Skip modules without debugify metadata.
790 NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
791 unsetDebugLocOriginCollection();
792 if (!NMD) {
793 dbg() << Banner << ": Skipping module without debugify metadata\n";
794 return false;
795 }
796
797 auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
799 ->getZExtValue();
800 };
801 assert(NMD->getNumOperands() == 2 &&
802 "llvm.debugify should have exactly 2 operands!");
803 unsigned OriginalNumLines = getDebugifyOperand(0);
804 unsigned OriginalNumVars = getDebugifyOperand(1);
805 bool HasErrors = false;
806
807 // Track debug info loss statistics if able.
808 DebugifyStatistics *Stats = nullptr;
809 if (StatsMap && !NameOfWrappedPass.empty())
810 Stats = &StatsMap->operator[](NameOfWrappedPass);
811
812 BitVector MissingLines{OriginalNumLines, true};
813 BitVector MissingVars{OriginalNumVars, true};
814 for (Function &F : Functions) {
815 if (isFunctionSkipped(F))
816 continue;
817
818 // Find missing lines.
819 for (Instruction &I : instructions(F)) {
820 auto DL = I.getDebugLoc();
821 if (DL && DL.getLine() != 0) {
822 MissingLines.reset(DL.getLine() - 1);
823 continue;
824 }
825
826 if (!isa<PHINode>(&I) && !DL) {
827 dbg() << "WARNING: Instruction with empty DebugLoc in function ";
828 dbg() << F.getName() << " --";
829 I.print(dbg());
830 dbg() << "\n";
831 }
832 }
833
834 // Find missing variables and mis-sized debug values.
835 auto CheckForMisSized = [&](auto *DbgVal) {
836 unsigned Var = ~0U;
837 (void)to_integer(DbgVal->getVariable()->getName(), Var, 10);
838 assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
839 bool HasBadSize = diagnoseMisSizedDbgValue(M, DbgVal);
840 if (!HasBadSize)
841 MissingVars.reset(Var - 1);
842 HasErrors |= HasBadSize;
843 };
844 for (Instruction &I : instructions(F)) {
845 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
846 if (DVR.isDbgValue() || DVR.isDbgAssign())
847 CheckForMisSized(&DVR);
848 }
849 }
850
851 // Print the results.
852 for (unsigned Idx : MissingLines.set_bits())
853 dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
854
855 for (unsigned Idx : MissingVars.set_bits())
856 dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
857
858 // Update DI loss statistics.
859 if (Stats) {
860 Stats->NumDbgLocsExpected += OriginalNumLines;
861 Stats->NumDbgLocsMissing += MissingLines.count();
862 Stats->NumDbgValuesExpected += OriginalNumVars;
863 Stats->NumDbgValuesMissing += MissingVars.count();
864 }
865
866 dbg() << Banner;
867 if (!NameOfWrappedPass.empty())
868 dbg() << " [" << NameOfWrappedPass << "]";
869 dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
870
871 // Strip debugify metadata if required.
872 bool Ret = false;
873 if (Strip)
874 Ret = stripDebugifyMetadata(M);
875
876 return Ret;
877}
878
879/// ModulePass for attaching synthetic debug info to everything, used with the
880/// legacy module pass manager.
881struct DebugifyModulePass : public ModulePass {
882 bool runOnModule(Module &M) override {
883 bool Result =
884 applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass);
885 return Result;
886 }
887
888 DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
889 StringRef NameOfWrappedPass = "",
890 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
891 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
892 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
893
894 void getAnalysisUsage(AnalysisUsage &AU) const override {
895 AU.setPreservesAll();
896 }
897
898 static char ID; // Pass identification.
899
900private:
901 StringRef NameOfWrappedPass;
902 DebugInfoPerPass *DebugInfoBeforePass;
903 enum DebugifyMode Mode;
904};
905
906/// FunctionPass for attaching synthetic debug info to instructions within a
907/// single function, used with the legacy module pass manager.
908struct DebugifyFunctionPass : public FunctionPass {
909 bool runOnFunction(Function &F) override {
910 bool Result =
911 applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass);
912 return Result;
913 }
914
915 DebugifyFunctionPass(
917 StringRef NameOfWrappedPass = "",
918 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
919 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
920 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
921
922 void getAnalysisUsage(AnalysisUsage &AU) const override {
923 AU.setPreservesAll();
924 }
925
926 static char ID; // Pass identification.
927
928private:
929 StringRef NameOfWrappedPass;
930 DebugInfoPerPass *DebugInfoBeforePass;
931 enum DebugifyMode Mode;
932};
933
934/// ModulePass for checking debug info inserted by -debugify, used with the
935/// legacy module pass manager.
936struct CheckDebugifyModulePass : public ModulePass {
937 bool runOnModule(Module &M) override {
938 bool Result;
940 Result = checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
941 "CheckModuleDebugify", Strip, StatsMap);
942 else
944 M, M.functions(), *DebugInfoBeforePass,
945 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
946 OrigDIVerifyBugsReportFilePath);
947
948 return Result;
949 }
950
951 CheckDebugifyModulePass(
952 bool Strip = false, StringRef NameOfWrappedPass = "",
953 DebugifyStatsMap *StatsMap = nullptr,
955 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
956 StringRef OrigDIVerifyBugsReportFilePath = "")
957 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
958 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
959 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
960 Strip(Strip) {}
961
962 void getAnalysisUsage(AnalysisUsage &AU) const override {
963 AU.setPreservesAll();
964 }
965
966 static char ID; // Pass identification.
967
968private:
969 StringRef NameOfWrappedPass;
970 StringRef OrigDIVerifyBugsReportFilePath;
971 DebugifyStatsMap *StatsMap;
972 DebugInfoPerPass *DebugInfoBeforePass;
973 enum DebugifyMode Mode;
974 bool Strip;
975};
976
977/// FunctionPass for checking debug info inserted by -debugify-function, used
978/// with the legacy module pass manager.
979struct CheckDebugifyFunctionPass : public FunctionPass {
980 bool runOnFunction(Function &F) override {
981 Module &M = *F.getParent();
982 auto FuncIt = F.getIterator();
983 bool Result;
985 Result = checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
986 NameOfWrappedPass, "CheckFunctionDebugify",
987 Strip, StatsMap);
988 else
990 M, make_range(FuncIt, std::next(FuncIt)), *DebugInfoBeforePass,
991 "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
992 OrigDIVerifyBugsReportFilePath);
993
994 return Result;
995 }
996
997 CheckDebugifyFunctionPass(
998 bool Strip = false, StringRef NameOfWrappedPass = "",
999 DebugifyStatsMap *StatsMap = nullptr,
1001 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
1002 StringRef OrigDIVerifyBugsReportFilePath = "")
1003 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
1004 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
1005 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
1006 Strip(Strip) {}
1007
1008 void getAnalysisUsage(AnalysisUsage &AU) const override {
1009 AU.setPreservesAll();
1010 }
1011
1012 static char ID; // Pass identification.
1013
1014private:
1015 StringRef NameOfWrappedPass;
1016 StringRef OrigDIVerifyBugsReportFilePath;
1017 DebugifyStatsMap *StatsMap;
1018 DebugInfoPerPass *DebugInfoBeforePass;
1019 enum DebugifyMode Mode;
1020 bool Strip;
1021};
1022
1023} // end anonymous namespace
1024
1026 std::error_code EC;
1027 raw_fd_ostream OS{Path, EC};
1028 if (EC) {
1029 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
1030 return;
1031 }
1032
1033 OS << "Pass Name" << ',' << "# of missing debug values" << ','
1034 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
1035 << "Missing/Expected location ratio" << '\n';
1036 for (const auto &Entry : Map) {
1037 StringRef Pass = Entry.first;
1038 DebugifyStatistics Stats = Entry.second;
1039
1040 OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
1041 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
1042 << Stats.getEmptyLocationRatio() << '\n';
1043 }
1044}
1045
1047 llvm::StringRef NameOfWrappedPass,
1048 DebugInfoPerPass *DebugInfoBeforePass) {
1050 return new DebugifyModulePass();
1051 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1052 return new DebugifyModulePass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
1053}
1054
1057 llvm::StringRef NameOfWrappedPass,
1058 DebugInfoPerPass *DebugInfoBeforePass) {
1060 return new DebugifyFunctionPass();
1061 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1062 return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
1063}
1064
1067 if (ApplyToMF) {
1068 auto ApplyToMFWrapper = [&](DIBuilder &DIB, Function &F) -> bool {
1069 return ApplyToMF(DIB, F, AM);
1070 };
1071 applyDebugifyMetadata(M, M.functions(),
1072 "ModuleDebugify: ", ApplyToMFWrapper);
1073 } else {
1074 applyDebugifyMetadata(M, M.functions(), "ModuleDebugify: ", nullptr);
1075 }
1076 } else {
1077 collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1078 "ModuleDebugify (original debuginfo)",
1079 NameOfWrappedPass);
1080 }
1081
1083 if (ApplyToMF)
1086 return PA;
1087}
1088
1090 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1091 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1092 StringRef OrigDIVerifyBugsReportFilePath) {
1094 return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
1095 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1096 return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
1097 DebugInfoBeforePass,
1098 OrigDIVerifyBugsReportFilePath);
1099}
1100
1102 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1103 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1104 StringRef OrigDIVerifyBugsReportFilePath) {
1106 return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
1107 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1108 return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
1109 DebugInfoBeforePass,
1110 OrigDIVerifyBugsReportFilePath);
1111}
1112
1116 checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
1117 "CheckModuleDebugify", Strip, StatsMap);
1118 else
1120 M, M.functions(), *DebugInfoBeforePass,
1121 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
1122 OrigDIVerifyBugsReportFilePath);
1123
1124 return PreservedAnalyses::all();
1125}
1126
1127static bool isIgnoredPass(StringRef PassID) {
1128 return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
1129 "AnalysisManagerProxy", "PrintFunctionPass",
1130 "PrintModulePass", "BitcodeWriterPass",
1131 "ThinLTOBitcodeWriterPass", "VerifierPass"});
1132}
1133
1136 PIC.registerBeforeNonSkippedPassCallback([this, &MAM](StringRef P, Any IR) {
1137 if (isIgnoredPass(P))
1138 return;
1141 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1142 Function &F = *const_cast<Function *>(*CF);
1143 applyDebugify(F, Mode, DebugInfoBeforePass, P);
1144 MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1145 .getManager()
1146 .invalidate(F, PA);
1147 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1148 Module &M = *const_cast<Module *>(*CM);
1149 applyDebugify(M, Mode, DebugInfoBeforePass, P);
1150 MAM.invalidate(M, PA);
1151 }
1152 });
1153 PIC.registerAfterPassCallback(
1154 [this, &MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1155 if (isIgnoredPass(P))
1156 return;
1159 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1160 auto &F = *const_cast<Function *>(*CF);
1161 Module &M = *F.getParent();
1162 auto It = F.getIterator();
1164 checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
1165 "CheckFunctionDebugify", /*Strip=*/true,
1166 DIStatsMap);
1167 else
1168 checkDebugInfoMetadata(M, make_range(It, std::next(It)),
1169 *DebugInfoBeforePass,
1170 "CheckModuleDebugify (original debuginfo)",
1171 P, OrigDIVerifyBugsReportFilePath);
1172 MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1173 .getManager()
1174 .invalidate(F, PA);
1175 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1176 Module &M = *const_cast<Module *>(*CM);
1178 checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
1179 /*Strip=*/true, DIStatsMap);
1180 else
1181 checkDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1182 "CheckModuleDebugify (original debuginfo)",
1183 P, OrigDIVerifyBugsReportFilePath);
1184 MAM.invalidate(M, PA);
1185 }
1186 });
1187}
1188
1189char DebugifyModulePass::ID = 0;
1191 "Attach debug info to everything");
1192
1193char CheckDebugifyModulePass::ID = 0;
1195 CDM("check-debugify", "Check debug info from -debugify");
1196
1197char DebugifyFunctionPass::ID = 0;
1198static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
1199 "Attach debug info to a function");
1200
1201char CheckDebugifyFunctionPass::ID = 0;
1203 CDF("check-debugify-function", "Check debug info from -debugify-function");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file implements the BitVector class.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static RegisterPass< CheckDebugifyModulePass > CDM("check-debugify", "Check debug info from -debugify")
ModulePass * createDebugifyModulePass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
bool hasLoc(const Instruction &I)
Definition Debugify.cpp:403
FunctionPass * createDebugifyFunctionPass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
static bool isIgnoredPass(StringRef PassID)
static bool applyDebugify(Function &F, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef NameOfWrappedPass="")
Definition Debugify.cpp:325
static bool checkInstructionCoverage(Instruction &I, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition Debugify.cpp:520
ModulePass * createCheckDebugifyModulePass(bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef OrigDIVerifyBugsReportFilePath)
static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath, StringRef FileNameFromCU, StringRef NameOfWrappedPass, llvm::json::Array &Bugs)
Definition Debugify.cpp:593
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:480
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)
static bool checkVars(const DebugVarMap &DIVarsBefore, const DebugVarMap &DIVarsAfter, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition Debugify.cpp:560
DebugifyMode
Used to check whether we track synthetic or original debug info.
Definition Debugify.h:96
@ SyntheticDebugInfo
Definition Debugify.h:96
@ OriginalDebugInfo
Definition Debugify.h:96
llvm::MapVector< const llvm::Function *, const llvm::DISubprogram * > DebugFnMap
Definition Debugify.h:29
llvm::MapVector< llvm::StringRef, DebugifyStatistics > DebugifyStatsMap
Map pass names to a per-pass DebugifyStatistics instance.
Definition Debugify.h:157
llvm::MapVector< const llvm::DILocalVariable *, unsigned > DebugVarMap
Definition Debugify.h:32
static bool runOnFunction(Function &F, bool PostInlining)
static SmallString< 128 > getFilename(const DIScope *SP, vfs::FileSystem &VFS)
Extract a filename for a DIScope.
Module.h This file contains the declarations for the Module class.
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:54
#define I(x, y, z)
Definition MD5.cpp:57
block placement Basic Block Placement Stats
Machine Check Debug Module
#define P(N)
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const char PassName[]
LLVM_ABI llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
LLVM_ABI llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:181
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI void finalize()
Construct any deferred debug info descriptors.
Definition DIBuilder.cpp:74
LLVM_ABI DISubroutineType * createSubroutineType(DITypeArray ParameterTypes, DINode::DIFlags Flags=DINode::FlagZero, unsigned CC=0)
Create subroutine type.
LLVM_ABI 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="", bool UseKeyInstructions=false)
Create a new descriptor for the specified subprogram.
LLVM_ABI DbgInstPtr insertDbgValueIntrinsic(llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, InsertPosition InsertPt)
Insert a new llvm.dbg.value intrinsic call.
LLVM_ABI DITypeArray getOrCreateTypeArray(ArrayRef< Metadata * > Elements)
Get a DITypeArray, create one if required.
LLVM_ABI DIBasicType * createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding, DINode::DIFlags Flags=DINode::FlagZero, uint32_t NumExtraInhabitants=0, uint32_t DataSizeInBits=0)
Create debugging information entry for a basic type.
LLVM_ABI DICompileUnit * createCompileUnit(DISourceLanguageName 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...
LLVM_ABI DIExpression * createExpression(ArrayRef< uint64_t > Addr={})
Create a new descriptor for the specified variable which has a complex address expression for its add...
LLVM_ABI 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.
LLVM_ABI 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.
Wrapper structure that holds source language identity metadata that includes language name,...
DISPFlags
Debug info subprogram flags.
Base class for types.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DILocation * get() const
Get the underlying DILocation.
Definition DebugLoc.h:220
static DebugLoc getUnknown()
Definition DebugLoc.h:153
LLVM_ABI void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const Function & getFunction() const
Definition Function.h:166
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:444
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const char * getOpcodeName() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
size_type count(const KeyT &Key) const
Definition MapVector.h:152
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
@ Warning
Emits a warning if two values disagree.
Definition Module.h:124
A tuple of MDNodes.
Definition Metadata.h:1753
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
iterator_range< op_iterator > operands()
Definition Metadata.h:1849
LLVM_ABI void addOperand(MDNode *M)
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:481
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool use_empty() const
Definition Value.h:346
static LLVM_ABI raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition WithColor.cpp:86
int getNumOccurrences() const
A range adaptor for a pair of iterators.
An Array is a JSON array, which contains heterogeneous JSON values.
Definition JSON.h:166
bool empty() const
Definition JSON.h:543
void push_back(const Value &E)
Definition JSON.h:548
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition JSON.h:98
std::pair< iterator, bool > insert(KV E)
Definition JSON.h:640
A Value is an JSON value of unknown type.
Definition JSON.h:291
A raw_ostream that writes to a file descriptor.
void close()
Manually flush the stream and close the file.
Expected< sys::fs::FileLocker > lock()
Locks the underlying file.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Changed
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:804
@ OF_Append
The file should be opened in append mode.
Definition FileSystem.h:807
This is an optimization pass for GlobalISel generic memory operations.
T any_cast(const Any &Value)
Definition Any.h:137
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition Format.h:122
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI bool stripDebugifyMetadata(Module &M)
Strip out all of the metadata and debug info inserted by debugify.
Definition Debugify.cpp:353
LLVM_ABI void exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map)
LLVM_ABI bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
LLVM_ABI 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:413
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI 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:620
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
@ DEBUG_METADATA_VERSION
Definition Metadata.h:54
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
Used to track the Debug Info Metadata information.
Definition Debugify.h:37
DebugFnMap DIFunctions
Definition Debugify.h:39
DebugVarMap DIVariables
Definition Debugify.h:44
WeakInstValueMap InstToDelete
Definition Debugify.h:42
Track how much debugify information (in the synthetic mode only) has been lost.
Definition Debugify.h:132
RegisterPass<t> template - This template class is used to notify the system that a Pass is available ...
Definition PassSupport.h:89