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