1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
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 // Common functionality for different debug information format backends.
10 // LLVM currently supports DWARF and CodeView.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DebugHandlerBase.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/CommandLine.h"
25
26 using namespace llvm;
27
28 #define DEBUG_TYPE "dwarfdebug"
29
30 /// If true, we drop variable location ranges which exist entirely outside the
31 /// variable's lexical scope instruction ranges.
32 static cl::opt<bool> TrimVarLocs("trim-var-locs", cl::Hidden, cl::init(true));
33
34 Optional<DbgVariableLocation>
extractFromMachineInstruction(const MachineInstr & Instruction)35 DbgVariableLocation::extractFromMachineInstruction(
36 const MachineInstr &Instruction) {
37 DbgVariableLocation Location;
38 if (!Instruction.isDebugValue())
39 return None;
40 if (!Instruction.getDebugOperand(0).isReg())
41 return None;
42 Location.Register = Instruction.getDebugOperand(0).getReg();
43 Location.FragmentInfo.reset();
44 // We only handle expressions generated by DIExpression::appendOffset,
45 // which doesn't require a full stack machine.
46 int64_t Offset = 0;
47 const DIExpression *DIExpr = Instruction.getDebugExpression();
48 auto Op = DIExpr->expr_op_begin();
49 while (Op != DIExpr->expr_op_end()) {
50 switch (Op->getOp()) {
51 case dwarf::DW_OP_constu: {
52 int Value = Op->getArg(0);
53 ++Op;
54 if (Op != DIExpr->expr_op_end()) {
55 switch (Op->getOp()) {
56 case dwarf::DW_OP_minus:
57 Offset -= Value;
58 break;
59 case dwarf::DW_OP_plus:
60 Offset += Value;
61 break;
62 default:
63 continue;
64 }
65 }
66 } break;
67 case dwarf::DW_OP_plus_uconst:
68 Offset += Op->getArg(0);
69 break;
70 case dwarf::DW_OP_LLVM_fragment:
71 Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
72 break;
73 case dwarf::DW_OP_deref:
74 Location.LoadChain.push_back(Offset);
75 Offset = 0;
76 break;
77 default:
78 return None;
79 }
80 ++Op;
81 }
82
83 // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
84 // instruction.
85 // FIXME: Replace these with DIExpression.
86 if (Instruction.isIndirectDebugValue())
87 Location.LoadChain.push_back(Offset);
88
89 return Location;
90 }
91
DebugHandlerBase(AsmPrinter * A)92 DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
93
beginModule(Module * M)94 void DebugHandlerBase::beginModule(Module *M) {
95 if (M->debug_compile_units().empty())
96 Asm = nullptr;
97 }
98
99 // Each LexicalScope has first instruction and last instruction to mark
100 // beginning and end of a scope respectively. Create an inverse map that list
101 // scopes starts (and ends) with an instruction. One instruction may start (or
102 // end) multiple scopes. Ignore scopes that are not reachable.
identifyScopeMarkers()103 void DebugHandlerBase::identifyScopeMarkers() {
104 SmallVector<LexicalScope *, 4> WorkList;
105 WorkList.push_back(LScopes.getCurrentFunctionScope());
106 while (!WorkList.empty()) {
107 LexicalScope *S = WorkList.pop_back_val();
108
109 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
110 if (!Children.empty())
111 WorkList.append(Children.begin(), Children.end());
112
113 if (S->isAbstractScope())
114 continue;
115
116 for (const InsnRange &R : S->getRanges()) {
117 assert(R.first && "InsnRange does not have first instruction!");
118 assert(R.second && "InsnRange does not have second instruction!");
119 requestLabelBeforeInsn(R.first);
120 requestLabelAfterInsn(R.second);
121 }
122 }
123 }
124
125 // Return Label preceding the instruction.
getLabelBeforeInsn(const MachineInstr * MI)126 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
127 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
128 assert(Label && "Didn't insert label before instruction");
129 return Label;
130 }
131
132 // Return Label immediately following the instruction.
getLabelAfterInsn(const MachineInstr * MI)133 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
134 return LabelsAfterInsn.lookup(MI);
135 }
136
137 /// If this type is derived from a base type then return base type size.
getBaseTypeSize(const DIType * Ty)138 uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
139 assert(Ty);
140 const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
141 if (!DDTy)
142 return Ty->getSizeInBits();
143
144 unsigned Tag = DDTy->getTag();
145
146 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
147 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
148 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
149 return DDTy->getSizeInBits();
150
151 DIType *BaseType = DDTy->getBaseType();
152
153 if (!BaseType)
154 return 0;
155
156 // If this is a derived type, go ahead and get the base type, unless it's a
157 // reference then it's just the size of the field. Pointer types have no need
158 // of this since they're a different type of qualification on the type.
159 if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
160 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
161 return Ty->getSizeInBits();
162
163 return getBaseTypeSize(BaseType);
164 }
165
isUnsignedDIType(const DIType * Ty)166 bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) {
167 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
168 // FIXME: Enums without a fixed underlying type have unknown signedness
169 // here, leading to incorrectly emitted constants.
170 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
171 return false;
172
173 // (Pieces of) aggregate types that get hacked apart by SROA may be
174 // represented by a constant. Encode them as unsigned bytes.
175 return true;
176 }
177
178 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
179 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
180 // Encode pointer constants as unsigned bytes. This is used at least for
181 // null pointer constant emission.
182 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
183 // here, but accept them for now due to a bug in SROA producing bogus
184 // dbg.values.
185 if (T == dwarf::DW_TAG_pointer_type ||
186 T == dwarf::DW_TAG_ptr_to_member_type ||
187 T == dwarf::DW_TAG_reference_type ||
188 T == dwarf::DW_TAG_rvalue_reference_type)
189 return true;
190 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
191 T == dwarf::DW_TAG_volatile_type ||
192 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
193 assert(DTy->getBaseType() && "Expected valid base type");
194 return isUnsignedDIType(DTy->getBaseType());
195 }
196
197 auto *BTy = cast<DIBasicType>(Ty);
198 unsigned Encoding = BTy->getEncoding();
199 assert((Encoding == dwarf::DW_ATE_unsigned ||
200 Encoding == dwarf::DW_ATE_unsigned_char ||
201 Encoding == dwarf::DW_ATE_signed ||
202 Encoding == dwarf::DW_ATE_signed_char ||
203 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
204 Encoding == dwarf::DW_ATE_boolean ||
205 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
206 Ty->getName() == "decltype(nullptr)")) &&
207 "Unsupported encoding");
208 return Encoding == dwarf::DW_ATE_unsigned ||
209 Encoding == dwarf::DW_ATE_unsigned_char ||
210 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
211 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
212 }
213
hasDebugInfo(const MachineModuleInfo * MMI,const MachineFunction * MF)214 static bool hasDebugInfo(const MachineModuleInfo *MMI,
215 const MachineFunction *MF) {
216 if (!MMI->hasDebugInfo())
217 return false;
218 auto *SP = MF->getFunction().getSubprogram();
219 if (!SP)
220 return false;
221 assert(SP->getUnit());
222 auto EK = SP->getUnit()->getEmissionKind();
223 if (EK == DICompileUnit::NoDebug)
224 return false;
225 return true;
226 }
227
beginFunction(const MachineFunction * MF)228 void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
229 PrevInstBB = nullptr;
230
231 if (!Asm || !hasDebugInfo(MMI, MF)) {
232 skippedNonDebugFunction();
233 return;
234 }
235
236 // Grab the lexical scopes for the function, if we don't have any of those
237 // then we're not going to be able to do anything.
238 LScopes.initialize(*MF);
239 if (LScopes.empty()) {
240 beginFunctionImpl(MF);
241 return;
242 }
243
244 // Make sure that each lexical scope will have a begin/end label.
245 identifyScopeMarkers();
246
247 // Calculate history for local variables.
248 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
249 assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
250 calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
251 DbgValues, DbgLabels);
252 InstOrdering.initialize(*MF);
253 if (TrimVarLocs)
254 DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering);
255 LLVM_DEBUG(DbgValues.dump());
256
257 // Request labels for the full history.
258 for (const auto &I : DbgValues) {
259 const auto &Entries = I.second;
260 if (Entries.empty())
261 continue;
262
263 auto IsDescribedByReg = [](const MachineInstr *MI) {
264 return MI->getDebugOperand(0).isReg() && MI->getDebugOperand(0).getReg();
265 };
266
267 // The first mention of a function argument gets the CurrentFnBegin label,
268 // so arguments are visible when breaking at function entry.
269 //
270 // We do not change the label for values that are described by registers,
271 // as that could place them above their defining instructions. We should
272 // ideally not change the labels for constant debug values either, since
273 // doing that violates the ranges that are calculated in the history map.
274 // However, we currently do not emit debug values for constant arguments
275 // directly at the start of the function, so this code is still useful.
276 // FIXME: If the first mention of an argument is in a unique section basic
277 // block, we cannot always assign the CurrentFnBeginLabel as it lies in a
278 // different section. Temporarily, we disable generating loc list
279 // information or DW_AT_const_value when the block is in a different
280 // section.
281 const DILocalVariable *DIVar =
282 Entries.front().getInstr()->getDebugVariable();
283 if (DIVar->isParameter() &&
284 getDISubprogram(DIVar->getScope())->describes(&MF->getFunction()) &&
285 Entries.front().getInstr()->getParent()->sameSection(&MF->front())) {
286 if (!IsDescribedByReg(Entries.front().getInstr()))
287 LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
288 if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
289 // Mark all non-overlapping initial fragments.
290 for (auto I = Entries.begin(); I != Entries.end(); ++I) {
291 if (!I->isDbgValue())
292 continue;
293 const DIExpression *Fragment = I->getInstr()->getDebugExpression();
294 if (std::any_of(Entries.begin(), I,
295 [&](DbgValueHistoryMap::Entry Pred) {
296 return Pred.isDbgValue() &&
297 Fragment->fragmentsOverlap(
298 Pred.getInstr()->getDebugExpression());
299 }))
300 break;
301 // The code that generates location lists for DWARF assumes that the
302 // entries' start labels are monotonically increasing, and since we
303 // don't change the label for fragments that are described by
304 // registers, we must bail out when encountering such a fragment.
305 if (IsDescribedByReg(I->getInstr()))
306 break;
307 LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
308 }
309 }
310 }
311
312 for (const auto &Entry : Entries) {
313 if (Entry.isDbgValue())
314 requestLabelBeforeInsn(Entry.getInstr());
315 else
316 requestLabelAfterInsn(Entry.getInstr());
317 }
318 }
319
320 // Ensure there is a symbol before DBG_LABEL.
321 for (const auto &I : DbgLabels) {
322 const MachineInstr *MI = I.second;
323 requestLabelBeforeInsn(MI);
324 }
325
326 PrevInstLoc = DebugLoc();
327 PrevLabel = Asm->getFunctionBegin();
328 beginFunctionImpl(MF);
329 }
330
beginInstruction(const MachineInstr * MI)331 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
332 if (!Asm || !MMI->hasDebugInfo())
333 return;
334
335 assert(CurMI == nullptr);
336 CurMI = MI;
337
338 // Insert labels where requested.
339 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
340 LabelsBeforeInsn.find(MI);
341
342 // No label needed.
343 if (I == LabelsBeforeInsn.end())
344 return;
345
346 // Label already assigned.
347 if (I->second)
348 return;
349
350 if (!PrevLabel) {
351 PrevLabel = MMI->getContext().createTempSymbol();
352 Asm->OutStreamer->emitLabel(PrevLabel);
353 }
354 I->second = PrevLabel;
355 }
356
endInstruction()357 void DebugHandlerBase::endInstruction() {
358 if (!Asm || !MMI->hasDebugInfo())
359 return;
360
361 assert(CurMI != nullptr);
362 // Don't create a new label after DBG_VALUE and other instructions that don't
363 // generate code.
364 if (!CurMI->isMetaInstruction()) {
365 PrevLabel = nullptr;
366 PrevInstBB = CurMI->getParent();
367 }
368
369 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
370 LabelsAfterInsn.find(CurMI);
371 CurMI = nullptr;
372
373 // No label needed.
374 if (I == LabelsAfterInsn.end())
375 return;
376
377 // Label already assigned.
378 if (I->second)
379 return;
380
381 // We need a label after this instruction.
382 if (!PrevLabel) {
383 PrevLabel = MMI->getContext().createTempSymbol();
384 Asm->OutStreamer->emitLabel(PrevLabel);
385 }
386 I->second = PrevLabel;
387 }
388
endFunction(const MachineFunction * MF)389 void DebugHandlerBase::endFunction(const MachineFunction *MF) {
390 if (Asm && hasDebugInfo(MMI, MF))
391 endFunctionImpl(MF);
392 DbgValues.clear();
393 DbgLabels.clear();
394 LabelsBeforeInsn.clear();
395 LabelsAfterInsn.clear();
396 InstOrdering.clear();
397 }
398
beginBasicBlock(const MachineBasicBlock & MBB)399 void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) {
400 if (!MBB.isBeginSection())
401 return;
402
403 PrevLabel = MBB.getSymbol();
404 }
405
endBasicBlock(const MachineBasicBlock & MBB)406 void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) {
407 if (!MBB.isEndSection())
408 return;
409
410 PrevLabel = nullptr;
411 }
412