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 
16 #include "llvm/Transforms/Utils/Debugify.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/InstIterator.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/PassInstrumentation.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/JSON.h"
30 
31 #define DEBUG_TYPE "debugify"
32 
33 using namespace llvm;
34 
35 namespace {
36 
37 cl::opt<bool> Quiet("debugify-quiet",
38                     cl::desc("Suppress verbose debugify output"));
39 
40 enum class Level {
41   Locations,
42   LocationsAndVariables
43 };
44 
45 // Used for the synthetic mode only.
46 cl::opt<Level> DebugifyLevel(
47     "debugify-level", cl::desc("Kind of debug info to add"),
48     cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
49                clEnumValN(Level::LocationsAndVariables, "location+variables",
50                           "Locations and Variables")),
51     cl::init(Level::LocationsAndVariables));
52 
53 raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
54 
55 uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
56   return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
57 }
58 
59 bool isFunctionSkipped(Function &F) {
60   return F.isDeclaration() || !F.hasExactDefinition();
61 }
62 
63 /// Find the basic block's terminating instruction.
64 ///
65 /// Special care is needed to handle musttail and deopt calls, as these behave
66 /// like (but are in fact not) terminators.
67 Instruction *findTerminatingInstruction(BasicBlock &BB) {
68   if (auto *I = BB.getTerminatingMustTailCall())
69     return I;
70   if (auto *I = BB.getTerminatingDeoptimizeCall())
71     return I;
72   return BB.getTerminator();
73 }
74 } // end anonymous namespace
75 
76 bool llvm::applyDebugifyMetadata(
77     Module &M, iterator_range<Module::iterator> Functions, StringRef Banner,
78     std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
79   // Skip modules with debug info.
80   if (M.getNamedMetadata("llvm.dbg.cu")) {
81     dbg() << Banner << "Skipping module with debug info\n";
82     return false;
83   }
84 
85   DIBuilder DIB(M);
86   LLVMContext &Ctx = M.getContext();
87   auto *Int32Ty = Type::getInt32Ty(Ctx);
88 
89   // Get a DIType which corresponds to Ty.
90   DenseMap<uint64_t, DIType *> TypeCache;
91   auto getCachedDIType = [&](Type *Ty) -> DIType * {
92     uint64_t Size = getAllocSizeInBits(M, Ty);
93     DIType *&DTy = TypeCache[Size];
94     if (!DTy) {
95       std::string Name = "ty" + utostr(Size);
96       DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
97     }
98     return DTy;
99   };
100 
101   unsigned NextLine = 1;
102   unsigned NextVar = 1;
103   auto File = DIB.createFile(M.getName(), "/");
104   auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
105                                   /*isOptimized=*/true, "", 0);
106 
107   // Visit each instruction.
108   for (Function &F : Functions) {
109     if (isFunctionSkipped(F))
110       continue;
111 
112     bool InsertedDbgVal = false;
113     auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
114     DISubprogram::DISPFlags SPFlags =
115         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
116     if (F.hasPrivateLinkage() || F.hasInternalLinkage())
117       SPFlags |= DISubprogram::SPFlagLocalToUnit;
118     auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
119                                  SPType, NextLine, DINode::FlagZero, SPFlags);
120     F.setSubprogram(SP);
121 
122     // Helper that inserts a dbg.value before \p InsertBefore, copying the
123     // location (and possibly the type, if it's non-void) from \p TemplateInst.
124     auto insertDbgVal = [&](Instruction &TemplateInst,
125                             Instruction *InsertBefore) {
126       std::string Name = utostr(NextVar++);
127       Value *V = &TemplateInst;
128       if (TemplateInst.getType()->isVoidTy())
129         V = ConstantInt::get(Int32Ty, 0);
130       const DILocation *Loc = TemplateInst.getDebugLoc().get();
131       auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
132                                              getCachedDIType(V->getType()),
133                                              /*AlwaysPreserve=*/true);
134       DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
135                                   InsertBefore);
136     };
137 
138     for (BasicBlock &BB : F) {
139       // Attach debug locations.
140       for (Instruction &I : BB)
141         I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
142 
143       if (DebugifyLevel < Level::LocationsAndVariables)
144         continue;
145 
146       // Inserting debug values into EH pads can break IR invariants.
147       if (BB.isEHPad())
148         continue;
149 
150       // Find the terminating instruction, after which no debug values are
151       // attached.
152       Instruction *LastInst = findTerminatingInstruction(BB);
153       assert(LastInst && "Expected basic block with a terminator");
154 
155       // Maintain an insertion point which can't be invalidated when updates
156       // are made.
157       BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
158       assert(InsertPt != BB.end() && "Expected to find an insertion point");
159       Instruction *InsertBefore = &*InsertPt;
160 
161       // Attach debug values.
162       for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
163         // Skip void-valued instructions.
164         if (I->getType()->isVoidTy())
165           continue;
166 
167         // Phis and EH pads must be grouped at the beginning of the block.
168         // Only advance the insertion point when we finish visiting these.
169         if (!isa<PHINode>(I) && !I->isEHPad())
170           InsertBefore = I->getNextNode();
171 
172         insertDbgVal(*I, InsertBefore);
173         InsertedDbgVal = true;
174       }
175     }
176     // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
177     // not have anything to work with as it goes about inserting DBG_VALUEs.
178     // (It's common for MIR tests to be written containing skeletal IR with
179     // empty functions -- we're still interested in debugifying the MIR within
180     // those tests, and this helps with that.)
181     if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
182       auto *Term = findTerminatingInstruction(F.getEntryBlock());
183       insertDbgVal(*Term, Term);
184     }
185     if (ApplyToMF)
186       ApplyToMF(DIB, F);
187     DIB.finalizeSubprogram(SP);
188   }
189   DIB.finalize();
190 
191   // Track the number of distinct lines and variables.
192   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
193   auto addDebugifyOperand = [&](unsigned N) {
194     NMD->addOperand(MDNode::get(
195         Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
196   };
197   addDebugifyOperand(NextLine - 1); // Original number of lines.
198   addDebugifyOperand(NextVar - 1);  // Original number of variables.
199   assert(NMD->getNumOperands() == 2 &&
200          "llvm.debugify should have exactly 2 operands!");
201 
202   // Claim that this synthetic debug info is valid.
203   StringRef DIVersionKey = "Debug Info Version";
204   if (!M.getModuleFlag(DIVersionKey))
205     M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
206 
207   return true;
208 }
209 
210 static bool
211 applyDebugify(Function &F,
212               enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
213               DebugInfoPerPassMap *DIPreservationMap = nullptr,
214               StringRef NameOfWrappedPass = "") {
215   Module &M = *F.getParent();
216   auto FuncIt = F.getIterator();
217   if (Mode == DebugifyMode::SyntheticDebugInfo)
218     return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
219                                  "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
220   assert(DIPreservationMap);
221   return collectDebugInfoMetadata(M, M.functions(), *DIPreservationMap,
222                                   "FunctionDebugify (original debuginfo)",
223                                   NameOfWrappedPass);
224 }
225 
226 static bool
227 applyDebugify(Module &M,
228               enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
229               DebugInfoPerPassMap *DIPreservationMap = nullptr,
230               StringRef NameOfWrappedPass = "") {
231   if (Mode == DebugifyMode::SyntheticDebugInfo)
232     return applyDebugifyMetadata(M, M.functions(),
233                                  "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
234   return collectDebugInfoMetadata(M, M.functions(), *DIPreservationMap,
235                                   "ModuleDebugify (original debuginfo)",
236                                   NameOfWrappedPass);
237 }
238 
239 bool llvm::stripDebugifyMetadata(Module &M) {
240   bool Changed = false;
241 
242   // Remove the llvm.debugify module-level named metadata.
243   NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
244   if (DebugifyMD) {
245     M.eraseNamedMetadata(DebugifyMD);
246     Changed = true;
247   }
248 
249   // Strip out all debug intrinsics and supporting metadata (subprograms, types,
250   // variables, etc).
251   Changed |= StripDebugInfo(M);
252 
253   // Strip out the dead dbg.value prototype.
254   Function *DbgValF = M.getFunction("llvm.dbg.value");
255   if (DbgValF) {
256     assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
257            "Not all debug info stripped?");
258     DbgValF->eraseFromParent();
259     Changed = true;
260   }
261 
262   // Strip out the module-level Debug Info Version metadata.
263   // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
264   NamedMDNode *NMD = M.getModuleFlagsMetadata();
265   if (!NMD)
266     return Changed;
267   SmallVector<MDNode *, 4> Flags(NMD->operands());
268   NMD->clearOperands();
269   for (MDNode *Flag : Flags) {
270     MDString *Key = dyn_cast_or_null<MDString>(Flag->getOperand(1));
271     if (Key->getString() == "Debug Info Version") {
272       Changed = true;
273       continue;
274     }
275     NMD->addOperand(Flag);
276   }
277   // If we left it empty we might as well remove it.
278   if (NMD->getNumOperands() == 0)
279     NMD->eraseFromParent();
280 
281   return Changed;
282 }
283 
284 bool llvm::collectDebugInfoMetadata(Module &M,
285                                     iterator_range<Module::iterator> Functions,
286                                     DebugInfoPerPassMap &DIPreservationMap,
287                                     StringRef Banner,
288                                     StringRef NameOfWrappedPass) {
289   LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
290 
291   // Clear the map with the debug info before every single pass.
292   DIPreservationMap.clear();
293 
294   if (!M.getNamedMetadata("llvm.dbg.cu")) {
295     dbg() << Banner << ": Skipping module without debug info\n";
296     return false;
297   }
298 
299   // Visit each instruction.
300   for (Function &F : Functions) {
301     if (isFunctionSkipped(F))
302       continue;
303 
304     // Collect the DISubprogram.
305     auto *SP = F.getSubprogram();
306     DIPreservationMap[NameOfWrappedPass].DIFunctions.insert({F.getName(), SP});
307     if (SP)
308       LLVM_DEBUG(dbgs() << "  Collecting subprogram: " << *SP << '\n');
309 
310     for (BasicBlock &BB : F) {
311       // Collect debug locations (!dbg).
312       // TODO: Collect dbg.values.
313       for (Instruction &I : BB) {
314         // Skip PHIs.
315         if (isa<PHINode>(I))
316           continue;
317 
318         // Skip debug instructions.
319         if (isa<DbgInfoIntrinsic>(&I))
320           continue;
321 
322         LLVM_DEBUG(dbgs() << "  Collecting info for inst: " << I << '\n');
323         DIPreservationMap[NameOfWrappedPass].InstToDelete.insert({&I, &I});
324 
325         const DILocation *Loc = I.getDebugLoc().get();
326         bool HasLoc = Loc != nullptr;
327         DIPreservationMap[NameOfWrappedPass].DILocations.insert({&I, HasLoc});
328       }
329     }
330   }
331 
332   return true;
333 }
334 
335 // This checks the preservation of original debug info attached to functions.
336 static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
337                            const DebugFnMap &DIFunctionsAfter,
338                            StringRef NameOfWrappedPass,
339                            StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
340                            llvm::json::Array &Bugs) {
341   bool Preserved = true;
342   for (const auto &F : DIFunctionsAfter) {
343     if (F.second)
344       continue;
345     auto SPIt = DIFunctionsBefore.find(F.first);
346     if (SPIt == DIFunctionsBefore.end()) {
347       if (ShouldWriteIntoJSON)
348         Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
349                                            {"name", F.first},
350                                            {"action", "not-generate"}}));
351       else
352         dbg() << "ERROR: " << NameOfWrappedPass
353               << " did not generate DISubprogram for " << F.first << " from "
354               << FileNameFromCU << '\n';
355       Preserved = false;
356     } else {
357       auto SP = SPIt->second;
358       if (!SP)
359         continue;
360       // If the function had the SP attached before the pass, consider it as
361       // a debug info bug.
362       if (ShouldWriteIntoJSON)
363         Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
364                                            {"name", F.first},
365                                            {"action", "drop"}}));
366       else
367         dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
368               << F.first << " from " << FileNameFromCU << '\n';
369       Preserved = false;
370     }
371   }
372 
373   return Preserved;
374 }
375 
376 // This checks the preservation of the original debug info attached to
377 // instructions.
378 static bool checkInstructions(const DebugInstMap &DILocsBefore,
379                               const DebugInstMap &DILocsAfter,
380                               const WeakInstValueMap &InstToDelete,
381                               StringRef NameOfWrappedPass,
382                               StringRef FileNameFromCU,
383                               bool ShouldWriteIntoJSON,
384                               llvm::json::Array &Bugs) {
385   bool Preserved = true;
386   for (const auto &L : DILocsAfter) {
387     if (L.second)
388       continue;
389     auto Instr = L.first;
390 
391     // In order to avoid pointer reuse/recycling, skip the values that might
392     // have been deleted during a pass.
393     auto WeakInstrPtr = InstToDelete.find(Instr);
394     if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second)
395       continue;
396 
397     auto FnName = Instr->getFunction()->getName();
398     auto BB = Instr->getParent();
399     auto BBName = BB->hasName() ? BB->getName() : "no-name";
400     auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
401 
402     auto InstrIt = DILocsBefore.find(Instr);
403     if (InstrIt == DILocsBefore.end()) {
404       if (ShouldWriteIntoJSON)
405         Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
406                                            {"fn-name", FnName.str()},
407                                            {"bb-name", BBName.str()},
408                                            {"instr", InstName},
409                                            {"action", "not-generate"}}));
410       else
411         dbg() << "WARNING: " << NameOfWrappedPass
412               << " did not generate DILocation for " << *Instr
413               << " (BB: " << BBName << ", Fn: " << FnName
414               << ", File: " << FileNameFromCU << ")\n";
415       Preserved = false;
416     } else {
417       if (!InstrIt->second)
418         continue;
419       // If the instr had the !dbg attached before the pass, consider it as
420       // a debug info issue.
421       if (ShouldWriteIntoJSON)
422         Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
423                                            {"fn-name", FnName.str()},
424                                            {"bb-name", BBName.str()},
425                                            {"instr", InstName},
426                                            {"action", "drop"}}));
427       else
428         dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of "
429               << *Instr << " (BB: " << BBName << ", Fn: " << FnName
430               << ", File: " << FileNameFromCU << ")\n";
431       Preserved = false;
432     }
433   }
434 
435   return Preserved;
436 }
437 
438 // Write the json data into the specifed file.
439 static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
440                       StringRef FileNameFromCU, StringRef NameOfWrappedPass,
441                       llvm::json::Array &Bugs) {
442   std::error_code EC;
443   raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
444                          sys::fs::OF_Append | sys::fs::OF_TextWithCRLF};
445   if (EC) {
446     errs() << "Could not open file: " << EC.message() << ", "
447            << OrigDIVerifyBugsReportFilePath << '\n';
448     return;
449   }
450 
451   OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
452 
453   StringRef PassName = NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
454   OS_FILE << "\"pass\":\"" << PassName << "\", ";
455 
456   llvm::json::Value BugsToPrint{std::move(Bugs)};
457   OS_FILE << "\"bugs\": " << BugsToPrint;
458 
459   OS_FILE << "}\n";
460 }
461 
462 bool llvm::checkDebugInfoMetadata(Module &M,
463                                   iterator_range<Module::iterator> Functions,
464                                   DebugInfoPerPassMap &DIPreservationMap,
465                                   StringRef Banner, StringRef NameOfWrappedPass,
466                                   StringRef OrigDIVerifyBugsReportFilePath) {
467   LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
468 
469   if (!M.getNamedMetadata("llvm.dbg.cu")) {
470     dbg() << Banner << ": Skipping module without debug info\n";
471     return false;
472   }
473 
474   // Map the debug info holding DIs after a pass.
475   DebugInfoPerPassMap DIPreservationAfter;
476 
477   // Visit each instruction.
478   for (Function &F : Functions) {
479     if (isFunctionSkipped(F))
480       continue;
481 
482     // TODO: Collect metadata other than DISubprograms.
483     // Collect the DISubprogram.
484     auto *SP = F.getSubprogram();
485     DIPreservationAfter[NameOfWrappedPass].DIFunctions.insert(
486         {F.getName(), SP});
487     if (SP)
488       LLVM_DEBUG(dbgs() << "  Collecting subprogram: " << *SP << '\n');
489 
490     for (BasicBlock &BB : F) {
491       // Collect debug locations (!dbg attachments).
492       // TODO: Collect dbg.values.
493       for (Instruction &I : BB) {
494         // Skip PHIs.
495         if (isa<PHINode>(I))
496           continue;
497 
498         // Skip debug instructions.
499         if (isa<DbgInfoIntrinsic>(&I))
500           continue;
501 
502         LLVM_DEBUG(dbgs() << "  Collecting info for inst: " << I << '\n');
503 
504         const DILocation *Loc = I.getDebugLoc().get();
505         bool HasLoc = Loc != nullptr;
506 
507         DIPreservationAfter[NameOfWrappedPass].DILocations.insert({&I, HasLoc});
508       }
509     }
510   }
511 
512   // TODO: The name of the module could be read better?
513   StringRef FileNameFromCU =
514       (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
515           ->getFilename();
516 
517   auto DIFunctionsBefore = DIPreservationMap[NameOfWrappedPass].DIFunctions;
518   auto DIFunctionsAfter = DIPreservationAfter[NameOfWrappedPass].DIFunctions;
519 
520   auto DILocsBefore = DIPreservationMap[NameOfWrappedPass].DILocations;
521   auto DILocsAfter = DIPreservationAfter[NameOfWrappedPass].DILocations;
522 
523   auto InstToDelete = DIPreservationAfter[NameOfWrappedPass].InstToDelete;
524 
525   bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
526   llvm::json::Array Bugs;
527 
528   bool ResultForFunc =
529       checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
530                      FileNameFromCU, ShouldWriteIntoJSON, Bugs);
531   bool ResultForInsts = checkInstructions(
532       DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass,
533       FileNameFromCU, ShouldWriteIntoJSON, Bugs);
534   bool Result = ResultForFunc && ResultForInsts;
535 
536   StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
537   if (ShouldWriteIntoJSON && !Bugs.empty())
538     writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
539               Bugs);
540 
541   if (Result)
542     dbg() << ResultBanner << ": PASS\n";
543   else
544     dbg() << ResultBanner << ": FAIL\n";
545 
546   LLVM_DEBUG(dbgs() << "\n\n");
547   return Result;
548 }
549 
550 namespace {
551 /// Return true if a mis-sized diagnostic is issued for \p DVI.
552 bool diagnoseMisSizedDbgValue(Module &M, DbgValueInst *DVI) {
553   // The size of a dbg.value's value operand should match the size of the
554   // variable it corresponds to.
555   //
556   // TODO: This, along with a check for non-null value operands, should be
557   // promoted to verifier failures.
558 
559   // For now, don't try to interpret anything more complicated than an empty
560   // DIExpression. Eventually we should try to handle OP_deref and fragments.
561   if (DVI->getExpression()->getNumElements())
562     return false;
563 
564   Value *V = DVI->getVariableLocationOp(0);
565   if (!V)
566     return false;
567 
568   Type *Ty = V->getType();
569   uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
570   Optional<uint64_t> DbgVarSize = DVI->getFragmentSizeInBits();
571   if (!ValueOperandSize || !DbgVarSize)
572     return false;
573 
574   bool HasBadSize = false;
575   if (Ty->isIntegerTy()) {
576     auto Signedness = DVI->getVariable()->getSignedness();
577     if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
578       HasBadSize = ValueOperandSize < *DbgVarSize;
579   } else {
580     HasBadSize = ValueOperandSize != *DbgVarSize;
581   }
582 
583   if (HasBadSize) {
584     dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
585           << ", but its variable has size " << *DbgVarSize << ": ";
586     DVI->print(dbg());
587     dbg() << "\n";
588   }
589   return HasBadSize;
590 }
591 
592 bool checkDebugifyMetadata(Module &M,
593                            iterator_range<Module::iterator> Functions,
594                            StringRef NameOfWrappedPass, StringRef Banner,
595                            bool Strip, DebugifyStatsMap *StatsMap) {
596   // Skip modules without debugify metadata.
597   NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
598   if (!NMD) {
599     dbg() << Banner << ": Skipping module without debugify metadata\n";
600     return false;
601   }
602 
603   auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
604     return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
605         ->getZExtValue();
606   };
607   assert(NMD->getNumOperands() == 2 &&
608          "llvm.debugify should have exactly 2 operands!");
609   unsigned OriginalNumLines = getDebugifyOperand(0);
610   unsigned OriginalNumVars = getDebugifyOperand(1);
611   bool HasErrors = false;
612 
613   // Track debug info loss statistics if able.
614   DebugifyStatistics *Stats = nullptr;
615   if (StatsMap && !NameOfWrappedPass.empty())
616     Stats = &StatsMap->operator[](NameOfWrappedPass);
617 
618   BitVector MissingLines{OriginalNumLines, true};
619   BitVector MissingVars{OriginalNumVars, true};
620   for (Function &F : Functions) {
621     if (isFunctionSkipped(F))
622       continue;
623 
624     // Find missing lines.
625     for (Instruction &I : instructions(F)) {
626       if (isa<DbgValueInst>(&I))
627         continue;
628 
629       auto DL = I.getDebugLoc();
630       if (DL && DL.getLine() != 0) {
631         MissingLines.reset(DL.getLine() - 1);
632         continue;
633       }
634 
635       if (!isa<PHINode>(&I) && !DL) {
636         dbg() << "WARNING: Instruction with empty DebugLoc in function ";
637         dbg() << F.getName() << " --";
638         I.print(dbg());
639         dbg() << "\n";
640       }
641     }
642 
643     // Find missing variables and mis-sized debug values.
644     for (Instruction &I : instructions(F)) {
645       auto *DVI = dyn_cast<DbgValueInst>(&I);
646       if (!DVI)
647         continue;
648 
649       unsigned Var = ~0U;
650       (void)to_integer(DVI->getVariable()->getName(), Var, 10);
651       assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
652       bool HasBadSize = diagnoseMisSizedDbgValue(M, DVI);
653       if (!HasBadSize)
654         MissingVars.reset(Var - 1);
655       HasErrors |= HasBadSize;
656     }
657   }
658 
659   // Print the results.
660   for (unsigned Idx : MissingLines.set_bits())
661     dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
662 
663   for (unsigned Idx : MissingVars.set_bits())
664     dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
665 
666   // Update DI loss statistics.
667   if (Stats) {
668     Stats->NumDbgLocsExpected += OriginalNumLines;
669     Stats->NumDbgLocsMissing += MissingLines.count();
670     Stats->NumDbgValuesExpected += OriginalNumVars;
671     Stats->NumDbgValuesMissing += MissingVars.count();
672   }
673 
674   dbg() << Banner;
675   if (!NameOfWrappedPass.empty())
676     dbg() << " [" << NameOfWrappedPass << "]";
677   dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
678 
679   // Strip debugify metadata if required.
680   if (Strip)
681     return stripDebugifyMetadata(M);
682 
683   return false;
684 }
685 
686 /// ModulePass for attaching synthetic debug info to everything, used with the
687 /// legacy module pass manager.
688 struct DebugifyModulePass : public ModulePass {
689   bool runOnModule(Module &M) override {
690     return applyDebugify(M, Mode, DIPreservationMap, NameOfWrappedPass);
691   }
692 
693   DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
694                      StringRef NameOfWrappedPass = "",
695                      DebugInfoPerPassMap *DIPreservationMap = nullptr)
696       : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
697         DIPreservationMap(DIPreservationMap), Mode(Mode) {}
698 
699   void getAnalysisUsage(AnalysisUsage &AU) const override {
700     AU.setPreservesAll();
701   }
702 
703   static char ID; // Pass identification.
704 
705 private:
706   StringRef NameOfWrappedPass;
707   DebugInfoPerPassMap *DIPreservationMap;
708   enum DebugifyMode Mode;
709 };
710 
711 /// FunctionPass for attaching synthetic debug info to instructions within a
712 /// single function, used with the legacy module pass manager.
713 struct DebugifyFunctionPass : public FunctionPass {
714   bool runOnFunction(Function &F) override {
715     return applyDebugify(F, Mode, DIPreservationMap, NameOfWrappedPass);
716   }
717 
718   DebugifyFunctionPass(
719       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
720       StringRef NameOfWrappedPass = "",
721       DebugInfoPerPassMap *DIPreservationMap = nullptr)
722       : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
723         DIPreservationMap(DIPreservationMap), Mode(Mode) {}
724 
725   void getAnalysisUsage(AnalysisUsage &AU) const override {
726     AU.setPreservesAll();
727   }
728 
729   static char ID; // Pass identification.
730 
731 private:
732   StringRef NameOfWrappedPass;
733   DebugInfoPerPassMap *DIPreservationMap;
734   enum DebugifyMode Mode;
735 };
736 
737 /// ModulePass for checking debug info inserted by -debugify, used with the
738 /// legacy module pass manager.
739 struct CheckDebugifyModulePass : public ModulePass {
740   bool runOnModule(Module &M) override {
741     if (Mode == DebugifyMode::SyntheticDebugInfo)
742       return checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
743                                    "CheckModuleDebugify", Strip, StatsMap);
744     return checkDebugInfoMetadata(
745         M, M.functions(), *DIPreservationMap,
746         "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
747         OrigDIVerifyBugsReportFilePath);
748   }
749 
750   CheckDebugifyModulePass(
751       bool Strip = false, StringRef NameOfWrappedPass = "",
752       DebugifyStatsMap *StatsMap = nullptr,
753       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
754       DebugInfoPerPassMap *DIPreservationMap = nullptr,
755       StringRef OrigDIVerifyBugsReportFilePath = "")
756       : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
757         OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
758         StatsMap(StatsMap), DIPreservationMap(DIPreservationMap), Mode(Mode),
759         Strip(Strip) {}
760 
761   void getAnalysisUsage(AnalysisUsage &AU) const override {
762     AU.setPreservesAll();
763   }
764 
765   static char ID; // Pass identification.
766 
767 private:
768   StringRef NameOfWrappedPass;
769   StringRef OrigDIVerifyBugsReportFilePath;
770   DebugifyStatsMap *StatsMap;
771   DebugInfoPerPassMap *DIPreservationMap;
772   enum DebugifyMode Mode;
773   bool Strip;
774 };
775 
776 /// FunctionPass for checking debug info inserted by -debugify-function, used
777 /// with the legacy module pass manager.
778 struct CheckDebugifyFunctionPass : public FunctionPass {
779   bool runOnFunction(Function &F) override {
780     Module &M = *F.getParent();
781     auto FuncIt = F.getIterator();
782     if (Mode == DebugifyMode::SyntheticDebugInfo)
783       return checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
784                                    NameOfWrappedPass, "CheckFunctionDebugify",
785                                    Strip, StatsMap);
786     return checkDebugInfoMetadata(
787         M, make_range(FuncIt, std::next(FuncIt)), *DIPreservationMap,
788         "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
789         OrigDIVerifyBugsReportFilePath);
790   }
791 
792   CheckDebugifyFunctionPass(
793       bool Strip = false, StringRef NameOfWrappedPass = "",
794       DebugifyStatsMap *StatsMap = nullptr,
795       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
796       DebugInfoPerPassMap *DIPreservationMap = nullptr,
797       StringRef OrigDIVerifyBugsReportFilePath = "")
798       : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
799         OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
800         StatsMap(StatsMap), DIPreservationMap(DIPreservationMap), Mode(Mode),
801         Strip(Strip) {}
802 
803   void getAnalysisUsage(AnalysisUsage &AU) const override {
804     AU.setPreservesAll();
805   }
806 
807   static char ID; // Pass identification.
808 
809 private:
810   StringRef NameOfWrappedPass;
811   StringRef OrigDIVerifyBugsReportFilePath;
812   DebugifyStatsMap *StatsMap;
813   DebugInfoPerPassMap *DIPreservationMap;
814   enum DebugifyMode Mode;
815   bool Strip;
816 };
817 
818 } // end anonymous namespace
819 
820 void llvm::exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map) {
821   std::error_code EC;
822   raw_fd_ostream OS{Path, EC};
823   if (EC) {
824     errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
825     return;
826   }
827 
828   OS << "Pass Name" << ',' << "# of missing debug values" << ','
829      << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
830      << "Missing/Expected location ratio" << '\n';
831   for (const auto &Entry : Map) {
832     StringRef Pass = Entry.first;
833     DebugifyStatistics Stats = Entry.second;
834 
835     OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
836        << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
837        << Stats.getEmptyLocationRatio() << '\n';
838   }
839 }
840 
841 ModulePass *createDebugifyModulePass(enum DebugifyMode Mode,
842                                      llvm::StringRef NameOfWrappedPass,
843                                      DebugInfoPerPassMap *DIPreservationMap) {
844   if (Mode == DebugifyMode::SyntheticDebugInfo)
845     return new DebugifyModulePass();
846   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
847   return new DebugifyModulePass(Mode, NameOfWrappedPass, DIPreservationMap);
848 }
849 
850 FunctionPass *
851 createDebugifyFunctionPass(enum DebugifyMode Mode,
852                            llvm::StringRef NameOfWrappedPass,
853                            DebugInfoPerPassMap *DIPreservationMap) {
854   if (Mode == DebugifyMode::SyntheticDebugInfo)
855     return new DebugifyFunctionPass();
856   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
857   return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DIPreservationMap);
858 }
859 
860 PreservedAnalyses NewPMDebugifyPass::run(Module &M, ModuleAnalysisManager &) {
861   applyDebugifyMetadata(M, M.functions(),
862                         "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
863   return PreservedAnalyses::all();
864 }
865 
866 ModulePass *createCheckDebugifyModulePass(
867     bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
868     enum DebugifyMode Mode, DebugInfoPerPassMap *DIPreservationMap,
869     StringRef OrigDIVerifyBugsReportFilePath) {
870   if (Mode == DebugifyMode::SyntheticDebugInfo)
871     return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
872   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
873   return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
874                                      DIPreservationMap,
875                                      OrigDIVerifyBugsReportFilePath);
876 }
877 
878 FunctionPass *createCheckDebugifyFunctionPass(
879     bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
880     enum DebugifyMode Mode, DebugInfoPerPassMap *DIPreservationMap,
881     StringRef OrigDIVerifyBugsReportFilePath) {
882   if (Mode == DebugifyMode::SyntheticDebugInfo)
883     return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
884   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
885   return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
886                                        DIPreservationMap,
887                                        OrigDIVerifyBugsReportFilePath);
888 }
889 
890 PreservedAnalyses NewPMCheckDebugifyPass::run(Module &M,
891                                               ModuleAnalysisManager &) {
892   checkDebugifyMetadata(M, M.functions(), "", "CheckModuleDebugify", false,
893                         nullptr);
894   return PreservedAnalyses::all();
895 }
896 
897 static bool isIgnoredPass(StringRef PassID) {
898   return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
899                                 "AnalysisManagerProxy", "PrintFunctionPass",
900                                 "PrintModulePass", "BitcodeWriterPass",
901                                 "ThinLTOBitcodeWriterPass", "VerifierPass"});
902 }
903 
904 void DebugifyEachInstrumentation::registerCallbacks(
905     PassInstrumentationCallbacks &PIC) {
906   PIC.registerBeforeNonSkippedPassCallback([](StringRef P, Any IR) {
907     if (isIgnoredPass(P))
908       return;
909     if (any_isa<const Function *>(IR))
910       applyDebugify(*const_cast<Function *>(any_cast<const Function *>(IR)));
911     else if (any_isa<const Module *>(IR))
912       applyDebugify(*const_cast<Module *>(any_cast<const Module *>(IR)));
913   });
914   PIC.registerAfterPassCallback([this](StringRef P, Any IR,
915                                        const PreservedAnalyses &PassPA) {
916     if (isIgnoredPass(P))
917       return;
918     if (any_isa<const Function *>(IR)) {
919       auto &F = *const_cast<Function *>(any_cast<const Function *>(IR));
920       Module &M = *F.getParent();
921       auto It = F.getIterator();
922       checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
923                             "CheckFunctionDebugify", /*Strip=*/true, &StatsMap);
924     } else if (any_isa<const Module *>(IR)) {
925       auto &M = *const_cast<Module *>(any_cast<const Module *>(IR));
926       checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
927                             /*Strip=*/true, &StatsMap);
928     }
929   });
930 }
931 
932 char DebugifyModulePass::ID = 0;
933 static RegisterPass<DebugifyModulePass> DM("debugify",
934                                            "Attach debug info to everything");
935 
936 char CheckDebugifyModulePass::ID = 0;
937 static RegisterPass<CheckDebugifyModulePass>
938     CDM("check-debugify", "Check debug info from -debugify");
939 
940 char DebugifyFunctionPass::ID = 0;
941 static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
942                                              "Attach debug info to a function");
943 
944 char CheckDebugifyFunctionPass::ID = 0;
945 static RegisterPass<CheckDebugifyFunctionPass>
946     CDF("check-debugify-function", "Check debug info from -debugify-function");
947