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