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