LLVM  8.0.1
DebugHandlerBase.cpp
Go to the documentation of this file.
1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Common functionality for different debug information format backends.
11 // LLVM currently supports DWARF and CodeView.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "dwarfdebug"
29 
32  const MachineInstr &Instruction) {
33  DbgVariableLocation Location;
34  if (!Instruction.isDebugValue())
35  return None;
36  if (!Instruction.getOperand(0).isReg())
37  return None;
38  Location.Register = Instruction.getOperand(0).getReg();
39  Location.FragmentInfo.reset();
40  // We only handle expressions generated by DIExpression::appendOffset,
41  // which doesn't require a full stack machine.
42  int64_t Offset = 0;
43  const DIExpression *DIExpr = Instruction.getDebugExpression();
44  auto Op = DIExpr->expr_op_begin();
45  while (Op != DIExpr->expr_op_end()) {
46  switch (Op->getOp()) {
47  case dwarf::DW_OP_constu: {
48  int Value = Op->getArg(0);
49  ++Op;
50  if (Op != DIExpr->expr_op_end()) {
51  switch (Op->getOp()) {
52  case dwarf::DW_OP_minus:
53  Offset -= Value;
54  break;
55  case dwarf::DW_OP_plus:
56  Offset += Value;
57  break;
58  default:
59  continue;
60  }
61  }
62  } break;
63  case dwarf::DW_OP_plus_uconst:
64  Offset += Op->getArg(0);
65  break;
67  Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
68  break;
69  case dwarf::DW_OP_deref:
70  Location.LoadChain.push_back(Offset);
71  Offset = 0;
72  break;
73  default:
74  return None;
75  }
76  ++Op;
77  }
78 
79  // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
80  // instruction.
81  // FIXME: Replace these with DIExpression.
82  if (Instruction.isIndirectDebugValue())
83  Location.LoadChain.push_back(Offset);
84 
85  return Location;
86 }
87 
89 
90 // Each LexicalScope has first instruction and last instruction to mark
91 // beginning and end of a scope respectively. Create an inverse map that list
92 // scopes starts (and ends) with an instruction. One instruction may start (or
93 // end) multiple scopes. Ignore scopes that are not reachable.
97  while (!WorkList.empty()) {
98  LexicalScope *S = WorkList.pop_back_val();
99 
100  const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
101  if (!Children.empty())
102  WorkList.append(Children.begin(), Children.end());
103 
104  if (S->isAbstractScope())
105  continue;
106 
107  for (const InsnRange &R : S->getRanges()) {
108  assert(R.first && "InsnRange does not have first instruction!");
109  assert(R.second && "InsnRange does not have second instruction!");
110  requestLabelBeforeInsn(R.first);
111  requestLabelAfterInsn(R.second);
112  }
113  }
114 }
115 
116 // Return Label preceding the instruction.
118  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
119  assert(Label && "Didn't insert label before instruction");
120  return Label;
121 }
122 
123 // Return Label immediately following the instruction.
125  return LabelsAfterInsn.lookup(MI);
126 }
127 
128 // Return the function-local offset of an instruction.
129 const MCExpr *
131  MCContext &MC = Asm->OutContext;
132 
133  MCSymbol *Start = Asm->getFunctionBegin();
134  const auto *StartRef = MCSymbolRefExpr::create(Start, MC);
135 
136  MCSymbol *AfterInsn = getLabelAfterInsn(MI);
137  assert(AfterInsn && "Expected label after instruction");
138  const auto *AfterRef = MCSymbolRefExpr::create(AfterInsn, MC);
139 
140  return MCBinaryExpr::createSub(AfterRef, StartRef, MC);
141 }
142 
143 /// If this type is derived from a base type then return base type size.
145  DIType *Ty = TyRef.resolve();
146  assert(Ty);
147  DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
148  if (!DDTy)
149  return Ty->getSizeInBits();
150 
151  unsigned Tag = DDTy->getTag();
152 
153  if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
154  Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
155  Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
156  return DDTy->getSizeInBits();
157 
158  DIType *BaseType = DDTy->getBaseType().resolve();
159 
160  if (!BaseType)
161  return 0;
162 
163  // If this is a derived type, go ahead and get the base type, unless it's a
164  // reference then it's just the size of the field. Pointer types have no need
165  // of this since they're a different type of qualification on the type.
166  if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
167  BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
168  return Ty->getSizeInBits();
169 
170  return getBaseTypeSize(BaseType);
171 }
172 
173 static bool hasDebugInfo(const MachineModuleInfo *MMI,
174  const MachineFunction *MF) {
175  if (!MMI->hasDebugInfo())
176  return false;
177  auto *SP = MF->getFunction().getSubprogram();
178  if (!SP)
179  return false;
180  assert(SP->getUnit());
181  auto EK = SP->getUnit()->getEmissionKind();
182  if (EK == DICompileUnit::NoDebug)
183  return false;
184  return true;
185 }
186 
188  PrevInstBB = nullptr;
189 
190  if (!Asm || !hasDebugInfo(MMI, MF)) {
192  return;
193  }
194 
195  // Grab the lexical scopes for the function, if we don't have any of those
196  // then we're not going to be able to do anything.
197  LScopes.initialize(*MF);
198  if (LScopes.empty()) {
199  beginFunctionImpl(MF);
200  return;
201  }
202 
203  // Make sure that each lexical scope will have a begin/end label.
205 
206  // Calculate history for local variables.
207  assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
208  assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
212 
213  // Request labels for the full history.
214  for (const auto &I : DbgValues) {
215  const auto &Ranges = I.second;
216  if (Ranges.empty())
217  continue;
218 
219  // The first mention of a function argument gets the CurrentFnBegin
220  // label, so arguments are visible when breaking at function entry.
221  const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable();
222  if (DIVar->isParameter() &&
223  getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
224  LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
225  if (Ranges.front().first->getDebugExpression()->isFragment()) {
226  // Mark all non-overlapping initial fragments.
227  for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
228  const DIExpression *Fragment = I->first->getDebugExpression();
229  if (std::all_of(Ranges.begin(), I,
231  return !Fragment->fragmentsOverlap(
232  Pred.first->getDebugExpression());
233  }))
234  LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
235  else
236  break;
237  }
238  }
239  }
240 
241  for (const auto &Range : Ranges) {
242  requestLabelBeforeInsn(Range.first);
243  if (Range.second)
244  requestLabelAfterInsn(Range.second);
245  }
246  }
247 
248  // Ensure there is a symbol before DBG_LABEL.
249  for (const auto &I : DbgLabels) {
250  const MachineInstr *MI = I.second;
252  }
253 
254  PrevInstLoc = DebugLoc();
256  beginFunctionImpl(MF);
257 }
258 
260  if (!MMI->hasDebugInfo())
261  return;
262 
263  assert(CurMI == nullptr);
264  CurMI = MI;
265 
266  // Insert labels where requested.
268  LabelsBeforeInsn.find(MI);
269 
270  // No label needed.
271  if (I == LabelsBeforeInsn.end())
272  return;
273 
274  // Label already assigned.
275  if (I->second)
276  return;
277 
278  if (!PrevLabel) {
280  Asm->OutStreamer->EmitLabel(PrevLabel);
281  }
282  I->second = PrevLabel;
283 }
284 
286  if (!MMI->hasDebugInfo())
287  return;
288 
289  assert(CurMI != nullptr);
290  // Don't create a new label after DBG_VALUE and other instructions that don't
291  // generate code.
292  if (!CurMI->isMetaInstruction()) {
293  PrevLabel = nullptr;
295  }
296 
298  LabelsAfterInsn.find(CurMI);
299  CurMI = nullptr;
300 
301  // No label needed.
302  if (I == LabelsAfterInsn.end())
303  return;
304 
305  // Label already assigned.
306  if (I->second)
307  return;
308 
309  // We need a label after this instruction.
310  if (!PrevLabel) {
312  Asm->OutStreamer->EmitLabel(PrevLabel);
313  }
314  I->second = PrevLabel;
315 }
316 
318  if (hasDebugInfo(MMI, MF))
319  endFunctionImpl(MF);
320  DbgValues.clear();
321  DbgLabels.clear();
322  LabelsBeforeInsn.clear();
323  LabelsAfterInsn.clear();
324 }
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:94
bool hasDebugInfo() const
Returns true if valid debug info is present.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:323
This class represents lattice values for constants.
Definition: AllocatorList.h:24
bool isAbstractScope() const
Definition: LexicalScopes.h:65
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:89
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void push_back(const T &Elt)
Definition: SmallVector.h:218
unsigned getReg() const
getReg - Returns the register number.
SmallVectorImpl< InsnRange > & getRanges()
Definition: LexicalScopes.h:67
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1186
A debug info location.
Definition: DebugLoc.h:34
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:97
bool isMetaInstruction() const
Return true if this instruction doesn&#39;t produce any output in the form of executable instructions...
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:45
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we&#39;re processing.
void calculateDbgEntityHistory(const MachineFunction *MF, const TargetRegisterInfo *TRI, DbgValueHistoryMap &DbgValues, DbgLabelInstrMap &DbgLabels)
DebugLoc PrevInstLoc
Previous instruction&#39;s location information.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
const MCExpr * getFunctionLocalOffsetAfterInsn(const MachineInstr *MI)
Return the function-local offset of an instruction.
SmallVectorImpl< LexicalScope * > & getChildren()
Definition: LexicalScopes.h:66
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
unsigned getTag() const
expr_op_iterator expr_op_begin() const
Visit the elements via ExprOperand wrappers.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
void beginFunction(const MachineFunction *MF) override
Gather pre-function debug information.
Only used in LLVM metadata.
Definition: Dwarf.h:133
uint64_t getSizeInBits() const
Holds a subclass of DINode.
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Definition: DebugInfo.cpp:44
Context object for machine code objects.
Definition: MCContext.h:63
DebugHandlerBase(AsmPrinter *A)
expr_op_iterator expr_op_end() const
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:546
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:212
void identifyScopeMarkers()
Indentify instructions that are marking the beginning of or ending of a scope.
void initialize(const MachineFunction &)
initialize - Scan machine function and constuct lexical scope nest, resets the instance if necessary...
const MCContext & getContext() const
virtual void endFunctionImpl(const MachineFunction *MF)=0
DenseMap< const MachineInstr *, MCSymbol * > LabelsAfterInsn
Maps instruction with label emitted after instruction.
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:576
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:217
const MachineBasicBlock * PrevInstBB
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
AsmPrinter * Asm
Target of debug info emission.
llvm::Optional< llvm::DIExpression::FragmentInfo > FragmentInfo
Present if the location is part of a larger variable.
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:79
DenseMap< const MachineInstr *, MCSymbol * > LabelsBeforeInsn
Maps instruction with label emitted before instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void endFunction(const MachineFunction *MF) override
Gather post-function debug information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
virtual void skippedNonDebugFunction()
Represents the location at which a variable is stored.
virtual void beginFunctionImpl(const MachineFunction *MF)=0
static Optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
Base class for types.
static bool hasDebugInfo(const MachineModuleInfo *MMI, const MachineFunction *MF)
bool isDebugValue() const
Definition: MachineInstr.h:997
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool fragmentsOverlap(const DIExpression *Other) const
Check if fragments overlap between this DIExpression and Other.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:394
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:254
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
Representation of each machine instruction.
Definition: MachineInstr.h:64
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
#define I(x, y, z)
Definition: MD5.cpp:58
std::pair< const MachineInstr *, const MachineInstr * > InstrRange
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void endInstruction() override
Process end of an instruction.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void reset()
Definition: Optional.h:151
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< int64_t, 1 > LoadChain
Chain of offsetted loads necessary to load the value if it lives in memory.
LLVM Value Representation.
Definition: Value.h:73
MachineModuleInfo * MMI
Collected machine module information.
static uint64_t getBaseTypeSize(const DITypeRef TyRef)
If this type is derived from a base type then return base type size.
IRTranslator LLVM IR MI
unsigned Register
Base register.
DILocalScope * getScope() const
Get the local scope for this variable.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
LLVM_DUMP_METHOD void dump() const
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the first operand is a register and the second operand is an immediate...
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
Definition: LexicalScopes.h:40
bool empty()
empty - Return true if there is any lexical scope information available.
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
This class contains meta information specific to a module.