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