LLVM  14.0.0git
MachineDebugify.cpp
Go to the documentation of this file.
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/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/IR/DIBuilder.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/InitializePasses.h"
30 
31 #define DEBUG_TYPE "mir-debugify"
32 
33 using namespace llvm;
34 
35 namespace {
36 bool applyDebugifyMetadataToMachineFunction(MachineModuleInfo &MMI,
37  DIBuilder &DIB, Function &F) {
38  MachineFunction *MaybeMF = MMI.getMachineFunction(F);
39  if (!MaybeMF)
40  return false;
41  MachineFunction &MF = *MaybeMF;
43 
44  DISubprogram *SP = F.getSubprogram();
45  assert(SP && "IR Debugify just created it?");
46 
47  Module &M = *F.getParent();
48  LLVMContext &Ctx = M.getContext();
49 
50  unsigned NextLine = SP->getLine();
51  for (MachineBasicBlock &MBB : MF) {
52  for (MachineInstr &MI : MBB) {
53  // This will likely emit line numbers beyond the end of the imagined
54  // source function and into subsequent ones. We don't do anything about
55  // that as it doesn't really matter to the compiler where the line is in
56  // the imaginary source code.
57  MI.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
58  }
59  }
60 
61  // Find local variables defined by debugify. No attempt is made to match up
62  // MIR-level regs to the 'correct' IR-level variables: there isn't a simple
63  // way to do that, and it isn't necessary to find interesting CodeGen bugs.
64  // Instead, simply keep track of one variable per line. Later, we can insert
65  // DBG_VALUE insts that point to these local variables. Emitting DBG_VALUEs
66  // which cover a wide range of lines can help stress the debug info passes:
67  // if we can't do that, fall back to using the local variable which precedes
68  // all the others.
69  Function *DbgValF = M.getFunction("llvm.dbg.value");
70  DbgValueInst *EarliestDVI = nullptr;
72  DIExpression *Expr = nullptr;
73  if (DbgValF) {
74  for (const Use &U : DbgValF->uses()) {
75  auto *DVI = dyn_cast<DbgValueInst>(U.getUser());
76  if (!DVI || DVI->getFunction() != &F)
77  continue;
78  unsigned Line = DVI->getDebugLoc().getLine();
79  assert(Line != 0 && "debugify should not insert line 0 locations");
80  Line2Var[Line] = DVI->getVariable();
81  if (!EarliestDVI || Line < EarliestDVI->getDebugLoc().getLine())
82  EarliestDVI = DVI;
83  Expr = DVI->getExpression();
84  }
85  }
86  if (Line2Var.empty())
87  return true;
88 
89  // Now, try to insert a DBG_VALUE instruction after each real instruction.
90  // Do this by introducing debug uses of each register definition. If that is
91  // not possible (e.g. we have a phi or a meta instruction), emit a constant.
92  uint64_t NextImm = 0;
94  const MCInstrDesc &DbgValDesc = TII.get(TargetOpcode::DBG_VALUE);
95  for (MachineBasicBlock &MBB : MF) {
97  for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
98  MachineInstr &MI = *I;
99  ++I;
100 
101  // `I` may point to a DBG_VALUE created in the previous loop iteration.
102  if (MI.isDebugInstr())
103  continue;
104 
105  // It's not allowed to insert DBG_VALUEs after a terminator.
106  if (MI.isTerminator())
107  continue;
108 
109  // Find a suitable insertion point for the DBG_VALUE.
110  auto InsertBeforeIt = MI.isPHI() ? FirstNonPHIIt : I;
111 
112  // Find a suitable local variable for the DBG_VALUE.
113  unsigned Line = MI.getDebugLoc().getLine();
114  if (!Line2Var.count(Line))
115  Line = EarliestDVI->getDebugLoc().getLine();
116  DILocalVariable *LocalVar = Line2Var[Line];
117  assert(LocalVar && "No variable for current line?");
118  VarSet.insert(LocalVar);
119 
120  // Emit DBG_VALUEs for register definitions.
122  for (MachineOperand &MO : MI.operands())
123  if (MO.isReg() && MO.isDef() && MO.getReg())
124  RegDefs.push_back(&MO);
125  for (MachineOperand *MO : RegDefs)
126  BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
127  /*IsIndirect=*/false, *MO, LocalVar, Expr);
128 
129  // OK, failing that, emit a constant DBG_VALUE.
130  if (RegDefs.empty()) {
131  auto ImmOp = MachineOperand::CreateImm(NextImm++);
132  BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
133  /*IsIndirect=*/false, ImmOp, 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("llvm.mir.debugify");
142  if (!NMD) {
143  NMD = M.getOrInsertNamedMetadata("llvm.mir.debugify");
144  auto addDebugifyOperand = [&](unsigned N) {
145  NMD->addOperand(MDNode::get(
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) {
158  };
159  // Set number of lines.
160  setDebugifyOperand(0, NextLine - 1);
161  // Set number of variables.
162  setDebugifyOperand(1, VarSet.size());
163  }
164 
165  return true;
166 }
167 
168 /// ModulePass for attaching synthetic debug info to everything, used with the
169 /// legacy module pass manager.
170 struct DebugifyMachineModule : public ModulePass {
171  bool runOnModule(Module &M) override {
172  MachineModuleInfo &MMI =
173  getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
174  return applyDebugifyMetadata(
175  M, M.functions(),
176  "ModuleDebugify: ", [&](DIBuilder &DIB, Function &F) -> bool {
177  return applyDebugifyMetadataToMachineFunction(MMI, DIB, F);
178  });
179  }
180 
181  DebugifyMachineModule() : ModulePass(ID) {}
182 
183  void getAnalysisUsage(AnalysisUsage &AU) const override {
186  AU.setPreservesCFG();
187  }
188 
189  static char ID; // Pass identification.
190 };
192 
193 } // end anonymous namespace
194 
195 INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE,
196  "Machine Debugify Module", false, false)
197 INITIALIZE_PASS_END(DebugifyMachineModule, DEBUG_TYPE,
198  "Machine Debugify Module", false, false)
199 
201  return new DebugifyMachineModule();
202 }
Int32Ty
IntegerType * Int32Ty
Definition: NVVMIntrRange.cpp:67
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
DEBUG_TYPE
#define DEBUG_TYPE
Definition: MachineDebugify.cpp:31
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1421
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1120
llvm::ModulePass
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:238
IntrinsicInst.h
llvm::DIBuilder
Definition: DIBuilder.h:41
Debugify.h
llvm::Function
Definition: Function.h:62
llvm::TargetSubtargetInfo::getInstrInfo
virtual const TargetInstrInfo * getInstrInfo() const
Definition: TargetSubtargetInfo.h:92
llvm::lltok::LocalVar
@ LocalVar
Definition: LLToken.h:476
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
llvm::NamedMDNode::setOperand
void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1132
DenseMap.h
TargetInstrInfo.h
llvm::SmallSet
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::count
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:145
llvm::applyDebugifyMetadata
bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2596
llvm::Type::getInt32Ty
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:241
llvm::MDNode::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1233
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::NamedMDNode::addOperand
void addOperand(MDNode *M)
Definition: Metadata.cpp:1130
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:97
llvm::DbgValueInst
This represents the llvm.dbg.value instruction.
Definition: IntrinsicInst.h:347
llvm::MachineOperand::CreateImm
static MachineOperand CreateImm(int64_t Val)
Definition: MachineOperand.h:773
llvm::DILocalVariable
Local variable.
Definition: DebugInfoMetadata.h:3104
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::Value::uses
iterator_range< use_iterator > uses()
Definition: Value.h:376
false
Definition: StackSlotColoring.cpp:142
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:129
llvm::MCInstrDesc
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:195
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:49
llvm::IntegerType
Class to represent integer types.
Definition: DerivedTypes.h:40
llvm::MachineModuleInfo
This class contains meta information specific to a module.
Definition: MachineModuleInfo.h:78
llvm::ConstantInt::get
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:925
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:95
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
Passes.h
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:634
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
uint64_t
llvm::MachineModuleInfoWrapperPass
Definition: MachineModuleInfo.h:279
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
llvm::DenseMap
Definition: DenseMap.h:714
DebugInfo.h
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::MachineBasicBlock::getFirstNonPHI
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: MachineBasicBlock.cpp:199
DIBuilder.h
MachineFunctionPass.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MachineModuleInfo.h
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::MachineFunction
Definition: MachineFunction.h:234
getDebugLoc
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
Definition: MachineInstrBundle.cpp:109
llvm::AnalysisUsage::setPreservesCFG
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
TargetSubtargetInfo.h
llvm::ValueAsMetadata::getConstant
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:366
llvm::createDebugifyMachineModulePass
ModulePass * createDebugifyMachineModulePass()
Creates MIR Debugify pass.
Definition: MachineDebugify.cpp:200
llvm::SmallSet::insert
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:180
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::empty
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:97
MBB
MachineBasicBlock & MBB
Definition: AArch64SLSHardening.cpp:74
llvm::MachineModuleInfo::getMachineFunction
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
Definition: MachineModuleInfo.cpp:286
llvm::DebugLoc::getLine
unsigned getLine() const
Definition: DebugLoc.cpp:25
Machine
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:366
SmallVector.h
llvm::MachineBasicBlock::begin
iterator begin()
Definition: MachineBasicBlock.h:268
llvm::Instruction::getDebugLoc
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:370
MachineInstrBuilder.h
llvm::SmallSet::size
size_type size() const
Definition: SmallSet.h:159
llvm::BuildMI
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Definition: MachineInstrBuilder.h:328
N
#define N
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE, "Machine Debugify Module", false, false) INITIALIZE_PASS_END(DebugifyMachineModule
llvm::DISubprogram
Subprogram description.
Definition: DebugInfoMetadata.h:1826
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
llvm::MachineInstrBundleIterator< MachineInstr >
InitializePasses.h
llvm::MachineBasicBlock::end
iterator end()
Definition: MachineBasicBlock.h:270
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44
SmallSet.h
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38