MachineDebugify.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. //===- MachineDebugify.cpp - Attach synthetic debug info to everything ----===//
  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 This pass attaches synthetic debug info to everything. It can be used
  10. /// to create targeted tests for debug info preservation, or test for CodeGen
  11. /// differences with vs. without debug info.
  12. ///
  13. /// This isn't intended to have feature parity with Debugify.
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/CodeGen/MachineInstrBuilder.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/Passes.h"
  21. #include "llvm/CodeGen/TargetInstrInfo.h"
  22. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/InitializePasses.h"
  25. #include "llvm/Transforms/Utils/Debugify.h"
  26. #define DEBUG_TYPE "mir-debugify"
  27. using namespace llvm;
  28. namespace {
  29. bool applyDebugifyMetadataToMachineFunction(MachineModuleInfo &MMI,
  30. DIBuilder &DIB, Function &F) {
  31. MachineFunction *MaybeMF = MMI.getMachineFunction(F);
  32. if (!MaybeMF)
  33. return false;
  34. MachineFunction &MF = *MaybeMF;
  35. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  36. DISubprogram *SP = F.getSubprogram();
  37. assert(SP && "IR Debugify just created it?");
  38. Module &M = *F.getParent();
  39. LLVMContext &Ctx = M.getContext();
  40. unsigned NextLine = SP->getLine();
  41. for (MachineBasicBlock &MBB : MF) {
  42. for (MachineInstr &MI : MBB) {
  43. // This will likely emit line numbers beyond the end of the imagined
  44. // source function and into subsequent ones. We don't do anything about
  45. // that as it doesn't really matter to the compiler where the line is in
  46. // the imaginary source code.
  47. MI.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
  48. }
  49. }
  50. // Find local variables defined by debugify. No attempt is made to match up
  51. // MIR-level regs to the 'correct' IR-level variables: there isn't a simple
  52. // way to do that, and it isn't necessary to find interesting CodeGen bugs.
  53. // Instead, simply keep track of one variable per line. Later, we can insert
  54. // DBG_VALUE insts that point to these local variables. Emitting DBG_VALUEs
  55. // which cover a wide range of lines can help stress the debug info passes:
  56. // if we can't do that, fall back to using the local variable which precedes
  57. // all the others.
  58. Function *DbgValF = M.getFunction("llvm.dbg.value");
  59. DbgValueInst *EarliestDVI = nullptr;
  60. DenseMap<unsigned, DILocalVariable *> Line2Var;
  61. DIExpression *Expr = nullptr;
  62. if (DbgValF) {
  63. for (const Use &U : DbgValF->uses()) {
  64. auto *DVI = dyn_cast<DbgValueInst>(U.getUser());
  65. if (!DVI || DVI->getFunction() != &F)
  66. continue;
  67. unsigned Line = DVI->getDebugLoc().getLine();
  68. assert(Line != 0 && "debugify should not insert line 0 locations");
  69. Line2Var[Line] = DVI->getVariable();
  70. if (!EarliestDVI || Line < EarliestDVI->getDebugLoc().getLine())
  71. EarliestDVI = DVI;
  72. Expr = DVI->getExpression();
  73. }
  74. }
  75. if (Line2Var.empty())
  76. return true;
  77. // Now, try to insert a DBG_VALUE instruction after each real instruction.
  78. // Do this by introducing debug uses of each register definition. If that is
  79. // not possible (e.g. we have a phi or a meta instruction), emit a constant.
  80. uint64_t NextImm = 0;
  81. SmallSet<DILocalVariable *, 16> VarSet;
  82. const MCInstrDesc &DbgValDesc = TII.get(TargetOpcode::DBG_VALUE);
  83. for (MachineBasicBlock &MBB : MF) {
  84. MachineBasicBlock::iterator FirstNonPHIIt = MBB.getFirstNonPHI();
  85. for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
  86. MachineInstr &MI = *I;
  87. ++I;
  88. // `I` may point to a DBG_VALUE created in the previous loop iteration.
  89. if (MI.isDebugInstr())
  90. continue;
  91. // It's not allowed to insert DBG_VALUEs after a terminator.
  92. if (MI.isTerminator())
  93. continue;
  94. // Find a suitable insertion point for the DBG_VALUE.
  95. auto InsertBeforeIt = MI.isPHI() ? FirstNonPHIIt : I;
  96. // Find a suitable local variable for the DBG_VALUE.
  97. unsigned Line = MI.getDebugLoc().getLine();
  98. if (!Line2Var.count(Line))
  99. Line = EarliestDVI->getDebugLoc().getLine();
  100. DILocalVariable *LocalVar = Line2Var[Line];
  101. assert(LocalVar && "No variable for current line?");
  102. VarSet.insert(LocalVar);
  103. // Emit DBG_VALUEs for register definitions.
  104. SmallVector<MachineOperand *, 4> RegDefs;
  105. for (MachineOperand &MO : MI.operands())
  106. if (MO.isReg() && MO.isDef() && MO.getReg())
  107. RegDefs.push_back(&MO);
  108. for (MachineOperand *MO : RegDefs)
  109. BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
  110. /*IsIndirect=*/false, *MO, LocalVar, Expr);
  111. // OK, failing that, emit a constant DBG_VALUE.
  112. if (RegDefs.empty()) {
  113. auto ImmOp = MachineOperand::CreateImm(NextImm++);
  114. BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
  115. /*IsIndirect=*/false, ImmOp, LocalVar, Expr);
  116. }
  117. }
  118. }
  119. // Here we save the number of lines and variables into "llvm.mir.debugify".
  120. // It is useful for mir-check-debugify.
  121. NamedMDNode *NMD = M.getNamedMetadata("llvm.mir.debugify");
  122. IntegerType *Int32Ty = Type::getInt32Ty(Ctx);
  123. if (!NMD) {
  124. NMD = M.getOrInsertNamedMetadata("llvm.mir.debugify");
  125. auto addDebugifyOperand = [&](unsigned N) {
  126. NMD->addOperand(MDNode::get(
  127. Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
  128. };
  129. // Add number of lines.
  130. addDebugifyOperand(NextLine - 1);
  131. // Add number of variables.
  132. addDebugifyOperand(VarSet.size());
  133. } else {
  134. assert(NMD->getNumOperands() == 2 &&
  135. "llvm.mir.debugify should have exactly 2 operands!");
  136. auto setDebugifyOperand = [&](unsigned Idx, unsigned N) {
  137. NMD->setOperand(Idx, MDNode::get(Ctx, ValueAsMetadata::getConstant(
  138. ConstantInt::get(Int32Ty, N))));
  139. };
  140. auto getDebugifyOperand = [&](unsigned Idx) {
  141. return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
  142. ->getZExtValue();
  143. };
  144. // Set number of lines.
  145. setDebugifyOperand(0, NextLine - 1);
  146. // Set number of variables.
  147. auto OldNumVars = getDebugifyOperand(1);
  148. setDebugifyOperand(1, OldNumVars + VarSet.size());
  149. }
  150. return true;
  151. }
  152. /// ModulePass for attaching synthetic debug info to everything, used with the
  153. /// legacy module pass manager.
  154. struct DebugifyMachineModule : public ModulePass {
  155. bool runOnModule(Module &M) override {
  156. // We will insert new debugify metadata, so erasing the old one.
  157. assert(!M.getNamedMetadata("llvm.mir.debugify") &&
  158. "llvm.mir.debugify metadata already exists! Strip it first");
  159. MachineModuleInfo &MMI =
  160. getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
  161. return applyDebugifyMetadata(
  162. M, M.functions(),
  163. "ModuleDebugify: ", [&](DIBuilder &DIB, Function &F) -> bool {
  164. return applyDebugifyMetadataToMachineFunction(MMI, DIB, F);
  165. });
  166. }
  167. DebugifyMachineModule() : ModulePass(ID) {}
  168. void getAnalysisUsage(AnalysisUsage &AU) const override {
  169. AU.addRequired<MachineModuleInfoWrapperPass>();
  170. AU.addPreserved<MachineModuleInfoWrapperPass>();
  171. AU.setPreservesCFG();
  172. }
  173. static char ID; // Pass identification.
  174. };
  175. char DebugifyMachineModule::ID = 0;
  176. } // end anonymous namespace
  177. INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE,
  178. "Machine Debugify Module", false, false)
  179. INITIALIZE_PASS_END(DebugifyMachineModule, DEBUG_TYPE,
  180. "Machine Debugify Module", false, false)
  181. ModulePass *llvm::createDebugifyMachineModulePass() {
  182. return new DebugifyMachineModule();
  183. }