Debugify.cpp 37 KB

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